Files
OCS_service/app/services/base_service.ts
T
2026-05-22 16:27:35 +08:00

50 lines
1.4 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// app/services/base_service.ts - 前端请求基础封装,保持和其他项目相近的调用风格
/** GET query 可接受的基础值类型 */
type QueryValue = string | number | boolean | null | undefined;
/** GET query 对象;空值会在请求前被过滤掉 */
type QueryParams = Record<string, QueryValue>;
/** 把 undefined/null/空字符串从 query 中移除,避免拼出无意义参数 */
const cleanQuery = (query?: QueryParams) => {
if (!query) return undefined;
return Object.fromEntries(
Object.entries(query).filter(([, value]) => {
return value !== undefined && value !== null && value !== "";
})
);
};
/**
* 基础请求类
*
* 其他项目里 service 方法返回 axios response,这里用 `$fetch` 包一层 `{ data }`
* 让 store 层仍然可以写成 `res.data`,后续替换请求库也不会影响组件。
*/
export default class BaseClientService {
/** 发起 GET 请求 */
public static async get<T>(url: string, query?: QueryParams) {
const data = await $fetch<T>(url, {
method: "GET",
query: cleanQuery(query)
});
return { data };
}
/** 发起 POST 请求 */
public static async post<T, B extends object | undefined = undefined>(
url: string,
body?: B
) {
const data = await $fetch<T>(url, {
method: "POST",
body
});
return { data };
}
}