feat(api): restore and update api-request module structure
This commit is contained in:
54
src/lib/api-request.ts
Normal file
54
src/lib/api-request.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
import { hostApiFetch } from '@src/lib/host-api';
|
||||
|
||||
interface RequestOptions {
|
||||
method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
|
||||
headers?: Record<string, string>;
|
||||
data?: unknown;
|
||||
params?: Record<string, string | number | boolean>;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
interface ApiResponse<T> {
|
||||
code: number;
|
||||
data: T;
|
||||
message?: string;
|
||||
}
|
||||
|
||||
async function request<T>(url: string, options: RequestOptions = {}): Promise<T> {
|
||||
const { method = 'GET', headers = {}, data, params, ...rest } = options;
|
||||
|
||||
let finalUrl = url;
|
||||
if (params && Object.keys(params).length > 0) {
|
||||
const searchParams = new URLSearchParams();
|
||||
Object.entries(params).forEach(([key, value]) => {
|
||||
searchParams.append(key, String(value));
|
||||
});
|
||||
finalUrl = `${url}?${searchParams.toString()}`;
|
||||
}
|
||||
|
||||
const init: RequestInit = {
|
||||
method,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...headers,
|
||||
},
|
||||
};
|
||||
|
||||
if (data && method !== 'GET') {
|
||||
init.body = JSON.stringify(data);
|
||||
}
|
||||
|
||||
const response = await hostApiFetch<ApiResponse<T>>(finalUrl, {
|
||||
...init,
|
||||
...rest,
|
||||
body: init.body,
|
||||
});
|
||||
|
||||
if (response && typeof response === 'object' && 'data' in response) {
|
||||
return response.data;
|
||||
}
|
||||
|
||||
return response as T;
|
||||
}
|
||||
|
||||
export default request;
|
||||
Reference in New Issue
Block a user