feat: 新增api接口

Co-authored-by: Copilot <copilot@github.com>
This commit is contained in:
2026-04-24 15:36:44 +08:00
parent 278f1aab85
commit 5ab74ad9dd
13 changed files with 537 additions and 59 deletions
+73
View File
@@ -0,0 +1,73 @@
import type { ApiResponse } from "#shared/types";
/**
* 构造统一成功响应
*
* @param data 要返回给前端的数据,没有数据时传 null(默认)
* @param msg 提示信息,默认 "请求成功"
* @returns 符合 ApiResponse 格式的对象,code 固定为 0
*/
export const createSuccessResponse = <T>(
data: T | null = null,
msg: string = "请求成功"
): ApiResponse<T> => {
return {
code: 0,
data,
msg
};
};
/**
* 构造统一错误响应
*
* @param code 错误码,默认 400(请求参数错误);上游错误时传上游状态码
* @param msg 错误描述,展示给前端的提示文字
* @param data 附带的错误详情,通常是上游返回的原始响应体,默认 null
* @returns 符合 ApiResponse 格式的对象,data 固定为 null 或错误详情
*/
export const createErrorResponse = (
code: number = 400,
msg: string = "请求失败",
data: any = null
): ApiResponse => {
return {
code,
data,
msg
};
};
/**
* 将上游请求错误转换为统一响应
*
* @param error ofetch 抛出的错误对象
* @param fallbackMessage 当上游没有提供可用错误信息时的兜底提示
* @returns 符合 ApiResponse 格式的错误响应
*/
export const createUpstreamErrorResponse = (
error: unknown,
fallbackMessage: string = "请求失败"
): ApiResponse => {
const fetchError = error as {
data?: unknown;
message?: string;
response?: {
_data?: unknown;
status?: number;
};
statusCode?: number;
};
const errorData = fetchError.data ?? fetchError.response?._data ?? null;
const errorMessage =
typeof errorData === "string"
? errorData
: fetchError.message || fallbackMessage;
return createErrorResponse(
fetchError.statusCode ?? fetchError.response?.status ?? 500,
errorMessage,
errorData
);
};
+25
View File
@@ -0,0 +1,25 @@
/** 上游 NewAPI 服务的根地址 */
const BASE_URL = "https://api.qflink.xyz";
/**
* 向上游 NewAPI 发起请求
*
* @param path 相对路径,如 "/api/user/register",会自动拼接到 BASE_URL 后面
* @param options 透传给 $fetch 的所有选项(method、body、headers 等)
* @returns Promise<T>T 是上游返回的数据类型
*
* @example
* const result = await newApiFetch<string>("/api/user/register", {
* method: "POST",
* body: { username: "xxx" }
* })
*/
export const newApiFetch = <T>(
path: string,
options?: Parameters<typeof $fetch>[1]
): Promise<T> => {
return $fetch<T>(path, {
baseURL: BASE_URL,
...options
}) as Promise<T>;
};
+2
View File
@@ -0,0 +1,2 @@
export * from "./createApiResponse";
export * from "./fetch";