From 5e84629e234801868cbdf16433778b2ff7b84eaf Mon Sep 17 00:00:00 2001 From: Ou Date: Mon, 14 Oct 2024 21:50:27 +0800 Subject: [PATCH] feat: optimize cache logi --- server/middleware/auth.ts | 24 +++++++++++++++--------- server/routes/s/[id].ts | 25 +++++++++++++++++-------- 2 files changed, 32 insertions(+), 17 deletions(-) diff --git a/server/middleware/auth.ts b/server/middleware/auth.ts index 7c0a2be..292b144 100644 --- a/server/middleware/auth.ts +++ b/server/middleware/auth.ts @@ -3,17 +3,23 @@ import { jwtVerify } from "jose" export default defineEventHandler(async (event) => { if (["JWT_SECRET", "G_CLIENT_ID", "G_CLIENT_SECRET"].find(k => !process.env[k])) { - event.context.user = true + event.context.disabledLogin = true } else { - const token = getHeader(event, "Authorization") - if (token && process.env.JWT_SECRET) { - try { - const { payload } = await jwtVerify(token.replace("Bearer ", ""), new TextEncoder().encode(process.env.JWT_SECRET)) as { payload?: { id: string, type: string } } - if (payload?.id) { - event.context.user = payload.id + const url = getRequestURL(event) + if (/^\/(?:me|s)\//.test(url.pathname)) { + const token = getHeader(event, "Authorization") + if (token && process.env.JWT_SECRET) { + try { + const { payload } = await jwtVerify(token.replace("Bearer ", ""), new TextEncoder().encode(process.env.JWT_SECRET)) as { payload?: { id: string, type: string } } + if (payload?.id) { + event.context.user = { + id: payload.id, + type: payload.type, + } + } + } catch { + logger.error("JWT verification failed") } - } catch { - logger.error("JWT verification failed") } } } diff --git a/server/routes/s/[id].ts b/server/routes/s/[id].ts index 010b18c..8fe11f1 100644 --- a/server/routes/s/[id].ts +++ b/server/routes/s/[id].ts @@ -26,7 +26,7 @@ export default defineEventHandler(async (event): Promise => { const cache = await cacheTable.get(id) if (cache) { // interval 刷新间隔,对于缓存失效也要执行的。本质上表示本来内容更新就很慢,这个间隔内可能内容压根不会更新。 - // 默认 10 分钟,是低于 TTL 的,但部分 Source 的间隔会超过 TTL,甚至有的一天刷新一次。 + // 默认 10 分钟,是低于 TTL 的,但部分 Source 的更新间隔会超过 TTL,甚至有的一天更新一次。 const interval = sources[id].interval if (now - cache.updated < interval) { return { @@ -40,13 +40,22 @@ export default defineEventHandler(async (event): Promise => { // 而 TTL 缓存失效时间,在时间范围内,就算内容更新了也要用这个缓存。 // 复用缓存是不会更新时间的。 - if ((!latest || !event.context.user) && now - cache.updated < TTL) { - return { - status: "cache", - data: { - updatedTime: cache.updated, - items: cache.data, - }, + if (now - cache.updated < TTL) { + // 有 latest + // 没有 latest,但服务器禁止登录 + + // 没有 latest + // 有 latest,服务器可以登录但没有登录 + if (!latest || (!event.context.disabledLogin && !event.context.user)) { + if (event.context.disabledLogin) { + return { + status: "cache", + data: { + updatedTime: cache.updated, + items: cache.data, + }, + } + } } } }