Advertisement
p_vasilevss

Untitled

Nov 25th, 2023
760
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const buildOptions = (data) => {
  2.     const options = {};
  3.  
  4.     if (data) {
  5.         options.headers = {
  6.             'content-type': 'application/json'
  7.         };
  8.         options.body = JSON.stringify(data);
  9.     };
  10.  
  11.     const token = localStorage.getItem('accessToken');
  12.  
  13.     if (token) {
  14.         options.headers = {
  15.             ...options.headers,
  16.             'X-Authorization':  {token},
  17.         };
  18.     }
  19.     return options;
  20. }
  21.  
  22. const request = async (method, url, data) => {
  23.     const response = await fetch(url, { //тук гърми на url
  24.         ...buildOptions(data),
  25.         method,
  26.     });
  27.  
  28.     if (response.status === 204) {
  29.         return {};
  30.     }
  31.  
  32.     const result = await response.json();
  33.  
  34.     if (!response.ok) {
  35.         throw result;
  36.     }
  37.  
  38.     return result;
  39. };
  40.  
  41. export const get = request.bind(null, 'GET');
  42. export const post = request.bind(null, 'POST');
  43. export const put = request.bind(null, 'PUT');
  44. export const patch = request.bind(null, 'PATCH');
  45. export const del = request.bind(null, 'DELETE');
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement