UNPKG

@coolio/http

Version:
35 lines 1.53 kB
import isNil from 'lodash/isNil'; import isString from 'lodash/isString'; import isBuffer from 'lodash/isBuffer'; import { getCaseConverter, getHeader } from './helpers'; import { urlEncode } from './helpers/urlEncoding.helper'; import { switchContentType } from './contentType'; import { CFormData } from './formData'; export const bodySerializer = ({ bodyCasing, } = {}) => { const caseConverter = getCaseConverter(bodyCasing); const bodySerializers = { JSON: (body) => JSON.stringify(caseConverter(body)), URL_ENCODED: (body) => urlEncode(caseConverter(body)), MULTIPART: (body) => CFormData.from(caseConverter(body)), TEXT: (body) => String(body), }; return (options) => { const contentTypeHeader = getHeader(options.headers, 'content-type') || ''; const contentType = contentTypeHeader.split(';') .map(type => type.trim().toLowerCase()); const body = options.body; if (isNil(body) || isString(body) || isBuffer(body) || CFormData.isFormData(body)) { return body; } if (typeof body === 'object') { for (const type of contentType) { const serializedBody = switchContentType(type, bodySerializers); if (serializedBody) { return serializedBody(body); } } } throw new Error(`Can not serialize request body. Content-Type "${contentTypeHeader}"`); }; }; //# sourceMappingURL=bodySerializer.js.map