UNPKG

@apolitical/server

Version:

Node.js module to encapsulate Apolitical's express server setup

33 lines (27 loc) 842 B
'use strict'; module.exports = ({ morgan, config, logger }) => { const { LOGGED_OUT_ID, TOKENS: { USER_ID }, } = config.SERVER.MORGAN_OPTIONS; function getUserId(req) { return req.user && req.user.id ? req.user.id : LOGGED_OUT_ID; } function buildCustomFormat(tokens, req, res) { return [ tokens.method(req, res), tokens.url(req, res), tokens.status(req, res), tokens[USER_ID](req), tokens['response-time'](req, res), 'ms', ].join(' '); } function buildMiddleware(labels) { // Setup Morgan with custom format and Apolitical Logger stream morgan.token(USER_ID, getUserId); const morganMiddleware = morgan(buildCustomFormat, logger.where(__filename, 'morganMiddleware', labels)); return morganMiddleware; } return { getUserId, buildMiddleware }; };