Refactored error cache control logic to middleware

refs https://github.com/TryGhost/Toolbox/issues/410

- This is groundwork for split cache-control rules for Admin app endpoints and the rest of Ghost apps.
This commit is contained in:
Naz 2022-09-20 17:08:10 +08:00 committed by naz
parent 190031f38c
commit 2acb0fca74
2 changed files with 16 additions and 6 deletions

View File

@ -7,7 +7,7 @@ const config = require('../../../shared/config');
const renderer = require('../../services/rendering'); const renderer = require('../../services/rendering');
// @TODO: make this properly shared code // @TODO: make this properly shared code
const {prepareError, prepareStack} = require('@tryghost/mw-error-handler'); const {prepareError, prepareErrorCacheControl, prepareStack} = require('@tryghost/mw-error-handler');
const messages = { const messages = {
oopsErrorTemplateHasError: 'Oops, seems there is an error in the error template.', oopsErrorTemplateHasError: 'Oops, seems there is an error in the error template.',
@ -86,6 +86,8 @@ const themeErrorRenderer = (err, req, res, next) => {
module.exports.handleThemeResponse = [ module.exports.handleThemeResponse = [
// Make sure the error can be served // Make sure the error can be served
prepareError, prepareError,
// Add cache-control header
prepareErrorCacheControl,
// Handle the error in Sentry // Handle the error in Sentry
sentry.errorHandler, sentry.errorHandler,
// Format the stack for the user // Format the stack for the user

View File

@ -90,11 +90,6 @@ module.exports.prepareError = (err, req, res, next) => {
// alternative for res.status(); // alternative for res.status();
res.statusCode = err.statusCode; res.statusCode = err.statusCode;
// never cache errors
res.set({
'Cache-Control': 'no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0'
});
next(err); next(err);
}; };
@ -122,6 +117,17 @@ const jsonErrorRenderer = (err, req, res, next) => { // eslint-disable-line no-u
}); });
}; };
module.exports.prepareErrorCacheControl = (err, req, res, next) => {
// never cache errors
let cacheControl = 'no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0';
res.set({
'Cache-Control': cacheControl
});
next(err);
};
const prepareUserMessage = (err, req) => { const prepareUserMessage = (err, req) => {
const userError = { const userError = {
message: err.message, message: err.message,
@ -221,6 +227,8 @@ module.exports.pageNotFound = (req, res, next) => {
module.exports.handleJSONResponse = sentry => [ module.exports.handleJSONResponse = sentry => [
// Make sure the error can be served // Make sure the error can be served
module.exports.prepareError, module.exports.prepareError,
// Add cache-control header
module.exports.prepareErrorCacheControl,
// Handle the error in Sentry // Handle the error in Sentry
sentry.errorHandler, sentry.errorHandler,
// Format the stack for the user // Format the stack for the user