From 6f27c17ed5c91f95340f9e334781eabce74b105d Mon Sep 17 00:00:00 2001 From: Adam Fipke Date: Sun, 6 Oct 2024 00:52:36 -0700 Subject: [PATCH] got started with switching to fetch from axios --- packages/frontend/app/api/index.ts | 44 +++++++++++++++++++++--------- 1 file changed, 31 insertions(+), 13 deletions(-) diff --git a/packages/frontend/app/api/index.ts b/packages/frontend/app/api/index.ts index 9b799aaea..480b39a77 100644 --- a/packages/frontend/app/api/index.ts +++ b/packages/frontend/app/api/index.ts @@ -63,6 +63,7 @@ import { import Axios, { AxiosInstance, Method } from 'axios' import { plainToClass } from 'class-transformer' import { ClassType } from 'class-transformer/ClassTransformer' +import { getErrorMessage } from '../utils/generalUtils' // Return type of array item, if T is an array type ItemIfArray = T extends (infer I)[] ? I : T @@ -86,8 +87,6 @@ export interface ChatQuestionResponse { } class APIClient { - private axios: AxiosInstance - /** * Send HTTP and return data, optionally serialized with class-transformer (helpful for Date serialization) * @param method HTTP method @@ -96,21 +95,40 @@ class APIClient { * @param body body to send with req */ private async req( - method: Method, + method: string, url: string, responseClass?: ClassType>, body?: any, params?: any, - ): Promise - private async req( - method: Method, - url: string, - responseClass?: ClassType, - body?: any, - params?: any, ): Promise { - const res = (await this.axios.request({ method, url, data: body, params })) - .data + // Construct the full URL with query parameters if any + const queryString = params + ? '?' + new URLSearchParams(params).toString() + : '' + const fullUrl = url + queryString + + // Set up the request options + const options: RequestInit = { + method, + headers: { + 'Content-Type': 'application/json', + }, + body: body ? JSON.stringify(body) : undefined, + } + + // Make the fetch request + const response = await fetch(fullUrl, options) + + // Parse the response data + const res = await response.json() + + // Check if the response is OK (status code 200-299) + if (!response.ok) { + const errorMessage = getErrorMessage(res) + throw new Error(errorMessage) + } + + // Optionally transform the response data return responseClass ? plainToClass(responseClass, res) : res } @@ -684,7 +702,7 @@ class APIClient { } constructor(baseURL = '') { - this.axios = Axios.create({ baseURL: baseURL }) + // this.axios = Axios.create({ baseURL: baseURL }) } }