From 2876385f20c3b21511bfd6a38acbf67cfeb0e1bd Mon Sep 17 00:00:00 2001 From: ccbikai Date: Sat, 20 Jul 2024 18:21:40 +0800 Subject: [PATCH] feat: add link cache TTL for performance optimization Improves response times by introducing a configurable link cache TTL, defaulting to 60 seconds, to ensure quick access to frequently requested links while maintaining responsiveness to updates. --- .env.example | 1 + docs/configuration.md | 4 ++++ nuxt.config.ts | 1 + server/middleware/1.redirect.ts | 4 ++-- 4 files changed, 8 insertions(+), 2 deletions(-) diff --git a/.env.example b/.env.example index eefd180..b1f341d 100644 --- a/.env.example +++ b/.env.example @@ -2,6 +2,7 @@ NUXT_PUBLIC_PREVIEW_MODE=true NUXT_PUBLIC_SLUG_DEFAULT_LENGTH=5 NUXT_SITE_TOKEN=SinkCool NUXT_REDIRECT_STATUS_CODE=308 +NUXT_LINK_CACHE_TTL=60 NUXT_HOME_URL="https://sink.cool" NUXT_CF_ACCOUNT_ID=123456 NUXT_CF_API_TOKEN=CloudflareAPIToken diff --git a/docs/configuration.md b/docs/configuration.md index ffb2517..47669be 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -14,6 +14,10 @@ Sets the default length of the generated SLUG. Redirects default to use HTTP 301 status code, you can set it to `302`/`307`/`308`. +## `NUXT_LINK_CACHE_TTL` + +Cache links can speed up access, but setting them too long may result in slow changes taking effect. The default value is 60 seconds. + ## `NUXT_HOME_URL` The default Sink homepage is the introduction page, you can replace it with your own website. diff --git a/nuxt.config.ts b/nuxt.config.ts index c7685f9..a071081 100644 --- a/nuxt.config.ts +++ b/nuxt.config.ts @@ -52,6 +52,7 @@ export default defineNuxtConfig({ runtimeConfig: { siteToken: 'SinkCool', redirectStatusCode: '301', + linkCacheTtl: 60, homeURL: '', cfAccountId: '', cfApiToken: '', diff --git a/server/middleware/1.redirect.ts b/server/middleware/1.redirect.ts index cf35bf1..327f2af 100644 --- a/server/middleware/1.redirect.ts +++ b/server/middleware/1.redirect.ts @@ -5,7 +5,7 @@ import type { LinkSchema } from '@/schemas/link' export default eventHandler(async (event) => { const { pathname: slug } = parsePath(event.path.slice(1)) // remove leading slash const { slugRegex, reserveSlug } = useAppConfig(event) - const { homeURL } = useRuntimeConfig(event) + const { homeURL, linkCacheTtl } = useRuntimeConfig(event) const { cloudflare } = event.context if (event.path === '/' && homeURL) @@ -13,7 +13,7 @@ export default eventHandler(async (event) => { if (slug && !reserveSlug.includes(slug) && slugRegex.test(slug) && cloudflare) { const { KV } = cloudflare.env - const link: z.infer | null = await KV.get(`link:${slug}`, { type: 'json' }) + const link: z.infer | null = await KV.get(`link:${slug}`, { type: 'json', cacheTtl: linkCacheTtl }) if (link) { event.context.link = link try {