src/middleware.js
import {app} from './application';
/**
* Creates a middleware function managing the application errors.
* @return {function} The created middleware function.
*/
export function errorHandler() {
return async (ctx, next) => {
try {
await next();
}
catch (err) {
let {message, name, status} = err;
let model = {message, name, status: typeof status == 'number' ? status : 500};
if (app().debug) model.stack = err.stack;
ctx.body = model;
ctx.status = model.status;
}
};
}
/**
* Creates a middleware function setting some security-related headers.
* @return {function} The created middleware function.
*/
export function securityHandler() {
return async (ctx, next) => {
ctx.remove('X-Powered-By');
ctx.set('X-Content-Type-Options', 'nosniff');
ctx.set('X-Frame-Options', 'SAMEORIGIN');
return next();
};
}
/**
* Creates a middleware function sending the application status.
* @return {function} The created middleware function.
*/
export function statusHandler() {
let startDate = new Date;
return async ctx => {
let {name, version} = app();
let uptime = Math.ceil((Date.now() - startDate.getTime()) / 1000);
ctx.body = {name, started: startDate.toISOString(), uptime, version};
};
}