UNPKG

@ents24/be-sure

Version:

NPM module for terse, 'throwy' validation

68 lines (67 loc) 2.79 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.beSureCustom = exports.beSureAllowNull = exports.beSure = void 0; const validation_error_1 = __importDefault(require("./validation-error")); const validators_1 = require("./validators"); /** * Find a validator that matches `key`, run it with the passed `value`, throw on failure * @param {Mixed} value the value to check * @param {String} key the validator key to check against * @param {any} errorType a type that extends Error * @param {String | undefined} errorText the text to include if an error is thrown * @throws A validator matching the passed key must exist and return true */ function beSure(value, key, errorType, errorText) { const validator = (0, validators_1.getValidator)(key); if (typeof validator !== 'function') { throw `No validator found for key: ${key}`; } if (validator(value) === false) { fail(value, key, errorType, errorText); } } exports.beSure = beSure; /** * Find a validator that matches `key`, run it with the passed `value`, throw on failure * Never throw on `null` value * @param {Mixed} value the value to check * @param {String} key the validator key to check against * @param {any} errorType a type that extends Error * @param {String | undefined} errorText the text to include if an error is thrown * @throws A validator matching the passed key must exist and return true */ function beSureAllowNull(value, key, errorType, errorText) { if (value !== null) { beSure(value, key, errorType, errorText); } } exports.beSureAllowNull = beSureAllowNull; function beSureCustom(value, customKey, errorType, errorText) { const validator = (0, validators_1.getCustomValidator)(customKey); if (typeof validator !== 'function') { throw `No validator found for key: ${customKey}`; } if (validator(value) === false) { fail(value, customKey, errorType, errorText); } } exports.beSureCustom = beSureCustom; function fail(value, key, errorType, errorText) { // Apply errorText or default error text if (typeof errorText !== 'string') { errorText = `${decorateValue(value)} failed validation for: ${key}`; } // Throw errorType or default ValidationError if (typeof errorType === 'function' && errorType.prototype instanceof Error) { throw new errorType(errorText); } throw new validation_error_1.default(errorText); } /** * Decorate a value to make log output more readable. Currently just wraps * strings in quotes */ const decorateValue = (value) => typeof value === 'string' ? `'${value}'` : value;