UNPKG

request-mocking-protocol

Version:
112 lines 3.61 kB
"use strict"; /** * Module to patch fetch request. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.RequestPatcher = void 0; const placeholders_1 = require("../response-builder/placeholders"); const utils_1 = require("../response-builder/utils"); class RequestPatcher { req; overrides; params; url; headers; body; constructor(req, overrides, params = {}) { this.req = req; this.overrides = overrides; this.params = params; this.url = new URL(req.url); this.headers = new Headers(req.headers); } async patch() { this.patchUrl(); this.patchQuery(); this.patchHeaders(); await this.patchBody(); return this.buildRequest(); } patchUrl() { const { url } = this.overrides; if (!url) return; const newUrl = (0, placeholders_1.replacePlaceholders)(url, this.params); this.url = new URL(newUrl); } patchQuery() { const { query } = this.overrides; if (!query) return; Object.keys(query).forEach((key) => { const value = query[key]; if (value) { this.url.searchParams.set(key, String(value)); } else { this.url.searchParams.delete(key); } }); } patchHeaders() { this.headers.set('content-encoding', 'identity'); Object.entries(this.overrides.headers || {}).forEach(([key, value]) => { if (value) { this.headers.set(key, String(value)); } else { this.headers.delete(key); } }); } // eslint-disable-next-line max-statements async patchBody() { const { body, bodyPatch } = this.overrides; if (body === null) { this.body = null; return; } if (body) { if (typeof body === 'string') { const newBody = (0, placeholders_1.replacePlaceholders)(body, this.params); this.setBodyAsString(newBody, 'text/plain'); } else { const newBody = (0, placeholders_1.stringifyWithPlaceholders)(body, this.params); this.setBodyAsString(newBody, 'application/json'); } } else if (bodyPatch) { const actualBody = await this.req.json(); const bodyPatchFinal = (0, placeholders_1.cloneWithPlaceholders)(bodyPatch, this.params); (0, utils_1.patchObject)(actualBody, bodyPatchFinal); this.setBodyAsString(JSON.stringify(actualBody), 'application/json'); } } setBodyAsString(body, contentType) { this.body = body; if (!this.headers.has('content-type')) { this.headers.set('content-type', contentType); } const contentLength = body ? new Blob([body]).size.toString() : '0'; this.headers.set('content-length', contentLength); } buildRequest() { const { req } = this; return new Request(this.url, { headers: this.headers, body: this.body, method: req.method, mode: req.mode, credentials: req.credentials, cache: req.cache, redirect: req.redirect, referrer: req.referrer, integrity: req.integrity, keepalive: req.keepalive, signal: req.signal, }); } } exports.RequestPatcher = RequestPatcher; //# sourceMappingURL=index.js.map