fetchWrappers.tsx54 lines · main
| 1 | import { getAccessToken } from './auth' |
| 2 | |
| 3 | interface DataProps { |
| 4 | [prop: string]: any |
| 5 | } |
| 6 | |
| 7 | export async function get(url: string, options = {} as { [key: string]: any }) { |
| 8 | const { headers: optionHeaders, ...otherOptions } = options |
| 9 | |
| 10 | const accessToken = await getAccessToken() |
| 11 | |
| 12 | let headers = new Headers({ |
| 13 | 'Content-Type': 'application/json', |
| 14 | Accept: 'application/json', |
| 15 | ...(accessToken && { Authorization: `Bearer ${accessToken}` }), |
| 16 | ...optionHeaders, |
| 17 | }) |
| 18 | |
| 19 | return fetch(url, { |
| 20 | method: 'GET', |
| 21 | headers, |
| 22 | credentials: 'include', |
| 23 | referrerPolicy: 'no-referrer-when-downgrade', |
| 24 | ...otherOptions, |
| 25 | }) |
| 26 | .then((res) => res.json()) |
| 27 | .catch((error) => { |
| 28 | throw error |
| 29 | }) |
| 30 | } |
| 31 | |
| 32 | export async function post(url: string, data: DataProps, options = {} as { [key: string]: any }) { |
| 33 | const { headers: optionHeaders, ...otherOptions } = options |
| 34 | |
| 35 | const accessToken = await getAccessToken() |
| 36 | |
| 37 | let headers = new Headers({ |
| 38 | 'Content-Type': 'application/json', |
| 39 | Accept: 'application/json', |
| 40 | ...(accessToken && { Authorization: `Bearer ${accessToken}` }), |
| 41 | ...optionHeaders, |
| 42 | }) |
| 43 | |
| 44 | return fetch(url, { |
| 45 | method: 'POST', |
| 46 | headers, |
| 47 | credentials: 'include', |
| 48 | referrerPolicy: 'no-referrer-when-downgrade', |
| 49 | body: JSON.stringify(data), |
| 50 | ...otherOptions, |
| 51 | }).catch((error) => { |
| 52 | throw error |
| 53 | }) |
| 54 | } |