Skip to content
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 31 additions & 13 deletions packages/frontend/app/api/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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> = T extends (infer I)[] ? I : T
Expand All @@ -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
Expand All @@ -96,21 +95,40 @@ class APIClient {
* @param body body to send with req
*/
private async req<T>(
method: Method,
method: string,
url: string,
responseClass?: ClassType<ItemIfArray<T>>,
body?: any,
params?: any,
): Promise<T>
private async req<T>(
method: Method,
url: string,
responseClass?: ClassType<T>,
body?: any,
params?: any,
): Promise<T> {
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
}

Expand Down Expand Up @@ -684,7 +702,7 @@ class APIClient {
}

constructor(baseURL = '') {
this.axios = Axios.create({ baseURL: baseURL })
// this.axios = Axios.create({ baseURL: baseURL })
}
}

Expand Down