feat(api): restore and update api-request module structure

This commit is contained in:
DEV_DSW
2026-04-20 16:51:09 +08:00
parent 2eaa8951f6
commit 25102c2ae4
3 changed files with 3 additions and 3 deletions

54
src/lib/api-request.ts Normal file
View 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;