nuxt-multi-cache
Version:
SSR route, component and data cache for Nuxt.js
46 lines (45 loc) • 1.66 kB
JavaScript
import { defineNitroPlugin } from "nitropack/runtime";
import { createStorage } from "unstorage";
import { onBeforeResponse } from "../hooks/beforeResponse.js";
import { onRequest } from "../hooks/request.js";
import { onAfterResponse } from "../hooks/afterResponse.js";
import { onError } from "../hooks/error.js";
import { MultiCacheState } from "../../helpers/MultiCacheState.js";
import { serveCachedHandler } from "../handler/serveCachedRoute.js";
import { serverOptions } from "#multi-cache-server-options";
import { useRuntimeConfig } from "#imports";
function createMultiCacheApp() {
const runtimeConfig = useRuntimeConfig();
const cacheContext = {};
if (runtimeConfig.multiCache.component) {
cacheContext.component = createStorage(serverOptions.component?.storage);
}
if (runtimeConfig.multiCache.data) {
cacheContext.data = createStorage(serverOptions.data?.storage);
}
if (runtimeConfig.multiCache.route) {
cacheContext.route = createStorage(serverOptions.route?.storage);
}
return {
cache: cacheContext,
serverOptions,
config: runtimeConfig.multiCache,
state: new MultiCacheState()
};
}
export default defineNitroPlugin((nitroApp) => {
const multiCache = createMultiCacheApp();
nitroApp.multiCache = multiCache;
nitroApp.hooks.hook("request", onRequest);
if (multiCache.config.cdn.enabled) {
nitroApp.hooks.hook("beforeResponse", onBeforeResponse);
}
if (multiCache.config.route) {
nitroApp.h3App.stack.unshift({
route: "/",
handler: serveCachedHandler
});
nitroApp.hooks.hook("afterResponse", onAfterResponse);
nitroApp.hooks.hook("error", onError);
}
});