UNPKG

@juntoz/koa-require-header

Version:

Koa middleware to require an http header and write to state variable

43 lines (33 loc) 1.22 kB
const { camelCase } = require('change-case'); function _defaultOptions() { return { headerName: null, stateName: null, ifNotFound: 'throw', // throw, ignore ignorePaths: [] }; } function setup(options) { options = Object.assign(_defaultOptions(), options); if (!options.ignorePaths) { options.ignorePaths = []; } if (!options.stateName) { // convert e.g. X-FORWARD-IP to xForwardIp options.stateName = camelCase(options.headerName); } return async(ctx, next) => { if (options.headerName && !options.ignorePaths.includes(ctx.path)) { // NOTE: it seems HTTP brings headers always in uppercase, yet the header object puts them all in lower case var headerValue = ctx.header[options.headerName.toLowerCase()]; if (!headerValue && options.ifNotFound === 'throw') { ctx.throw(400, `${options.headerName} is required`); } if (headerValue && options.stateName) { ctx.state[options.stateName] = headerValue; } } await next(); }; } module.exports = setup;