UNPKG

@chubbyts/chubbyts-api

Version:

[![CI](https://github.com/chubbyts/chubbyts-api/workflows/CI/badge.svg?branch=master)](https://github.com/chubbyts/chubbyts-api/actions?query=workflow%3ACI) [![Coverage Status](https://coveralls.io/repos/github/chubbyts/chubbyts-api/badge.svg?branch=maste

39 lines (38 loc) 1.61 kB
import { isObject, isArray, isBoolean, isNumber, isString } from '@chubbyts/chubbyts-decode-encode/dist'; import { EncodeError } from '@chubbyts/chubbyts-decode-encode/dist/encoder'; import { isHttpError } from '@chubbyts/chubbyts-http-error/dist/http-error'; export const valueToData = (value) => { if (isObject(value)) { return Object.fromEntries(Object.entries(value) .filter(([_, subValue]) => subValue !== undefined) .map(([subKey, subValue]) => [subKey, valueToData(subValue)])); } else if (isArray(value)) { return value.filter((subValue) => subValue !== undefined).map(valueToData); } else if (isString(value) || isNumber(value) || isBoolean(value) || value === null) { return value; } else if (value instanceof Date) { return value.toJSON(); } else if (isHttpError(value)) { return valueToData({ ...value }); } throw new EncodeError(`Unsupported value of type ${typeof value === 'object' ? value.constructor.name : typeof value}`); }; export const stringifyResponseBody = (request, response, encoder, data) => { if (!data) { response.body.end(); return response; } const accept = request.attributes.accept; if (!accept) { throw new Error('Use createAcceptNegotiationMiddleware to assign request.attributes.accept.'); } if (!encoder) { throw new Error('Missing encoder'); } response.body.end(encoder.encode(data, accept, { request })); return { ...response, headers: { ...response.headers, 'content-type': [accept] } }; };