@sprucelabs/schema
Version:
Static and dynamic binding plus runtime validation and transformation to ensure your app is sound. 🤓
74 lines (73 loc) • 2.67 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const test_utils_1 = require("@sprucelabs/test-utils");
const SpruceError_1 = __importDefault(require("../errors/SpruceError"));
function buildFailMessage(code, name, options) {
const templates = {
INVALID_PARAMETER: `Expected '${name}' to be invalid. But it appears it is.`,
MISSING_PARAMETER: `I found '${name}' even though it should be reported as missing.`,
UNEXPECTED_PARAMETER: `I was expecting to unexpectedly find '${name}', but I didn't.`,
};
return `${templates[code]}\n\nHere is the error I got: ${test_utils_1.assertUtil.stringify(options)}`;
}
function flattenFields(fieldErrors, flattened, namePrefix = '') {
fieldErrors.forEach((err) => {
const name = namePrefix + err.name;
flattened[name] = err.code;
if (err.errors) {
flattenFields(err.errors, flattened, name + '.');
}
});
}
const validationErrorAssert = {
assertError(error, options) {
const missing = [];
const err = error;
if (!err) {
missing.push('error');
}
if (!options) {
missing.push('options');
}
if (missing.length > 0) {
throw new SpruceError_1.default({
code: 'MISSING_PARAMETERS',
parameters: missing,
});
}
if (err.options?.code !== 'VALIDATION_FAILED') {
throw new SpruceError_1.default({
code: 'INVALID_PARAMETERS',
parameters: ['error'],
friendlyMessage: `Expected error to be SchemaError({code: 'VALIDATION_FAILED'})`,
});
}
const keys = [
'missing',
'invalid',
'unexpected',
];
const codes = [
'MISSING_PARAMETER',
'INVALID_PARAMETER',
'UNEXPECTED_PARAMETER',
];
const fieldErrors = err.options.errors;
const flattened = {};
flattenFields(fieldErrors, flattened);
for (let idx = 0; idx < keys.length; idx++) {
const code = codes[idx];
const key = keys[idx];
for (const lookup of options?.[key] ?? []) {
const match = flattened[lookup] === code;
if (!match) {
test_utils_1.assert.fail(buildFailMessage(code, lookup, flattened));
}
}
}
},
};
exports.default = validationErrorAssert;