官网开发中 0731
This commit is contained in:
@@ -1,28 +1,41 @@
|
||||
/**
|
||||
* 统一请求封装(基于 Nuxt 内置 ofetch)
|
||||
* 响应格式约定:{ code, data, message },成功码 '0000'
|
||||
*
|
||||
* 与 dashboard 后端约定响应格式:{ code, msg, data }
|
||||
* - code = 1:成功
|
||||
* - code = 0:业务错误
|
||||
* - code = 2:无数据
|
||||
*/
|
||||
|
||||
interface ApiResponse<T = unknown> {
|
||||
code: string;
|
||||
data: T;
|
||||
message: string;
|
||||
export interface ApiResponse<T = unknown> {
|
||||
code: number;
|
||||
msg: string;
|
||||
data: T | null;
|
||||
}
|
||||
|
||||
export class ApiError extends Error {
|
||||
code: number;
|
||||
constructor(msg: string, code: number) {
|
||||
super(msg);
|
||||
this.code = code;
|
||||
}
|
||||
}
|
||||
|
||||
export function useRequest() {
|
||||
const config = useRuntimeConfig();
|
||||
const baseURL = config.public.apiBaseUrl as string;
|
||||
|
||||
async function request<T = unknown>(url: string, options?: Parameters<typeof $fetch>[1]): Promise<T> {
|
||||
async function request<T = unknown>(url: string, options?: Parameters<typeof $fetch>[1]): Promise<T | null> {
|
||||
const res = await $fetch<ApiResponse<T>>(url, {
|
||||
baseURL,
|
||||
...options
|
||||
});
|
||||
|
||||
if (res.code !== '0000') {
|
||||
throw new Error(res.message || 'Request failed');
|
||||
if (res.code === 0) {
|
||||
throw new ApiError(res.msg || '请求失败', res.code);
|
||||
}
|
||||
|
||||
// code = 2(无数据)时 data 为 null,正常返回
|
||||
return res.data;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user