63 lines
1.8 KiB
TypeScript
Raw Normal View History

2024-10-05 17:20:49 +08:00
import { Interval, TTL } from "@shared/consts"
import type { SourceResponse } from "@shared/types"
import { sources } from "@shared/data"
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-05 17:20:49 +08:00
const id = getRouterParam(event, "id") as keyof typeof sourcesFn
2024-10-03 17:24:29 +08:00
const query = getQuery(event)
const latest = query.latest !== undefined && query.latest !== "false"
2024-10-03 13:16:14 +08:00
2024-10-05 23:55:30 +08:00
if (!id || !sources[id] || !sourcesFn[id]) throw new Error("Invalid source id")
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-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 17:20:49 +08:00
} else if (latest) {
let interval = Interval
if ("interval" in sources[id]) interval = sources[id].interval as number
if (now - cache.updated < interval) {
return {
status: "success",
data: {
updatedTime: now,
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
})