71 lines
2.2 KiB
TypeScript
Raw Normal View History

2024-10-12 12:49:20 +08:00
import { TTL } from "@shared/consts"
2024-10-08 20:49:19 +08:00
import type { SourceID, SourceResponse } from "@shared/types"
import { sources } from "@shared/sources"
2024-10-05 23:55:30 +08:00
import { sourcesFn } from "#/sources"
2024-10-03 17:24:29 +08:00
import { Cache } from "#/cache"
2024-09-29 20:57:24 +08:00
2024-10-05 17:20:49 +08:00
export default defineEventHandler(async (event): Promise<SourceResponse> => {
2024-10-03 17:24:29 +08:00
try {
2024-10-08 20:49:19 +08:00
let id = getRouterParam(event, "id") as SourceID
2024-10-03 17:24:29 +08:00
const query = getQuery(event)
const latest = query.latest !== undefined && query.latest !== "false"
2024-10-08 20:49:19 +08:00
const isValid = (id: SourceID) => !id || !sources[id] || !sourcesFn[id]
if (isValid(id)) {
const redirectID = sources[id].redirect
if (redirectID) id = redirectID
if (isValid(id)) throw new Error("Invalid source id")
}
2024-10-03 13:16:14 +08:00
2024-10-03 17:24:29 +08:00
const db = useDatabase()
const cacheStore = db ? new Cache(db) : undefined
2024-10-05 17:20:49 +08:00
const now = Date.now()
2024-10-03 17:24:29 +08:00
if (cacheStore) {
2024-10-04 15:36:03 +08:00
// await cacheStore.init()
2024-10-03 17:24:29 +08:00
const cache = await cacheStore.get(id)
if (cache) {
2024-10-08 22:41:38 +08:00
// interval 刷新间隔,对于缓存失效也要执行的。本质上表示本来内容更新就很慢,这个间隔内可能内容压根不会更新。
// 默认 10 分钟,是低于 TTL 的,但部分 Source 的间隔会超过 TTL甚至有的一天刷新一次。
2024-10-12 12:49:20 +08:00
const interval = sources[id].interval
2024-10-08 22:41:38 +08:00
if (now - cache.updated < interval) {
return {
status: "success",
data: {
updatedTime: now,
items: cache.data,
},
}
}
// 而 TTL 缓存失效时间,在时间范围内,就算内容更新了也要用这个缓存。
// 复用缓存是不会更新时间的。
2024-10-05 17:20:49 +08:00
if (!latest && now - cache.updated < TTL) {
2024-10-03 17:24:29 +08:00
return {
status: "cache",
2024-10-05 17:20:49 +08:00
data: {
updatedTime: cache.updated,
items: cache.data,
},
2024-10-03 17:24:29 +08:00
}
}
}
}
2024-10-05 23:55:30 +08:00
const data = await sourcesFn[id]()
logger.success(`fetch ${id} latest`)
if (cacheStore) event.waitUntil(cacheStore.set(id, data))
return {
status: "success",
data: {
updatedTime: now,
items: data,
},
2024-10-03 17:24:29 +08:00
}
} catch (e: any) {
2024-10-05 23:55:30 +08:00
logger.error(e)
2024-10-03 17:24:29 +08:00
return {
status: "error",
message: e.message ?? e,
}
2024-10-03 13:16:14 +08:00
}
2024-09-29 20:57:24 +08:00
})