maptile/web/plugins/http.ts

82 lines
2.0 KiB
TypeScript

import type { FetchResponse, SearchParameters } from "ofetch";
export interface ResponseOptions<T> {
data: T;
code: number;
message: string;
}
export default defineNuxtPlugin((nuxtApp) => {
const err = (text: string) => {
console.log(text);
};
const handleStatus: { [key: number]: () => void } = {
404: () => err("服务器资源不存在"),
500: () => err("服务器内部错误"),
403: () => err("没有权限访问该资源"),
401: () => err("登录状态已过期,需要重新登录"),
};
const handleError = <T>(
response: FetchResponse<ResponseOptions<T>> & FetchResponse<ResponseType>
) => {
if (!response._data) {
err("请求超时,服务器无响应!");
return;
}
if (handleStatus[response.status]) {
handleStatus[response.status]();
} else {
err("未知错误!");
}
};
const paramsSerializer = (params?: SearchParameters) => {
if (!params) return;
const query = useCloned(params, { deep: true }) as any;
Object.entries(query).forEach(([key, value]) => {
if (typeof value === "object" && Array.isArray(value) && value !== null) {
query[`${key}[]`] = toRaw(value).map((val: any) => JSON.stringify(val));
delete query[key];
}
});
return query;
};
const http = $fetch.create({
onRequest({ options }) {
options.params = paramsSerializer(options.params);
//TODO 添加token
},
onResponse({ response }) {
if (
response.headers.get("content-disposition") &&
response.status === 200
) {
return
}
if (response._data.code !== 200) {
handleError(response);
return Promise.reject(response._data);
}
response._data = response._data.data
return
},
onResponseError({ response }) {
handleError(response);
return Promise.reject(response?._data ?? null);
},
});
return {
provide: {
http: http,
},
};
});