File size: 1,982 Bytes
7fc5208
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import { authMiddleware } from "../utils/auth.js";
import { addCorsHeaders } from "../utils/cors.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 addCorsHeaders(authResponse);
    }

    const KV_KEY = "accounts" 

    try {
        // GET 请求处理
        if (request.method === 'GET') {
            const accounts = await env.KV.get(KV_KEY);
            return addCorsHeaders(new Response(accounts || '[]', {
                status: 200,
                headers: { 'Content-Type': 'application/json' }
            }));
        }
        
        // POST 请求处理
        if (request.method === 'POST') {
            const data = await request.json();
            
            // 验证数据格式
            if (!Array.isArray(data)) {
                return addCorsHeaders(new Response(JSON.stringify({ error: '无效的数据格式' }), {
                    status: 400,
                    headers: { 'Content-Type': 'application/json' }
                }));
            }

            // 存储账号数据
            await env.KV.put(KV_KEY, JSON.stringify(data));
            
            return addCorsHeaders(new Response(JSON.stringify({ message: '保存成功' }), {
                status: 200,
                headers: { 'Content-Type': 'application/json' }
            }));
        }

        // 不支持的请求方法
        return addCorsHeaders(new Response(JSON.stringify({ error: '不支持的请求方法' }), {
            status: 405,
            headers: { 'Content-Type': 'application/json' }
        }));

    } catch (error) {
        return addCorsHeaders(new Response(JSON.stringify({ error: '服务器内部错误' }), {
            status: 500,
            headers: { 'Content-Type': 'application/json' }
        }));
    }
};