Files
directus/api/src/middleware/cache.ts
rijkvanzanten 578b761ded Add auto-purge option
And add cache-control header when auto purge is disabled

Fixes #3425
2020-12-16 14:26:38 -05:00

32 lines
948 B
TypeScript

import { RequestHandler } from 'express';
import asyncHandler from 'express-async-handler';
import env from '../env';
import { getCacheKey } from '../utils/get-cache-key';
import cache from '../cache';
const checkCacheMiddleware: RequestHandler = asyncHandler(async (req, res, next) => {
if (req.method.toLowerCase() !== 'get') return next();
if (env.CACHE_ENABLED !== true) return next();
if (!cache) return next();
const key = getCacheKey(req);
const cachedData = await cache.get(key);
if (cachedData) {
// Set cache-control header
if (env.CACHE_AUTO_PURGE !== true) {
const expiresAt = await cache.get(`${key}__expires_at`);
const maxAge = `max-age="${expiresAt - Date.now()}"`;
const access = !!req.accountability?.role === false ? 'public' : 'private';
res.setHeader('Cache-Control', `${access}, ${maxAge}`);
}
return res.json(cachedData);
} else {
return next();
}
});
export default checkCacheMiddleware;