Refactor request handling with improved error management and header consolidation

This commit is contained in:
wood chen 2025-02-08 02:00:48 +08:00
parent 2d0565c72e
commit 2e1e7ee722

134
main.ts
View File

@ -51,7 +51,6 @@ interface Price {
} }
// 声明全局变量 // 声明全局变量
declare const kv: Deno.Kv;
declare const vendors: { [key: string]: Vendor }; declare const vendors: { [key: string]: Vendor };
// 缓存供应商数据 // 缓存供应商数据
@ -59,6 +58,16 @@ let vendorsCache: VendorResponse | null = null;
let vendorsCacheTime: number = 0; let vendorsCacheTime: number = 0;
const CACHE_DURATION = 1000 * 60 * 5; // 5分钟缓存 const CACHE_DURATION = 1000 * 60 * 5; // 5分钟缓存
// 初始化 KV 存储
let kv: Deno.Kv;
try {
kv = await Deno.openKv();
} catch (error) {
console.error('初始化 KV 存储失败:', error);
Deno.exit(1);
}
// 获取供应商数据 // 获取供应商数据
async function getVendors(): Promise<VendorResponse> { async function getVendors(): Promise<VendorResponse> {
const now = Date.now(); const now = Date.now();
@ -791,8 +800,6 @@ function validateData(data: any): string | null {
// 修改处理函数 // 修改处理函数
async function handler(req: Request): Promise<Response> { async function handler(req: Request): Promise<Response> {
const url = new URL(req.url);
const headers = { const headers = {
"Access-Control-Allow-Origin": "*", "Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, OPTIONS", "Access-Control-Allow-Methods": "GET, POST, OPTIONS",
@ -800,10 +807,43 @@ async function handler(req: Request): Promise<Response> {
"Access-Control-Allow-Credentials": "true" "Access-Control-Allow-Credentials": "true"
}; };
const jsonHeaders = {
...headers,
"Content-Type": "application/json"
};
const htmlHeaders = {
...headers,
"Content-Type": "text/html; charset=utf-8"
};
try {
const url = new URL(req.url);
if (req.method === "OPTIONS") { if (req.method === "OPTIONS") {
return new Response(null, { headers }); return new Response(null, { headers });
} }
// 认证状态检查
if (url.pathname === "/api/auth/status") {
try {
const username = await verifyDiscourseSSO(req);
return new Response(JSON.stringify({
authenticated: !!username,
user: username
}), { headers: jsonHeaders });
} catch (error) {
console.error('验证用户状态失败:', error);
return new Response(JSON.stringify({
error: "验证用户状态失败",
details: error.message
}), {
status: 500,
headers: jsonHeaders
});
}
}
// 登录处理 // 登录处理
if (url.pathname === "/api/auth/login") { if (url.pathname === "/api/auth/login") {
const params = new URLSearchParams(url.search); const params = new URLSearchParams(url.search);
@ -811,10 +851,7 @@ async function handler(req: Request): Promise<Response> {
if (!returnUrl) { if (!returnUrl) {
return new Response(JSON.stringify({ error: "缺少 return_url 参数" }), { return new Response(JSON.stringify({ error: "缺少 return_url 参数" }), {
status: 400, status: 400,
headers: { headers: jsonHeaders
"Content-Type": "application/json",
...headers
}
}); });
} }
@ -929,38 +966,19 @@ async function handler(req: Request): Promise<Response> {
return new Response(JSON.stringify({ success: true }), { return new Response(JSON.stringify({ success: true }), {
headers: { headers: {
...headers, ...jsonHeaders,
"Content-Type": "application/json",
"Set-Control-Allow-Credentials": "true",
"Set-Cookie": "session=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0" "Set-Cookie": "session=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0"
} }
}); });
} }
// 认证状态检查
if (url.pathname === "/api/auth/status") {
const username = await verifyDiscourseSSO(req);
return new Response(JSON.stringify({
authenticated: !!username,
user: username
}), {
headers: {
"Content-Type": "application/json",
...headers
}
});
}
// 价格审核 // 价格审核
if (url.pathname.match(/^\/api\/prices\/\d+\/review$/)) { if (url.pathname.match(/^\/api\/prices\/\d+\/review$/)) {
const username = await verifyDiscourseSSO(req); const username = await verifyDiscourseSSO(req);
if (!username || username !== 'wood') { if (!username || username !== 'wood') {
return new Response(JSON.stringify({ error: "未授权" }), { return new Response(JSON.stringify({ error: "未授权" }), {
status: 403, status: 403,
headers: { headers: jsonHeaders
"Content-Type": "application/json",
...headers
}
}); });
} }
@ -987,20 +1005,14 @@ async function handler(req: Request): Promise<Response> {
await writePrices(prices); await writePrices(prices);
return new Response(JSON.stringify({ success: true }), { return new Response(JSON.stringify({ success: true }), {
headers: { headers: jsonHeaders
"Content-Type": "application/json",
...headers
}
}); });
} catch (error) { } catch (error) {
return new Response(JSON.stringify({ return new Response(JSON.stringify({
error: error.message || "审核失败" error: error.message || "审核失败"
}), { }), {
status: 400, status: 400,
headers: { headers: jsonHeaders
"Content-Type": "application/json",
...headers
}
}); });
} }
} }
@ -1012,10 +1024,7 @@ async function handler(req: Request): Promise<Response> {
if (!username) { if (!username) {
return new Response(JSON.stringify({ error: "请先登录" }), { return new Response(JSON.stringify({ error: "请先登录" }), {
status: 401, status: 401,
headers: { headers: jsonHeaders
"Content-Type": "application/json",
...headers
}
}); });
} }
@ -1060,10 +1069,7 @@ async function handler(req: Request): Promise<Response> {
if (error) { if (error) {
return new Response(JSON.stringify({ error }), { return new Response(JSON.stringify({ error }), {
status: 400, status: 400,
headers: { headers: jsonHeaders
"Content-Type": "application/json",
...headers
}
}); });
} }
@ -1083,10 +1089,7 @@ async function handler(req: Request): Promise<Response> {
success: true, success: true,
data: newPrice data: newPrice
}), { }), {
headers: { headers: jsonHeaders
"Content-Type": "application/json",
...headers
}
}); });
} catch (error) { } catch (error) {
console.error("处理价格提交失败:", error); console.error("处理价格提交失败:", error);
@ -1095,10 +1098,7 @@ async function handler(req: Request): Promise<Response> {
details: "数据处理失败,请检查输入格式" details: "数据处理失败,请检查输入格式"
}), { }), {
status: 500, status: 500,
headers: { headers: jsonHeaders
"Content-Type": "application/json",
...headers
}
}); });
} }
} }
@ -1108,10 +1108,7 @@ async function handler(req: Request): Promise<Response> {
try { try {
const prices = await readPrices(); const prices = await readPrices();
return new Response(JSON.stringify(prices), { return new Response(JSON.stringify(prices), {
headers: { headers: jsonHeaders
"Content-Type": "application/json",
...headers
}
}); });
} catch (error) { } catch (error) {
console.error('获取价格列表失败:', error); console.error('获取价格列表失败:', error);
@ -1120,10 +1117,7 @@ async function handler(req: Request): Promise<Response> {
details: error.message details: error.message
}), { }), {
status: 500, status: 500,
headers: { headers: jsonHeaders
"Content-Type": "application/json",
...headers
}
}); });
} }
} }
@ -1131,17 +1125,27 @@ async function handler(req: Request): Promise<Response> {
// 提供静态页面 // 提供静态页面
if (url.pathname === "/" || url.pathname === "/index.html") { if (url.pathname === "/" || url.pathname === "/index.html") {
return new Response(html, { return new Response(html, {
headers: { headers: htmlHeaders
"Content-Type": "text/html; charset=utf-8",
...headers
}
}); });
} }
return new Response("Not Found", { return new Response("Not Found", {
status: 404, status: 404,
headers headers: {
...headers,
"Content-Type": "text/plain"
}
}); });
} catch (error) {
console.error('处理请求失败:', error);
return new Response(JSON.stringify({
error: "处理请求失败",
details: error.message
}), {
status: 500,
headers: jsonHeaders
});
}
} }
// 启动服务器 // 启动服务器