UNPKG

@routup/body

Version:
105 lines (96 loc) 2.79 kB
import { json, raw, text, urlencoded } from 'body-parser'; import { coreHandler } from 'routup'; function createJsonHandler(options) { const handler = json(options); return coreHandler((req, res, next)=>{ handler(req, res, next); }); } function createRawHandler(options) { const handler = raw(options); return coreHandler((req, res, next)=>{ handler(req, res, next); }); } function createTextHandler(options) { const handler = text(options); return coreHandler((req, res, next)=>{ handler(req, res, next); }); } function createUrlEncodedHandler(options) { const handler = urlencoded({ extended: false, ...options || {} }); return 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 }; } export { body, createJsonHandler, createRawHandler, createTextHandler, createUrlEncodedHandler, body as default, setRequestBody, useRequestBody }; //# sourceMappingURL=index.mjs.map