UNPKG

es-dev-server

Version:

Development server for modern web apps

60 lines 2.17 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.createResponseTransformMiddleware = void 0; const utils_1 = require("../utils/utils"); function createResponseTransformMiddleware(config) { return async function responseTransformMiddlewareConfig(ctx, next) { await next(); let body; try { body = await utils_1.getBodyAsString(ctx); } catch (error) { if (error instanceof utils_1.RequestCancelledError) { return; } if (error instanceof utils_1.IsBinaryFileError) { return; } throw error; } let newBody = body; let newContentType = ctx.response.get('content-type'); let changedBody = false; let changedContentType = false; // execute transformers in order, not parallel for (const transformer of config.responseTransformers) { const result = await transformer({ url: ctx.url, headers: ctx.headers, status: ctx.status, contentType: newContentType, body: newBody, }); if (result) { if (typeof result.body === 'string') { newBody = result.body; changedBody = true; } if (result.contentType) { newContentType = result.contentType; changedContentType = true; } } if (result && result.body) { newBody = result.body; } } // if the body was transformed, we always serve it as 200. this allows serving a // virtual file which doesn't exist (404 on the file system) if (changedBody) { ctx.status = 200; ctx.body = newBody; } if (changedContentType) { ctx.response.set('content-type', newContentType); } }; } exports.createResponseTransformMiddleware = createResponseTransformMiddleware; //# sourceMappingURL=response-transform.js.map