Advertisement
bebo231312312321

Untitled

Sep 17th, 2024
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import AsyncStorage from '@react-native-async-storage/async-storage';
  2.  
  3. // To be moved to .env file
  4. const baseUrl = 'https://harmonix.emage.co.uk/api';
  5.  
  6. async function request(method, endpoint, params, requiresAuth = true) {
  7.   const options = {
  8.     method,
  9.     headers: {},
  10.   };
  11.  
  12.   if (params) {
  13.     options.headers['Content-Type'] = 'application/json';
  14.     options.body = JSON.stringify(params);
  15.   }
  16.  
  17.   if (requiresAuth) {
  18.     try {
  19.       const token = await AsyncStorage.getItem('userToken');
  20.       if (token) {
  21.         options.headers['Authorization'] = `Bearer ${token}`;
  22.       }
  23.     } catch (error) {
  24.       console.error('Error retrieving token:', error);
  25.     }
  26.   }
  27.  
  28.   try {
  29.     let response = await fetch(baseUrl + endpoint, options);
  30.     let data = null;
  31.  
  32.     if (response.status !== 204) {
  33.       const contentType = response.headers.get("content-type");
  34.       if (contentType && contentType.indexOf("application/json") !== -1) {
  35.         data = await response.json();
  36.       } else {
  37.         data = await response.text();
  38.       }
  39.     }
  40.  
  41.     if (!response.ok) {
  42.       throw new Error(typeof data === 'string' ? data : JSON.stringify(data));
  43.     }
  44.  
  45.     return data;
  46.   } catch (error) {
  47.     console.error('Error making request:', error.message);
  48.     throw error;
  49.   }
  50. }
  51.  
  52. export const get = (endpoint, requiresAuth = true) => request('GET', endpoint, null, requiresAuth);
  53. export const post = (endpoint, params, requiresAuth = true) => request('POST', endpoint, params, requiresAuth);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement