UNPKG

validator-tsk

Version:
49 lines (48 loc) 2.01 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Validator = void 0; const BAD_REQUEST = "400"; const JOIN_SEPARATOR = ", "; class Validator { constructor(resources, resourceKey, defaultErrorCode = BAD_REQUEST) { this.resources = resources; this.resourceKey = resourceKey; this.defaultErrorCode = defaultErrorCode; } isValidEntry(result, paramsToValidate, errorCode) { let isValid = true; const keysToValidate = Object.keys(paramsToValidate); const keysNotFound = []; keysToValidate.forEach((key) => { if (!Reflect.has(paramsToValidate, key) || !Reflect.get(paramsToValidate, key)) { keysNotFound.push(key); } else if (Array.isArray(paramsToValidate[key])) { const validations = paramsToValidate[key]; validations.forEach((validation) => { if (typeof validation !== "function") { throw new Error("Validator-tsk only allows function arrays. It cannot pass object arrays."); } const resultMessage = validation(); if (resultMessage === null || resultMessage === true || resultMessage === "") { return; } if (typeof resultMessage === "string") { keysNotFound.push(resultMessage); } else { keysNotFound.push(key); } }); } }); if (keysNotFound === null || keysNotFound === void 0 ? void 0 : keysNotFound.length) { result.setError(this.resources.getWithParams(this.resourceKey, { missingParams: keysNotFound.join(JOIN_SEPARATOR), }), errorCode || this.defaultErrorCode); isValid = false; } return isValid; } } exports.Validator = Validator;