import { QueryParam, stringifyQueryParams } from 'temen'; import fetch from 'cross-fetch'; import { requestHandler, RequestOptions, responseHandler } from './handlers'; const getEndpoint = (baseURL: string, path: string, params?: QueryParam) => { const querystring = stringifyQueryParams(params); return /https?:\/\//.test(path) ? path : `${baseURL}${path}${querystring}`; }; export type WithoutRequestBodyOptions = Omit; export const createInstance = ({ baseURL }: { baseURL: string }) => { const request = async (path: string, options: RequestOptions) => { const response = await fetch( getEndpoint(baseURL, path, options.params), requestHandler(options) ); return responseHandler(response); }; return { request, get: (path: string, options?: WithoutRequestBodyOptions) => request(path, { ...options, method: 'GET', }), post: (path: string, data: any, options?: WithoutRequestBodyOptions) => request(path, { ...options, method: 'POST', body: data, }), patch: (path: string, data: any, options?: WithoutRequestBodyOptions) => request(path, { ...options, method: 'PATCH', body: data, }), put: (path: string, data: any, options?: WithoutRequestBodyOptions) => request(path, { ...options, method: 'PUT', body: data, }), delete: (path: string, options?: WithoutRequestBodyOptions) => request(path, { ...options, method: 'DELETE', }), }; };