nuxt-multi-cache
Version:
SSR route, component and data cache for Nuxt.js
59 lines (58 loc) • 1.85 kB
JavaScript
import {
MULTI_CACHE_CDN_CONTEXT_KEY,
MULTI_CACHE_CONTEXT_KEY,
MULTI_CACHE_PREFIX_KEY,
MULTI_CACHE_ROUTE_CONTEXT_KEY
} from "../../helpers/server.js";
import { NuxtMultiCacheRouteCacheHelper } from "../../helpers/RouteCacheHelper.js";
import { useMultiCacheApp } from "../utils/useMultiCacheApp.js";
import { NuxtMultiCacheCDNHelper } from "../../helpers/CDNHelper.js";
async function addCacheContext(event) {
const { cache, serverOptions, config } = useMultiCacheApp();
if (serverOptions.cacheKeyPrefix) {
if (typeof serverOptions.cacheKeyPrefix === "string") {
event[MULTI_CACHE_PREFIX_KEY] = serverOptions.cacheKeyPrefix;
} else {
event[MULTI_CACHE_PREFIX_KEY] = await serverOptions.cacheKeyPrefix(event);
}
}
event[MULTI_CACHE_CONTEXT_KEY] = cache;
if (cache.route) {
event[MULTI_CACHE_ROUTE_CONTEXT_KEY] = new NuxtMultiCacheRouteCacheHelper();
}
if (config.cdn.enabled) {
const helper = new NuxtMultiCacheCDNHelper();
event[MULTI_CACHE_CDN_CONTEXT_KEY] = helper;
}
return cache;
}
function enabledForRequest(event) {
const { serverOptions } = useMultiCacheApp();
if (serverOptions.enabledForRequest) {
return serverOptions.enabledForRequest(event);
}
return Promise.resolve(true);
}
function applies(path) {
const { serverOptions } = useMultiCacheApp();
if (serverOptions.route?.applies) {
return serverOptions.route.applies(path);
}
if (path.startsWith("/_nuxt") || path.startsWith("/__nuxt_error")) {
return false;
}
return !/.\.(ico|png|jpg|js|css|html|woff|woff2|ttf|otf|eot|svg)$/.test(path);
}
export async function onRequest(event) {
if (!event.path) {
return;
}
if (!applies(event.path)) {
return;
}
const cachingEnabled = await enabledForRequest(event);
if (!cachingEnabled) {
return;
}
await addCacheContext(event);
}