bebo231312312321

Untitled

Sep 1st, 2024
42
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { handle401Error } from '../../utils/handle401Error';
  2. import { refreshToken } from '../../utils/refreshToken';
  3.  
  4. const requester = async (method, url, data) => {
  5.   const options = {
  6.     credentials: 'include',
  7.   };
  8.  
  9.   if (method !== 'GET') {
  10.     options.method = method;
  11.  
  12.     if (data) {
  13.       options.headers = {
  14.         'content-type': 'application/json',
  15.       };
  16.  
  17.       options.body = JSON.stringify(data);
  18.     }
  19.   }
  20.  
  21.   const serializedAuth = localStorage.getItem('auth');
  22.   if (serializedAuth) {
  23.     const auth = JSON.parse(serializedAuth);
  24.     if (auth.token) {
  25.       const accessToken = await refreshToken(auth);
  26.       if (!accessToken) return window.location.replace('/sign-up');
  27.       options.headers = {
  28.         ...options.headers,
  29.         Authorization: `Bearer ${accessToken}`,
  30.       };
  31.     }
  32.   }
  33.  
  34.   const response = await fetch(url, options);
  35.  
  36.   const result = await response.json();
  37.   if (response.status === 401) {
  38.     handle401Error();
  39.  
  40.   }
  41.   if (!response.ok) {
  42.     if (response.status === 401) return window.location.replace('/sign-up');
  43.     throw result;
  44.   }
  45.  
  46.   return result;
  47. };
  48.  
  49. export const requestFactory = () => {
  50.   return {
  51.     get: requester.bind(null, 'GET'),
  52.     post: requester.bind(null, 'POST'),
  53.     put: requester.bind(null, 'PUT'),
  54.     patch: requester.bind(null, 'PATCH'),
  55.     del: requester.bind(null, 'DELETE'),
  56.   };
  57. };
  58.  
Add Comment
Please, Sign In to add comment