import { serve } from "https://deno.land/std@0.220.1/http/server.ts"; // HTML 页面 const html = ` AI Models Price Update

AI Models Price Update

`; // 使用 Deno KV 存储数据 const kv = await Deno.openKv(); // 读取价格数据 async function readPrices(): Promise { const prices = await kv.get(["prices"]); return prices.value || []; } // 写入价格数据 async function writePrices(prices: any[]): Promise { await kv.set(["prices"], prices); } // 验证请求数据 function validateData(data: any): string | null { if (!data.model || !data.type || !data.channel_type || !data.input || !data.output) { return "所有字段都是必需的"; } if (isNaN(data.channel_type) || isNaN(data.input) || isNaN(data.output)) { return "数字字段格式无效"; } return null; } // 处理请求 async function handler(req: Request): Promise { const url = new URL(req.url); // 提供静态页面 if (url.pathname === "/" || url.pathname === "/index.html") { return new Response(html, { headers: { "Content-Type": "text/html; charset=utf-8" } }); } // API 端点 if (url.pathname === "/api/prices") { if (req.method === "POST") { try { const data = await req.json(); // 验证数据 const error = validateData(data); if (error) { return new Response(JSON.stringify({ error }), { status: 400, headers: { "Content-Type": "application/json" } }); } // 转换数据类型 const newPrice = { model: data.model, type: data.type, channel_type: parseInt(data.channel_type), input: parseFloat(data.input), output: parseFloat(data.output) }; // 读取现有数据 const prices = await readPrices(); // 添加新数据 prices.push(newPrice); // 保存数据 await writePrices(prices); return new Response(JSON.stringify({ success: true }), { headers: { "Content-Type": "application/json" } }); } catch (error) { return new Response(JSON.stringify({ error: error.message }), { status: 500, headers: { "Content-Type": "application/json" } }); } } else if (req.method === "GET") { const prices = await readPrices(); return new Response(JSON.stringify(prices), { headers: { "Content-Type": "application/json" } }); } } return new Response("Not Found", { status: 404 }); } // 启动服务器 serve(handler);