| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455 |
- type DocResponse = { code: number, msg: string, data: string }
- const TTL_MS = 60 * 60 * 1000
- const cache = new Map<string, { value: string, expiresAt: number }>()
- const inFlight = new Map<string, Promise<string>>()
- export default defineEventHandler(async (event) => {
- const { key } = getQuery(event) as { key?: string }
- if (!key) {
- throw createError({ statusCode: 400, statusMessage: 'Missing key' })
- }
- const now = Date.now()
- const hit = cache.get(key)
- if (hit && hit.expiresAt > now) {
- return { code: 0, msg: '', data: hit.value }
- }
- const existing = inFlight.get(key)
- if (existing) {
- return { code: 0, msg: '', data: await existing }
- }
- const p = (async () => {
- const runtimeConfig = useRuntimeConfig()
- const baseURL = runtimeConfig.serverApiBase as string | undefined
- if (!baseURL) {
- throw createError({ statusCode: 500, statusMessage: 'Missing serverApiBase' })
- }
- const res = await $fetch<DocResponse>('/base/doc/get', {
- baseURL,
- params: { key },
- })
- if (!res || res.code !== 0) {
- throw createError({ statusCode: 500, statusMessage: res?.msg || 'Request failed' })
- }
- const html = res.data || ''
- cache.set(key, { value: html, expiresAt: Date.now() + TTL_MS })
- return html
- })()
- inFlight.set(key, p)
- try {
- return { code: 0, msg: '', data: await p }
- }
- finally {
- inFlight.delete(key)
- }
- })
|