diff --git a/app/controllers/query_controller.js b/app/controllers/query_controller.js index 630f9a9a..6b4e2d69 100644 --- a/app/controllers/query_controller.js +++ b/app/controllers/query_controller.js @@ -20,6 +20,8 @@ const affectedTables = require('../middlewares/affected-tables'); const accessValidator = require('../middlewares/access-validator'); const queryMayWrite = require('../middlewares/query-may-write'); const cacheControl = require('../middlewares/cache-control'); +const cacheChannel = require('../middlewares/cache-channel'); +const surrogateKey = require('../middlewares/surrogate-key'); function QueryController(metadataBackend, userDatabaseService, statsd_client, userLimitsService) { this.metadataBackend = metadataBackend; @@ -48,6 +50,8 @@ QueryController.prototype.route = function (app) { accessValidator(), queryMayWrite(), cacheControl(), + cacheChannel(), + surrogateKey(), this.handleQuery.bind(this), errorMiddleware() ]; @@ -92,13 +96,6 @@ QueryController.prototype.handleQuery = function (req, res, next) { res.header("Content-Disposition", getContentDisposition(formatter, filename, useInline)); res.header("Content-Type", formatter.getContentType()); - // Only set an X-Cache-Channel for responses we want Varnish to cache. - var skipNotUpdatedAtTables = true; - if (!!affectedTables && affectedTables.getTables(skipNotUpdatedAtTables).length > 0 && !mayWrite) { - res.header('X-Cache-Channel', affectedTables.getCacheChannel(skipNotUpdatedAtTables)); - res.header('Surrogate-Key', affectedTables.key(skipNotUpdatedAtTables).join(' ')); - } - if(!!affectedTables) { res.header('Last-Modified', new Date(affectedTables.getLastUpdatedAt(Number(new Date()))).toUTCString()); diff --git a/app/middlewares/cache-channel.js b/app/middlewares/cache-channel.js new file mode 100644 index 00000000..b9cd461f --- /dev/null +++ b/app/middlewares/cache-channel.js @@ -0,0 +1,14 @@ +'use strict'; + +module.exports = function cacheChannel () { + return function cacheChannelMiddleware (req, res, next) { + const { affectedTables, mayWrite } = res.locals; + const skipNotUpdatedAtTables = true; + + if (!!affectedTables && affectedTables.getTables(skipNotUpdatedAtTables).length > 0 && !mayWrite) { + res.header('X-Cache-Channel', affectedTables.getCacheChannel(skipNotUpdatedAtTables)); + } + + next(); + }; +}; diff --git a/app/middlewares/surrogate-key.js b/app/middlewares/surrogate-key.js new file mode 100644 index 00000000..7cb803be --- /dev/null +++ b/app/middlewares/surrogate-key.js @@ -0,0 +1,14 @@ +'use strict'; + +module.exports = function surrogateKey () { + return function surrogateKeyMiddleware (req, res, next) { + const { affectedTables, mayWrite } = res.locals; + const skipNotUpdatedAtTables = true; + + if (!!affectedTables && affectedTables.getTables(skipNotUpdatedAtTables).length > 0 && !mayWrite) { + res.header('Surrogate-Key', affectedTables.key(skipNotUpdatedAtTables).join(' ')); + } + + next(); + }; +};