import { serve } from "https://deno.land/std@0.220.1/http/server.ts";
// HTML 页面
const html = `
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 === undefined || data.input === undefined || data.output === undefined) {
return "所有字段都是必需的";
}
// 确保数字字段是数字类型
const channel_type = Number(data.channel_type);
const input = Number(data.input);
const output = Number(data.output);
if (isNaN(channel_type) || isNaN(input) || isNaN(output)) {
return "数字字段格式无效";
}
// 验证数字范围(允许等于0)
if (channel_type < 0 || input < 0 || output < 0) {
return "数字不能小于0";
}
return null;
}
// 处理请求
async function handler(req: Request): Promise {
const url = new URL(req.url);
// 添加 CORS 支持
const headers = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type",
};
// 处理 OPTIONS 请求
if (req.method === "OPTIONS") {
return new Response(null, { headers });
}
// API 端点
if (url.pathname === "/api/prices") {
if (req.method === "POST") {
try {
let data;
const contentType = req.headers.get("content-type") || "";
if (contentType.includes("application/json")) {
data = await req.json();
} else if (contentType.includes("application/x-www-form-urlencoded")) {
const formData = await req.formData();
data = {};
for (const [key, value] of formData.entries()) {
// 如果值包含逗号,只取第一个值
const actualValue = String(value).split(',')[0];
data[key] = actualValue;
}
} else {
throw new Error("不支持的内容类型");
}
console.log("Received raw data:", data); // 调试日志
// 清理和转换数据
const cleanData = {
model: String(data.model).trim(),
type: String(data.type).trim(),
channel_type: Number(String(data.channel_type).split(',')[0]),
input: Number(String(data.input).split(',')[0]),
output: Number(String(data.output).split(',')[0])
};
console.log("Cleaned data:", cleanData); // 调试日志
// 验证数据
const error = validateData(cleanData);
if (error) {
return new Response(JSON.stringify({ error }), {
status: 400,
headers: {
"Content-Type": "application/json",
...headers
}
});
}
// 读取现有数据
const prices = await readPrices();
// 添加新数据
prices.push(cleanData);
// 保存数据
await writePrices(prices);
return new Response(JSON.stringify({
success: true,
data: cleanData
}), {
headers: {
"Content-Type": "application/json",
...headers
}
});
} catch (error) {
console.error("Processing error:", error); // 调试日志
return new Response(JSON.stringify({
error: error.message,
details: "数据处理失败,请检查输入格式"
}), {
status: 500,
headers: {
"Content-Type": "application/json",
...headers
}
});
}
} else if (req.method === "GET") {
const prices = await readPrices();
return new Response(JSON.stringify(prices), {
headers: {
"Content-Type": "application/json",
...headers
}
});
}
}
// 提供静态页面
if (url.pathname === "/" || url.pathname === "/index.html") {
return new Response(html, {
headers: {
"Content-Type": "text/html; charset=utf-8",
...headers
}
});
}
return new Response("Not Found", {
status: 404,
headers
});
}
// 启动服务器
serve(handler);