UNPKG

@smartlyio/oats-mirage-adapter

Version:

Mirage.js adapter for Oats

89 lines 3.44 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.bind = bind; const mirage = require("miragejs"); function guessContentType(contentTypeHeader, value) { if (contentTypeHeader?.includes('application/json')) { return 'application/json'; } if (contentTypeHeader) { return contentTypeHeader; } if (value instanceof FormData) { return 'multipart/form-data'; } return 'text/html'; } async function guessValue(contentType, value) { if (value instanceof FormData) { return await handleFormData(value); } if (contentType.match(/application\/json/) && value) { return JSON.parse(value); } return value; } async function handleFormData(value) { const result = {}; const keys = []; value.forEach((_, key) => keys.push(key)); for (const key of keys) { const keyValue = value.get(key); if (keyValue instanceof Blob) { result[key] = await keyValue.arrayBuffer(); } else if (typeof keyValue === 'string') { result[key] = keyValue; } } return result; } function adapter(mirageServer, requestContextCreator, opts) { // eslint-disable-next-line no-console, @typescript-eslint/no-empty-function const log = opts?.logging !== false ? console.log : () => { }; return (path, op, method, handler) => { const miragePath = path.replace(/{([^}]+)}/g, (m, param) => ':' + param); const mirageHandler = mirageServer[method]; mirageHandler(miragePath, async (schema, request) => { const headers = Object.keys(request.requestHeaders).reduce((lowerCaseHeaders, key) => { lowerCaseHeaders[key.toLowerCase()] = request.requestHeaders[key]; return lowerCaseHeaders; }, {}); const contentType = guessContentType(headers['content-type'], request.requestBody); const value = await guessValue(contentType, request.requestBody); const body = value != null ? { value, contentType } : undefined; const ctx = { path, method, servers: [], op, headers, params: request.params, query: request.queryParams, body, requestContext: requestContextCreator(schema, request) }; log('oats-mirage-adapter request', ctx); try { const result = await handler(ctx); log('oats-mirage-adapter response', { result }); return new mirage.Response(result.status, { ...result.headers, 'content-type': result.value.contentType }, result.value.contentType.match(/application\/json/) ? JSON.stringify(result.value.value) : result.value.value); } catch (error) { log('oats-mirage-adapter handler threw: ' + error.message, { error }); return new mirage.Response(400, { 'content-type': 'text/plain' }, 'Error from handler: ' + error.message); } }); }; } /** * Bind provided handlers for the OpenAPI routes */ function bind(opts) { opts.handler(adapter(opts.server, opts.requestContextCreator || (() => ({})), { logging: opts.logging ?? true }))(opts.spec); } //# sourceMappingURL=index.js.map