fix: deploy to cloudflare without d1 db

fix #17
This commit is contained in:
Ou 2024-10-29 16:13:45 +08:00
parent a1c76de436
commit 6cbce058cc
4 changed files with 21 additions and 20 deletions

View File

@ -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/**"],
}))

View File

@ -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<SourceResponse> => {
try {
@ -18,10 +17,9 @@ export default defineEventHandler(async (event): Promise<SourceResponse> => {
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 刷新间隔,对于缓存失效也要执行的。本质上表示本来内容更新就很慢,这个间隔内可能内容压根不会更新。

View File

@ -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)
}
}

View File

@ -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)
}
}