feat: 接口统一优化
This commit is contained in:
+7
-15
@@ -1,4 +1,8 @@
|
||||
// server/utils/answer.ts - OCS 答题提示词构建、答案清洗和响应格式化
|
||||
import type {
|
||||
ISearchErrorResponse,
|
||||
ISearchSuccessResponse
|
||||
} from "~~/shared/types/answer";
|
||||
|
||||
/** `/api/search` 从 OCS 请求中最终抽取出的标准参数 */
|
||||
export interface SearchParams {
|
||||
@@ -10,21 +14,9 @@ export interface SearchParams {
|
||||
options: string;
|
||||
}
|
||||
|
||||
/** OCS AnswererWrapper handler 期望的成功响应结构 */
|
||||
export interface OcsSuccessResponse {
|
||||
code: 1;
|
||||
/** 返回原题,handler 会将它作为匹配题目展示 */
|
||||
question: string;
|
||||
/** 返回最终答案;多选题必须是 `#` 分隔字符串,而不是数组 */
|
||||
answer: string;
|
||||
}
|
||||
|
||||
/** OCS AnswererWrapper handler 期望的失败响应结构 */
|
||||
export interface OcsErrorResponse {
|
||||
code: 0;
|
||||
/** 只放本地业务文案,不暴露上游或内部异常详情 */
|
||||
msg: string;
|
||||
}
|
||||
/** OCS 兼容响应类型别名,与 shared/types/answer.ts 保持一致 */
|
||||
export type OcsSuccessResponse = ISearchSuccessResponse;
|
||||
export type OcsErrorResponse = ISearchErrorResponse;
|
||||
|
||||
/**
|
||||
* 不同题型对应的补充说明
|
||||
|
||||
@@ -23,18 +23,18 @@ export const publicApiRoutes: ApiRouteRule[] = [
|
||||
];
|
||||
|
||||
/** 路径匹配:支持精确匹配、`/**` 前缀通配和 RegExp */
|
||||
function matchPath(rulePath: string | RegExp, pathname: string): boolean {
|
||||
const matchPath = (rulePath: string | RegExp, pathname: string): boolean => {
|
||||
if (rulePath instanceof RegExp) return rulePath.test(pathname);
|
||||
if (rulePath.endsWith("/**")) {
|
||||
const prefix = rulePath.slice(0, -3);
|
||||
return pathname === prefix || pathname.startsWith(`${prefix}/`);
|
||||
}
|
||||
return pathname === rulePath;
|
||||
}
|
||||
};
|
||||
|
||||
/** 判断当前请求是否命中公开路由规则 */
|
||||
export function isPublicApiRoute(pathname: string, method: string): boolean {
|
||||
return publicApiRoutes.some((rule) => {
|
||||
export const isPublicApiRoute = (pathname: string, method: string): boolean =>
|
||||
publicApiRoutes.some((rule) => {
|
||||
const methods = Array.isArray(rule.method)
|
||||
? rule.method
|
||||
: rule.method
|
||||
@@ -43,4 +43,3 @@ export function isPublicApiRoute(pathname: string, method: string): boolean {
|
||||
const methodMatched = !methods || methods.includes(method as HttpMethod);
|
||||
return methodMatched && matchPath(rule.path, pathname);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
// server/utils/response.ts - 统一 API 响应工具函数(非 OCS 接口专用)
|
||||
// OCS 搜题接口 /api/search 有固定的兼容格式,不使用此工具
|
||||
|
||||
/** 成功响应:code 0,data 为业务数据,msg 固定为"请求成功" */
|
||||
export const apiOk = <T>(data: T) => ({
|
||||
code: 0 as const,
|
||||
data,
|
||||
msg: "请求成功"
|
||||
});
|
||||
|
||||
/** 错误响应:data 固定为 null,msg 为本地安全文案,不暴露上游细节 */
|
||||
export const apiErr = (code: number, msg: string) => ({
|
||||
code,
|
||||
data: null,
|
||||
msg
|
||||
});
|
||||
Reference in New Issue
Block a user