nuxt-multi-cache
Version:
SSR route, component and data cache for Nuxt.js
50 lines (49 loc) • 1.37 kB
JavaScript
import { createError, getHeader } from "h3";
import { useMultiCacheApp } from "../../utils/useMultiCacheApp.js";
const AUTH_HEADER = "x-nuxt-multi-cache-token";
export function getCacheInstance(event) {
const multiCache = useMultiCacheApp();
const cacheName = event.context.params?.cacheName;
if (cacheName) {
const cache = multiCache.cache[cacheName];
if (cache) {
return cache;
}
}
throw createError({
statusCode: 404,
statusMessage: `The given cache "${cacheName}" is not available.`
});
}
export async function checkAuth(event) {
const { serverOptions, config } = useMultiCacheApp();
const { authorizationDisabled, authorizationToken } = config.api || {};
if (authorizationDisabled) {
return;
}
if (authorizationToken) {
const headerToken = getHeader(event, AUTH_HEADER);
if (headerToken === authorizationToken) {
return;
}
throw createError({
statusCode: 401,
statusMessage: "Unauthorized"
});
}
const authorization = serverOptions.api?.authorization;
if (!authorization) {
throw createError({
statusCode: 500,
statusMessage: "No authorization configuration option provided."
});
}
const result = await authorization(event);
if (result) {
return;
}
throw createError({
statusCode: 401,
statusMessage: "Unauthorized"
});
}