2024-10-03 13:16:14 +08:00
|
|
|
import { fallback, sources } from "#/sources"
|
2024-10-03 17:24:29 +08:00
|
|
|
import { Cache } from "#/cache"
|
2024-09-29 20:57:24 +08:00
|
|
|
|
|
|
|
export default defineEventHandler(async (event) => {
|
2024-10-03 17:24:29 +08:00
|
|
|
try {
|
|
|
|
const id = getRouterParam(event, "id") as keyof typeof sources
|
|
|
|
const query = getQuery(event)
|
|
|
|
const latest = query.latest !== undefined && query.latest !== "false"
|
2024-10-03 13:16:14 +08:00
|
|
|
|
2024-10-03 17:24:29 +08:00
|
|
|
if (!id) throw new Error("Invalid source id")
|
|
|
|
const db = useDatabase()
|
|
|
|
const cacheStore = db ? new Cache(db) : undefined
|
|
|
|
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) {
|
|
|
|
if (!latest && cache.expires > Date.now()) {
|
|
|
|
return {
|
|
|
|
status: "cache",
|
|
|
|
data: cache.data,
|
|
|
|
}
|
|
|
|
} else if (latest && Date.now() - cache.updated < 60 * 1000) {
|
|
|
|
return {
|
|
|
|
status: "success",
|
|
|
|
data: cache.data,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!sources[id]) {
|
2024-10-04 15:36:03 +08:00
|
|
|
const last = performance.now()
|
2024-10-03 17:24:29 +08:00
|
|
|
const data = await fallback(id)
|
2024-10-04 15:36:03 +08:00
|
|
|
console.log(`fetch: ${id}`, performance.now() - last)
|
2024-10-03 23:11:10 +08:00
|
|
|
if (cacheStore) await cacheStore.set(id, data)
|
2024-10-03 17:24:29 +08:00
|
|
|
return {
|
|
|
|
status: "success",
|
|
|
|
data,
|
|
|
|
}
|
|
|
|
} else {
|
2024-10-04 15:36:03 +08:00
|
|
|
const last = performance.now()
|
|
|
|
const data = await (await sources[id])()
|
|
|
|
console.log(`fetch: ${id}`, performance.now() - last)
|
2024-10-03 23:11:10 +08:00
|
|
|
if (cacheStore) await cacheStore.set(id, data)
|
2024-10-03 17:24:29 +08:00
|
|
|
return {
|
|
|
|
status: "success",
|
|
|
|
data,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
} catch (e: any) {
|
|
|
|
console.error(e)
|
|
|
|
return {
|
|
|
|
status: "error",
|
|
|
|
message: e.message ?? e,
|
|
|
|
}
|
2024-10-03 13:16:14 +08:00
|
|
|
}
|
2024-09-29 20:57:24 +08:00
|
|
|
})
|