UNPKG

nuxt-multi-cache

Version:

SSR route, component and data cache for Nuxt.js

65 lines (64 loc) 1.97 kB
import { useMultiCacheApp } from "../utils/useMultiCacheApp.js"; import { encodeRouteCacheKey, getCacheKeyWithPrefix, getMultiCacheContext } from "../../helpers/server.js"; import { decodeRouteCacheItem, handleRawCacheData } from "../../helpers/cacheItem.js"; import { logger } from "../../helpers/logger.js"; import { setCachedResponse } from "../../helpers/routeCache.js"; import { useRuntimeConfig } from "#imports"; function canBeServedFromCache(key, decoded, state) { const now = Date.now() / 1e3; const isExpired = decoded.expires ? now >= decoded.expires : false; if (!isExpired) { return true; } if (decoded.staleWhileRevalidate && state.isBeingRevalidated(key)) { return true; } return false; } export async function serveCachedHandler(event) { try { const { serverOptions, state } = useMultiCacheApp(); const context = getMultiCacheContext(event); if (!context?.route) { return; } const fullKey = serverOptions?.route?.buildCacheKey ? serverOptions.route.buildCacheKey(event) : getCacheKeyWithPrefix(encodeRouteCacheKey(event.path), event); const cachedRaw = handleRawCacheData( await context.route.getItemRaw(fullKey) ); if (!cachedRaw) { return; } const decoded = decodeRouteCacheItem(cachedRaw); if (!decoded) { return; } event.__MULTI_CACHE_DECODED_CACHED_ROUTE = decoded; if (!canBeServedFromCache(fullKey, decoded, state)) { if (decoded.staleWhileRevalidate) { state.addKeyBeingRevalidated(fullKey); event.__MULTI_CACHE_REVALIDATION_KEY = fullKey; } return; } const debugEnabled = useRuntimeConfig().multiCache.debug; if (debugEnabled) { logger.info("Serving cached route for path: " + event.path, { fullKey }); } setCachedResponse(event, decoded); return decoded.data; } catch (e) { if (e instanceof Error) { console.debug(e.message); } } }