fix: refactor fetching and refetch logic
This commit is contained in:
+19
-22
@@ -1,7 +1,7 @@
|
||||
import process from "node:process"
|
||||
import type { NewsItem } from "@shared/types"
|
||||
import type { Database } from "db0"
|
||||
import type { CacheInfo } from "../types"
|
||||
import type { CacheInfo, CacheRow } from "../types"
|
||||
|
||||
export class Cache {
|
||||
private db
|
||||
@@ -28,27 +28,22 @@ export class Cache {
|
||||
logger.success(`set ${key} cache`)
|
||||
}
|
||||
|
||||
async get(key: string): Promise<CacheInfo> {
|
||||
const row: any = await this.db.prepare(`SELECT id, data, updated FROM cache WHERE id = ?`).get(key)
|
||||
const r = row
|
||||
? {
|
||||
...row,
|
||||
data: JSON.parse(row.data),
|
||||
}
|
||||
: undefined
|
||||
logger.success(`get ${key} cache`)
|
||||
return r
|
||||
async get(key: string): Promise<CacheInfo | undefined > {
|
||||
const row = (await this.db.prepare(`SELECT id, data, updated FROM cache WHERE id = ?`).get(key)) as CacheRow | undefined
|
||||
if (row) {
|
||||
logger.success(`get ${key} cache`)
|
||||
return {
|
||||
id: row.id,
|
||||
updated: row.updated,
|
||||
items: JSON.parse(row.data),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async getEntries(keys: string[]) {
|
||||
async getEntire(keys: string[]): Promise<CacheInfo[]> {
|
||||
const keysStr = keys.map(k => `id = '${k}'`).join(" or ")
|
||||
const res = await this.db.prepare(`SELECT id, data, updated FROM cache WHERE ${keysStr}`).all() as any
|
||||
|
||||
const rows = (res.results ?? res) as {
|
||||
id: SourceID
|
||||
data: string
|
||||
updated: number
|
||||
}[]
|
||||
const rows = (res.results ?? res) as CacheRow[]
|
||||
|
||||
/**
|
||||
* https://developers.cloudflare.com/d1/build-with-d1/d1-client-api/#return-object
|
||||
@@ -60,12 +55,14 @@ export class Cache {
|
||||
* }
|
||||
*/
|
||||
if (rows?.length) {
|
||||
logger.success(`get entries cache`)
|
||||
return Object.fromEntries(rows.map(row => [row.id, {
|
||||
logger.success(`get entire (...) cache`)
|
||||
return rows.map(row => ({
|
||||
id: row.id,
|
||||
updatedTime: row.updated,
|
||||
updated: row.updated,
|
||||
items: JSON.parse(row.data) as NewsItem[],
|
||||
}]))
|
||||
}))
|
||||
} else {
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user