newsnow/server/cache.ts

50 lines
1.3 KiB
TypeScript
Raw Normal View History

2024-10-03 17:24:29 +08:00
import { TTL } from "@shared/consts"
import type { CacheInfo } from "@shared/types"
2024-10-03 23:11:10 +08:00
import type { Database } from "db0"
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() {
2024-10-04 15:36:03 +08:00
const last = performance.now()
2024-10-03 23:11:10 +08:00
await this.db.prepare(`
2024-10-03 17:24:29 +08:00
CREATE TABLE IF NOT EXISTS cache (
id TEXT PRIMARY KEY,
data TEXT,
updated INTEGER,
expires INTEGER
);
2024-10-03 23:11:10 +08:00
`).run()
2024-10-04 15:36:03 +08:00
console.log(`init: `, performance.now() - last)
2024-10-03 17:24:29 +08:00
}
async set(key: string, value: any) {
const now = Date.now()
2024-10-04 15:36:03 +08:00
const last = performance.now()
await this.db.prepare(
2024-10-03 17:24:29 +08:00
`INSERT OR REPLACE INTO cache (id, data, updated, expires) VALUES (?, ?, ?, ?)`,
).run(key, JSON.stringify(value), now, now + TTL)
2024-10-04 15:36:03 +08:00
console.log(`set ${key}: `, performance.now() - last)
2024-10-03 17:24:29 +08:00
}
async get(key: string): Promise<CacheInfo> {
2024-10-04 15:36:03 +08:00
const last = performance.now()
2024-10-03 23:11:10 +08:00
const row: any = await this.db.prepare(`SELECT id, data, updated, expires 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-04 15:36:03 +08:00
console.log(`get ${key}: `, performance.now() - last)
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)
}
}