@contract-case/case-core-plugin-http
Version:
ContractCase core HTTP plugin, providing HTTP matchers and mocks
56 lines • 3.24 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.HttpStatusCodeMatcher = void 0;
const case_plugin_base_1 = require("@contract-case/case-plugin-base");
const codeValidator_1 = require("./codeValidator");
const statusCodeExample = (matcher, matchContext) => '_case:matcher:example' in matcher && matcher['_case:matcher:example'] != null
? matcher['_case:matcher:example']
: (0, codeValidator_1.validateCodes)(matcher['_case:matcher:rule'], matchContext);
const checkExample = (rule, actual, makeError) => {
if (typeof actual !== 'number')
return (0, case_plugin_base_1.makeResults)(makeError(`Inappropriate type '${typeof actual}' for HTTP status code - must be a number`));
switch (typeof rule) {
case 'number':
return (0, case_plugin_base_1.errorWhen)(actual !== rule, makeError(`Status code ${(0, case_plugin_base_1.actualToString)(actual)} is not equal to '${rule}'`));
case 'string': {
const actualAsString = `${actual}`;
if (actualAsString.length !== 3) {
return (0, case_plugin_base_1.makeResults)(makeError(`Status code ${(0, case_plugin_base_1.actualToString)(actual)} does not appear to be the right length`));
}
for (let i = 0; i < rule.length; i += 1) {
if (rule.charAt(i) !== 'x' &&
rule.charAt(i) !== 'X' &&
actualAsString.charAt(i) !== rule.charAt(i)) {
return (0, case_plugin_base_1.makeResults)(makeError(`Status code ${(0, case_plugin_base_1.actualToString)(actual)} does not match '${rule}'`));
}
}
return (0, case_plugin_base_1.makeResults)();
}
default:
throw new case_plugin_base_1.CaseCoreError(`Inappropriate type '${typeof rule}' for HTTP status code matching rule.`);
}
};
const check = (matcher, matchContext, actual) => {
const makeError = (message) => (0, case_plugin_base_1.matchingError)(matcher, message, actual, matchContext);
if (Array.isArray(matcher['_case:matcher:rule'])) {
const result = matcher['_case:matcher:rule']
.map((e) => checkExample(e, actual, makeError))
.find(case_plugin_base_1.hasNoErrors);
return result !== undefined
? result
: (0, case_plugin_base_1.makeResults)((0, case_plugin_base_1.matchingError)(matcher, `The returned http status code (${(0, case_plugin_base_1.actualToString)(actual)}) did not match any of the following status codes: ${matcher['_case:matcher:rule'].join(', ')}`, actual, matchContext));
}
return checkExample(matcher['_case:matcher:rule'], actual, makeError);
};
const validate = (matcher, matchContext) => Promise.resolve().then(() => {
statusCodeExample(matcher, matchContext);
});
exports.HttpStatusCodeMatcher = {
describe: (matcher) => `httpStatus ${Array.isArray(matcher['_case:matcher:rule'])
? matcher['_case:matcher:rule'].map((r) => `${r}`).join(' | ')
: matcher['_case:matcher:rule']}`,
check,
strip: (matcher, matchContext) => statusCodeExample(matcher, matchContext),
validate,
};
//# sourceMappingURL=HttpStatusCodeMatcher.js.map