Skip to content

Commit

Permalink
refactor: organize between middlewares and routes
Browse files Browse the repository at this point in the history
It will make the app.js file much more simple to read and every little
execution is moved to a module that can easily be tested.
Mateu Aguiló Bosch committed May 28, 2018
1 parent 2e0a100 commit 2c5e925
Showing 12 changed files with 63 additions and 26 deletions.
1 change: 1 addition & 0 deletions .emdaer/docs/notes.md
Original file line number Diff line number Diff line change
@@ -16,3 +16,4 @@ just meant to save ideas for documentation to process some other time._
- Validate the request bodies before reaching the CMS using the resource schemas.
- Filter requests that the CMS should not be bothered with using the resource lists.
- Make sure to mention that the _Contenta Redis_ module needs to be enabled.
- Make sure to mention that the /healthckeck is for auto-scaling policies.
35 changes: 12 additions & 23 deletions src/helpers/app.js
Original file line number Diff line number Diff line change
@@ -9,11 +9,12 @@ const bodyParser = require('body-parser');
const config = require('config');
const express = require('express');

const cmsHost = config.get('cms.host');

const cacheControl = require('./cacheControl');
const errorHandler = require('./errorHandler');
const proxyHandler = require('./proxyHandler');
const cacheControl = require('../middlewares/cacheControl');
const copyToRequestObject = require('../middlewares/copyToRequestObject');
const customCors = require('../middlewares/customCors');
const errorHandler = require('../middlewares/errorHandler');
const healthcheck = require('../routes/healthcheck');
const proxyHandler = require('../routes/proxyHandler');

const app = express();
app.disable('x-powered-by');
@@ -22,28 +23,16 @@ app.disable('x-powered-by');
app.enable('etag');
app.set('etag', 'strong');
const jsonApiPrefix = `/${_.get(process, 'env.jsonApiPrefix')}`;
const cmsHost = config.get('cms.host');

// Add headers.
app.use((req, res, next) => {
// Enable CORS.
res.set('Access-Control-Allow-Origin', '*');
res.set(
'Access-Control-Allow-Headers',
config.get('cors.headers').join(', ')
);

// Set the cmsHost and jsonApiPrefix in the request.
req.cmsHost = cmsHost;
req.jsonApiPrefix = jsonApiPrefix;
// Initialize the request object with valuable information.
app.use(copyToRequestObject({ jsonApiPrefix, cmsHost }));

next();
});
// Add headers.
app.use(customCors);

// Healthcheck is a special endpoint used for application monitoring.
app.get('/healthcheck', (req, res) => {
res.set('Cache-Control', 'private, max-age=0, no-cache');
res.json({ meta: { healthcheck: 'good' } });
});
app.get('/healthcheck', healthcheck);

// Set cache control header.
app.use(cacheControl);
File renamed without changes.
File renamed without changes.
20 changes: 20 additions & 0 deletions src/middlewares/copyToRequestObject.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
// @flow

import type { ObjectLiteral } from '../../flow/types/common';

/**
* Returns a middleware that will copy all of the properties to the request.
*
* This is useful to store variables that will be used in any arbitrary
* middleware down the process.
*/
module.exports = (args: ObjectLiteral) => (
req: any,
res: any,
next: Function
): void => {
Object.keys(args).forEach(key => {
req[key] = args[key];
});
next();
};
16 changes: 16 additions & 0 deletions src/middlewares/customCors.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// @flow

const config = require('config');

/**
* A custom implementation of CORS.
*/
module.exports = (req: any, res: any, next: Function): void => {
// Enable CORS.
res.set('Access-Control-Allow-Origin', '*');
res.set(
'Access-Control-Allow-Headers',
config.get('cors.headers').join(', ')
);
next();
};
File renamed without changes.
File renamed without changes.
File renamed without changes.
11 changes: 11 additions & 0 deletions src/routes/healthcheck.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
// @flow

/**
* A healthcheck endpoint.
*
* Useful for auto-scaling policies, like EC2.
*/
module.exports = (req: any, res: any): void => {
res.set('Cache-Control', 'private, max-age=0, no-cache');
res.json({ meta: { healthcheck: 'good' } });
};
2 changes: 1 addition & 1 deletion src/helpers/proxyHandler.js → src/routes/proxyHandler.js
Original file line number Diff line number Diff line change
@@ -3,7 +3,7 @@
const _ = require('lodash');
const config = require('config');
const logger = require('pino')();
const fallbackToCms = require('./fallbackToCms');
const fallbackToCms = require('../middlewares/fallbackToCms');
const { redisGet } = require('../caching/drupalRedis')(
_.get(process, 'env.redisPrefix', ''),
_.get(process, 'env.redisCidTemplate', ''),
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
const proxyHandler = require('./proxyHandler');

jest.mock('./fallbackToCms');
jest.mock('../middlewares/fallbackToCms');
jest.mock('../caching/drupalRedis', () => () => ({
redisGet(uri) {
switch (uri) {
@@ -43,7 +43,7 @@ describe('The proxy middleware', () => {
let fallbackToCms;

beforeEach(() => {
fallbackToCms = require('./fallbackToCms');
fallbackToCms = require('../middlewares/fallbackToCms');
});

test('It falls back on cache miss', done => {

0 comments on commit 2c5e925

Please sign in to comment.