60 lines
1.6 KiB
TypeScript
Raw Normal View History

import process from "node:process"
2024-10-14 00:02:58 +08:00
import type { NewsItem } from "@shared/types"
2024-10-03 23:11:10 +08:00
import type { Database } from "db0"
2024-10-14 00:02:58 +08:00
import type { CacheInfo } from "../types"
2024-10-03 17:24:29 +08:00
export class Cache {
private db
2024-10-03 23:11:10 +08:00
constructor(db: Database) {
2024-10-03 17:24:29 +08:00
this.db = db
2024-10-03 23:11:10 +08:00
}
async init() {
await this.db.prepare(`
2024-10-03 17:24:29 +08:00
CREATE TABLE IF NOT EXISTS cache (
id TEXT PRIMARY KEY,
updated INTEGER,
2024-10-05 17:20:49 +08:00
data TEXT
2024-10-03 17:24:29 +08:00
);
2024-10-03 23:11:10 +08:00
`).run()
2024-10-05 23:55:30 +08:00
logger.success(`init cache table`)
2024-10-03 17:24:29 +08:00
}
2024-10-05 17:20:49 +08:00
async set(key: string, value: NewsItem[]) {
2024-10-03 17:24:29 +08:00
const now = Date.now()
2024-10-04 15:36:03 +08:00
await this.db.prepare(
2024-10-05 17:20:49 +08:00
`INSERT OR REPLACE INTO cache (id, data, updated) VALUES (?, ?, ?)`,
).run(key, JSON.stringify(value), now)
2024-10-05 23:55:30 +08:00
logger.success(`set ${key} cache`)
2024-10-03 17:24:29 +08:00
}
async get(key: string): Promise<CacheInfo> {
2024-10-05 17:20:49 +08:00
const row: any = await this.db.prepare(`SELECT id, data, updated FROM cache WHERE id = ?`).get(key)
2024-10-04 15:36:03 +08:00
const r = row
2024-10-03 17:24:29 +08:00
? {
...row,
data: JSON.parse(row.data),
}
: undefined
2024-10-05 23:55:30 +08:00
logger.success(`get ${key} cache`)
2024-10-04 15:36:03 +08:00
return r
2024-10-03 17:24:29 +08:00
}
async delete(key: string) {
return await this.db.prepare(`DELETE FROM cache WHERE id = ?`).run(key)
}
}
export async function getCacheTable() {
try {
// 如果没有数据库,这里不会报错,只会在第一次访问的时候报错
const db = useDatabase()
if (process.env.NODE_ENV && process.env.NODE_ENV !== "production") return
const cacheTable = new Cache(db)
if (process.env.INIT_TABLE !== "false") await cacheTable.init()
return cacheTable
} catch (e) {
logger.error("failed to init database ", e)
}
}