fetchWrappers.tsx 1.3 KB

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