Skip to content

Commit

Permalink
Merge pull request #800 from Financial-Times/add-via-headers
Browse files Browse the repository at this point in the history
Send a Via response header
  • Loading branch information
rowanmanning authored Nov 24, 2023
2 parents 8bf8ba1 + 480174d commit ffe0a25
Show file tree
Hide file tree
Showing 3 changed files with 63 additions and 0 deletions.
4 changes: 4 additions & 0 deletions main.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ const teapot = fs.readFileSync(
path.join(__dirname, 'src/assets/teapot.ascii'),
'utf8'
);
const generateViaMiddleware = require('./src/middleware/via');

/**
* @param {AppOptions} options
Expand Down Expand Up @@ -98,6 +99,9 @@ const getAppContainer = (options) => {
app.set('x-powered-by', false);
app.use(security);

// Add the application system code to the Via HTTP header
app.use(generateViaMiddleware(meta.systemCode));

// utility middleware
app.use(vary);

Expand Down
16 changes: 16 additions & 0 deletions src/middleware/via.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
/**
* @typedef {import("../../typings/n-express").Callback} Callback
*/

/**
* @param {string} systemCode
* @returns {Callback}
*/
module.exports = function generateViaMiddleware (systemCode) {
return (request, response, next) => {
const requestVia = request.get('via');
const appViaEntry = `${request.httpVersion} ${systemCode}`;
response.set('via', requestVia ? `${requestVia}, ${appViaEntry}` : appViaEntry);
next();
};
};
43 changes: 43 additions & 0 deletions test/middleware/via.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
const generateViaMiddleware = require('../../src/middleware/via');
const sinon = require('sinon');
const sinonChai = require('sinon-chai');
const chai = require('chai');
const expect = chai.expect;
chai.use(sinonChai);

describe('via middleware', function () {
let middleware;
let request;
let response;
let next;

beforeEach(() => {
request = {
get: sinon.stub().withArgs('via').returns(undefined),
httpVersion: 'mock-http-version'
};
response = {
set: sinon.spy()
};
next = sinon.spy();
middleware = generateViaMiddleware('mock-system');
});

describe('when no request Via header is present', () => {
it('sends a response Via header set to the application system code', () => {
middleware(request, response, next);
expect(response.set).calledWithExactly('via', 'mock-http-version mock-system');
expect(next).calledWithExactly();
});
});

describe('when a request Via header is present', () => {
it('sends a response Via header appending the application system code', () => {
request.get.withArgs('via').returns('mock-request-via');
middleware(request, response, next);
expect(response.set).calledWithExactly('via', 'mock-request-via, mock-http-version mock-system');
expect(next).calledWithExactly();
});
});

});

0 comments on commit ffe0a25

Please sign in to comment.