|
import { authMiddleware } from "../utils/auth.js"; |
|
|
|
|
|
export const onRequest = async (context: RouteContext): Promise<Response> => { |
|
const request = context.request; |
|
const env = context.env as Env; |
|
|
|
const authResponse = await authMiddleware(request, env); |
|
if (authResponse) { |
|
return authResponse; |
|
} |
|
|
|
const KV_KEY = "accounts" |
|
|
|
try { |
|
|
|
if (request.method === 'GET') { |
|
const accounts = await env.KV.get(KV_KEY); |
|
return new Response(accounts || '[]', { |
|
status: 200, |
|
headers: { 'Content-Type': 'application/json' } |
|
}); |
|
} |
|
|
|
|
|
if (request.method === 'POST') { |
|
const data = await request.json(); |
|
|
|
|
|
if (!Array.isArray(data)) { |
|
return new Response(JSON.stringify({ error: '无效的数据格式' }), { |
|
status: 400, |
|
headers: { 'Content-Type': 'application/json' } |
|
}); |
|
} |
|
|
|
|
|
await env.KV.put(KV_KEY, JSON.stringify(data)); |
|
|
|
return new Response(JSON.stringify({ message: '保存成功' }), { |
|
status: 200, |
|
headers: { 'Content-Type': 'application/json' } |
|
}); |
|
} |
|
|
|
|
|
return new Response(JSON.stringify({ error: '不支持的请求方法' }), { |
|
status: 405, |
|
headers: { 'Content-Type': 'application/json' } |
|
}); |
|
|
|
} catch (error) { |
|
return new Response(JSON.stringify({ error: '服务器内部错误' }), { |
|
status: 500, |
|
headers: { 'Content-Type': 'application/json' } |
|
}); |
|
} |
|
}; |