UNPKG

@routup/body

Version:
117 lines (106 loc) 3.15 kB
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var bodyParser = require('body-parser'); var routup = require('routup'); function createJsonHandler(options) { const handler = bodyParser.json(options); return routup.coreHandler((req, res, next)=>{ handler(req, res, next); }); } function createRawHandler(options) { const handler = bodyParser.raw(options); return routup.coreHandler((req, res, next)=>{ handler(req, res, next); }); } function createTextHandler(options) { const handler = bodyParser.text(options); return routup.coreHandler((req, res, next)=>{ handler(req, res, next); }); } function createUrlEncodedHandler(options) { const handler = bodyParser.urlencoded({ extended: false, ...options || {} }); return routup.coreHandler((req, res, next)=>{ handler(req, res, next); }); } function boolToObject(input) { if (typeof input === 'boolean') { return {}; } return input; } function isObject(item) { return !!item && typeof item === 'object' && !Array.isArray(item); } function body(options = {}) { if (typeof options.json === 'undefined' && typeof options.raw === 'undefined' && typeof options.urlEncoded === 'undefined' && typeof options.text === 'undefined') { options.json = true; options.urlEncoded = true; } return { name: 'body', install: (router)=>{ if (options.json) { router.use(createJsonHandler(boolToObject(options.json))); } if (options.raw) { router.use(createRawHandler(boolToObject(options.raw))); } if (options.text) { router.use(createTextHandler(boolToObject(options.text))); } if (options.urlEncoded) { router.use(createUrlEncodedHandler(boolToObject(options.urlEncoded))); } } }; } const BodySymbol = Symbol.for('ReqBody'); function useRequestBody(req, key) { let body; /* istanbul ignore next */ if ('body' in req) { body = req.body; } if (BodySymbol in req) { if (body) { body = { ...req[BodySymbol], ...body }; } else { body = req[BodySymbol]; } } if (body) { if (typeof key === 'string') { return body[key]; } return body; } return typeof key === 'string' ? undefined : {}; } function setRequestBody(req, key, value) { if (isObject(key)) { req[BodySymbol] = key; return; } req[BodySymbol] = { [key]: value }; } exports.body = body; exports.createJsonHandler = createJsonHandler; exports.createRawHandler = createRawHandler; exports.createTextHandler = createTextHandler; exports.createUrlEncodedHandler = createUrlEncodedHandler; exports.default = body; exports.setRequestBody = setRequestBody; exports.useRequestBody = useRequestBody; module.exports = Object.assign(exports.default, exports); //# sourceMappingURL=index.cjs.map