@n1k1t/mock-server
Version:
The ultimate toolkit to intercept, transform, and simulate HTTP/WS traffic with type-safe expectations
76 lines • 3.09 kB
JavaScript
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const lodash_1 = __importDefault(require("lodash"));
const utils_1 = require("../utils");
const operator_1 = require("../models/operator");
class SwitchExpectationOperator extends operator_1.ExpectationOperator {
constructor() {
super(...arguments);
this.compiled = {
cases: Object
.entries(this.command.$cases)
.reduce((acc, [key, schema]) => {
const extracted = this.extractNestedSchema(schema);
if (!extracted) {
return acc;
}
const Operator = this.operators[extracted.key];
return lodash_1.default.set(acc, key, new Operator(this.operators, extracted.nested));
}, {}),
...(this.command.$default && {
default: (() => {
const extracted = this.extractNestedSchema(this.command.$default);
if (!extracted) {
return null;
}
const Operator = this.operators[extracted.key];
return new Operator(this.operators, extracted.nested);
})(),
}),
...(this.command.$exec && {
exec: this.compileExecHandler(this.command.$exec, ['payload', 'utils']),
}),
};
}
get tags() {
const acc = (0, utils_1.compileMetaTagsAccumulator)(this.command.$location);
return (0, utils_1.mergeMetaTags)([
acc?.(Object.keys(this.compiled.cases)) ?? {},
this.compiled.default?.tags ?? {},
...Object.values(this.compiled.cases).map((operator) => operator.tags),
]);
}
async match(context) {
const operator = await this.handle(context);
return (await operator?.match(context)) ?? false;
}
async manipulate(context) {
const operator = await this.handle(context);
await operator?.manipulate(context);
return context;
}
async handle(context) {
const value = await this.extractValue(context);
if (value === null) {
return this.compiled.default ?? null;
}
return lodash_1.default.get(this.compiled.cases, String(value)) ?? this.compiled.default ?? null;
}
async extractValue(context) {
const payload = (0, utils_1.extractContextByLocation)(this.command.$location, context);
if (!payload) {
return null;
}
if (this.compiled.exec) {
return this.compiled.exec('match', context, payload.value);
}
return this.command.$path
? payload.type === 'object' ? lodash_1.default.get(payload.value, this.command.$path) : payload.value
: payload.value;
}
}
exports.default = SwitchExpectationOperator;
//# sourceMappingURL=switch.operator.js.map