Migrate from file-based storage to Deno KV for price data management

This commit is contained in:
wood chen 2025-02-07 21:28:48 +08:00
parent 76767bf429
commit 8c000f16b0

21
main.ts
View File

@ -1,4 +1,4 @@
import { serve } from "https://deno.land/std/http/server.ts"; import { serve } from "https://deno.land/std@0.220.1/http/server.ts";
// HTML 页面 // HTML 页面
const html = `<!DOCTYPE html> const html = `<!DOCTYPE html>
@ -80,21 +80,18 @@ const html = `<!DOCTYPE html>
</body> </body>
</html>`; </html>`;
// 读取prices.json文件 // 使用 Deno KV 存储数据
const kv = await Deno.openKv();
// 读取价格数据
async function readPrices(): Promise<any[]> { async function readPrices(): Promise<any[]> {
try { const prices = await kv.get(["prices"]);
const decoder = new TextDecoder("utf-8"); return prices.value || [];
const data = await Deno.readFile("prices.json");
return JSON.parse(decoder.decode(data));
} catch {
return [];
}
} }
// 写入prices.json文件 // 写入价格数据
async function writePrices(prices: any[]): Promise<void> { async function writePrices(prices: any[]): Promise<void> {
const encoder = new TextEncoder(); await kv.set(["prices"], prices);
await Deno.writeFile("prices.json", encoder.encode(JSON.stringify(prices, null, 2)));
} }
// 验证请求数据 // 验证请求数据