diff --git a/eslint.config.mjs b/eslint.config.mjs index 84fa1bf..c6524cb 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -1,7 +1,8 @@ -import { ourongxing } from "@ourongxing/eslint-config" +import { ourongxing, react } from "@ourongxing/eslint-config" export default ourongxing({ type: "app", - react: true, ignores: ["**/routeTree.gen.ts"], -}) +}).append(react({ + files: ["src/**"], +})) diff --git a/server/api/s/[id].ts b/server/api/s/[id].ts index 6f8eb28..633dd72 100644 --- a/server/api/s/[id].ts +++ b/server/api/s/[id].ts @@ -1,9 +1,8 @@ -import process from "node:process" import { TTL } from "@shared/consts" import type { SourceID, SourceResponse } from "@shared/types" import { sources } from "@shared/sources" import { getters } from "#/getters" -import { useCache } from "#/hooks/useCache" +import { getCacheTable } from "#/database/cache" export default defineEventHandler(async (event): Promise => { try { @@ -18,10 +17,9 @@ export default defineEventHandler(async (event): Promise => { if (isValid(id)) throw new Error("Invalid source id") } - const cacheTable = useCache() + const cacheTable = await getCacheTable() const now = Date.now() if (cacheTable) { - if (process.env.INIT_TABLE !== "false") await cacheTable.init() const cache = await cacheTable.get(id) if (cache) { // interval 刷新间隔,对于缓存失效也要执行的。本质上表示本来内容更新就很慢,这个间隔内可能内容压根不会更新。 diff --git a/server/database/cache.ts b/server/database/cache.ts index c1ba875..8267d8f 100644 --- a/server/database/cache.ts +++ b/server/database/cache.ts @@ -1,3 +1,4 @@ +import process from "node:process" import type { NewsItem } from "@shared/types" import type { Database } from "db0" import type { CacheInfo } from "../types" @@ -43,3 +44,17 @@ export class Cache { return await this.db.prepare(`DELETE FROM cache WHERE id = ?`).run(key) } } + +export async function getCacheTable() { + try { + // 如果没有数据库,这里不会报错,只会在第一次访问的时候报错 + const db = useDatabase() + if (process.env.CF_PAGES_BRANCH && process.env.CF_PAGES_BRANCH !== "main") return + 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) + } +} diff --git a/server/hooks/useCache.ts b/server/hooks/useCache.ts deleted file mode 100644 index 290546f..0000000 --- a/server/hooks/useCache.ts +++ /dev/null @@ -1,13 +0,0 @@ -import process from "node:process" -import { Cache } from "#/database/cache" - -export function useCache() { - try { - const db = useDatabase() - if (process.env.CF_PAGES_BRANCH && process.env.CF_PAGES_BRANCH !== "main") return - if (process.env.NODE_ENV && process.env.NODE_ENV !== "production") return - if (db) return new Cache(db) - } catch (e) { - logger.error("failed to init database ", e) - } -}