// @ts-nocheck import { API_URL } from "react-native-dotenv"; import { getConfig } from "../config"; type FetchMethod = "GET" | "POST" | "PUT" | "DELETE"; export interface FetchRequest { url: string; headers: any; method: FetchMethod; body?: any; } type Interceptor = (request: FetchRequest) => FetchRequest; class FetchService { interceptors: Interceptor[] = []; private request(url: string, request: Omit) { if (request.body) { request = { ...request, body: JSON.stringify(request.body), }; } return fetch(url, request).then((response) => { if (response.ok) { let result; try { result = response.json(); } catch (e) { throw e; } return result; } else if (!response.ok) { return response .json() .catch(() => { // Couldn't parse the JSON throw new Error(`Error: ${response.status}`); }) .then(({ message }) => { // Got valid JSON with error response, use it throw new Error(message || response.status); }); } }); } get = (endpoint: string): Promise => { const fullUrl = `${getConfig().API_URL}/${endpoint}`; const { url, ...request } = this.getRequestParams(fullUrl, "GET"); return this.request(url, request); }; post = (endpoint: string, payload: any): Promise => { const fullUrl = `${getConfig().API_URL}/${endpoint}`; const { url, ...request } = this.getRequestParams(fullUrl, "POST", payload); return this.request(url, request); }; put = (endpoint: string, payload: any): Promise => { const fullUrl = `${getConfig().API_URL}/${endpoint}`; const { url, ...request } = this.getRequestParams(fullUrl, "PUT", payload); return this.request(url, request); }; delete = (endpoint: string): Promise => { const fullUrl = `${getConfig().API_URL}/${endpoint}`; const { url, ...request } = this.getRequestParams(fullUrl, "DELETE"); return this.request(url, request); }; addInterceptor(interceptorFn: Interceptor) { this.interceptors = [...this.interceptors, interceptorFn]; return () => { this.interceptors = this.interceptors.filter( (_fn, index) => index !== this.interceptors.indexOf(interceptorFn) ); }; } getRequestParams(url: string, method: FetchMethod, body?: any) { let payload = { url, method, body, headers: { "content-type": "application/json;charset=UTF-8", }, }; const pipe = (a, b) => (arg) => b(a(arg)); const reduced = (...ops: Interceptor[]) => ops.reduce(pipe); return reduced(...this.interceptors)(payload); } } export const fetchService = new FetchService();