request-mocking-protocol
Version:
A protocol for declarative mocking of HTTP requests
69 lines • 2.22 kB
JavaScript
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.BodyMatcher = void 0;
/**
* Body matcher.
*/
const isMatch_1 = __importDefault(require("lodash/isMatch"));
class BodyMatcher {
schema;
constructor(schema) {
this.schema = schema;
}
get expectedBody() {
return this.schema.body;
}
get expectedBodyStr() {
return typeof this.expectedBody === 'string'
? this.expectedBody
: JSON.stringify(this.expectedBody);
}
async match(ctx) {
if (!this.expectedBody)
return true;
const actualBodyStream = this.schema.body;
if (!actualBodyStream) {
ctx.log(false, `body`, this.expectedBodyStr, `null`);
return false;
}
if (typeof this.expectedBody === 'string') {
return this.matchAsString(ctx, this.expectedBody);
}
else {
return this.matchAsObject(ctx, this.expectedBody);
}
}
async matchAsString(ctx, expectedBody) {
const actualBody = await ctx.req.clone().text();
const result = actualBody === expectedBody;
ctx.log(result, `body`, expectedBody, trimLongString(actualBody));
return result;
}
async matchAsObject(ctx, expectedBody) {
const actualBody = await ctx.req.clone().text();
const actualBodyParsed = jsonParseSafe(actualBody);
if (!actualBodyParsed) {
ctx.log(false, `body`, this.expectedBodyStr, trimLongString(actualBody));
return false;
}
const result = (0, isMatch_1.default)(actualBodyParsed, expectedBody);
ctx.log(result, `body`, this.expectedBodyStr, trimLongString(actualBody));
return result;
}
}
exports.BodyMatcher = BodyMatcher;
function trimLongString(str, maxLength = 150) {
return str.length > maxLength ? `${str.slice(0, maxLength)}...` : str;
}
function jsonParseSafe(str) {
try {
return JSON.parse(str);
}
catch {
return null;
}
}
//# sourceMappingURL=body.js.map