UNPKG

koas-serializer

Version:

Koas serializer converts a response body to the negotiated response format.

43 lines (42 loc) 1.89 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.serializer = void 0; const type_is_1 = require("type-is"); const defaultSerializers = { 'application/json': (body) => JSON.stringify(body), 'text/*': (body) => (body instanceof Buffer ? body : String(body)), }; /** * Serialize a response body based on the accept header. * * Default serializers have been registered for `application/json` and `text/*`. * * @param options - The options for serializeing the response body. * @returns A Koas plugin which serializes the response body bases on the accept header. */ function serializer({ serializers = {} } = {}) { const allSerializers = { ...defaultSerializers, ...serializers, }; const supportedMimeTypes = Object.keys(allSerializers).sort((a, b) => (a > b ? -1 : 1)); return ({ resolveRef }) => async (ctx, next) => { await next(); const { body, openApi, request } = ctx; const { operationObject } = openApi; const responseObject = resolveRef(operationObject.responses[ctx.status] || operationObject.responses.default); if (responseObject === null || responseObject === void 0 ? void 0 : responseObject.content) { const contentType = request.accepts(Object.keys(responseObject.content)); ctx.assert(contentType, 406); const type = supportedMimeTypes.find((m) => (0, type_is_1.is)(contentType, m)); // If type is null, this means a type was specified in the api specification, but no // serializer has been registered. Let’s assume in this case a developer has serialized the // body some other way. if (type != null) { ctx.body = allSerializers[type](body, ctx); ctx.type = contentType; } } }; } exports.serializer = serializer;