UNPKG

@sprucelabs/schema

Version:

Static and dynamic binding plus runtime validation and transformation to ensure your app is sound. 🤓

70 lines (69 loc) • 2.54 kB
import { assert, assertUtil } from '@sprucelabs/test-utils'; import SpruceError from '../errors/SpruceError.js'; 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: ${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) { var _a, _b; const missing = []; const err = error; if (!err) { missing.push('error'); } if (!options) { missing.push('options'); } if (missing.length > 0) { throw new SpruceError({ code: 'MISSING_PARAMETERS', parameters: missing, }); } if (((_a = err.options) === null || _a === void 0 ? void 0 : _a.code) !== 'VALIDATION_FAILED') { throw new SpruceError({ 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 (_b = options === null || options === void 0 ? void 0 : options[key]) !== null && _b !== void 0 ? _b : []) { const match = flattened[lookup] === code; if (!match) { assert.fail(buildFailMessage(code, lookup, flattened)); } } } }, }; export default validationErrorAssert;