This commit is contained in:
张成
2026-03-27 15:18:33 +08:00
parent c3aab075d9
commit aac2d4a8d5
6 changed files with 3738 additions and 267 deletions

View File

@@ -48,8 +48,7 @@ function buildProxyRoutes() {
// 1. 提取 Token
const token = extractToken(ctx);
if (!token) {
ctx.status = 401;
ctx.body = { ok: false, error_code: "TOKEN_MISSING", message: "缺少 Token" };
ctx.fail("缺少 Token");
return;
}
@@ -57,8 +56,7 @@ function buildProxyRoutes() {
const feature = pickFeature(spec);
const authResult = await auth.verifyRequest({ token, feature, api_path: path });
if (!authResult.ok) {
ctx.status = 403;
ctx.body = authResult;
ctx.fail(authResult.message || "鉴权失败");
return;
}
@@ -76,9 +74,13 @@ function buildProxyRoutes() {
auth_ctx: authResult.context,
});
// 5. 原样返回上游响应
ctx.status = result.status;
ctx.body = result.data;
// 5. 根据上游 Success 字段决定响应方式
const upstream = result.data;
if (upstream && upstream.Success === true) {
ctx.success(upstream);
} else {
ctx.fail(upstream && upstream.Text ? upstream.Text : "上游请求失败", upstream);
}
};
}
}

View File

@@ -16,7 +16,7 @@ const upstreamBaseUrl = config.upstream_api_url || "http://127.0.0.1:8888";
* @param {object} params.auth_ctx - 鉴权上下文verifyRequest 返回的 context
* @returns {object} { status, data, headers }
*/
async function forwardRequest({ api_path, method, query, body, headers, auth_ctx }) {
async function forwardRequest({ api_path, method, query, body, headers, auth_ctx = {} }) {
const url = `${upstreamBaseUrl}${api_path}`;
const start = Date.now();
let status_code = 0;
@@ -66,18 +66,23 @@ async function forwardRequest({ api_path, method, query, body, headers, auth_ctx
* 写入 API 调用日志
*/
async function writeCallLog({ user_id, token_id, api_path, http_method, status_code, response_time }) {
const now = new Date();
const call_date = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}-${String(now.getDate()).padStart(2, "0")}`;
await baseModel.biz_api_call_log.create({
user_id,
token_id,
api_path,
http_method,
status_code,
response_time,
call_date,
created_at: now,
});
try {
const now = new Date();
const call_date = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}-${String(now.getDate()).padStart(2, "0")}`;
await baseModel.biz_api_call_log.create({
user_id,
token_id,
api_path,
http_method,
status_code,
response_time,
call_date,
created_at: now,
});
} catch (e) {
logs.error("[proxy] 写调用日志失败", e.message);
}
}
module.exports = { forwardRequest };