@n1k1t/mock-server
Version:
Powerful util to setup mocks over HTTP APIs
78 lines • 3.15 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 operator_1 = require("../models/operator");
const utils_1 = require("../utils");
const types_1 = require("../types");
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() {
return [
...(types_1.LExpectationMetaTagLocation.includes(this.command.$location)
? Object.keys(this.compiled.cases).map((value) => ({ location: this.command.$location, value }))
: []),
...Object.values(this.compiled.cases).reduce((acc, operator) => acc.concat(operator.tags), []),
...(this.compiled.default?.tags ?? []),
];
}
match(context) {
const operator = this.handle(context);
return operator?.match(context) ?? false;
}
manipulate(context) {
const operator = this.handle(context);
operator?.manipulate(context);
return context;
}
handle(context) {
const value = 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;
}
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