UNPKG

@rashedmakkouk/dev-utils

Version:
50 lines (49 loc) 2.04 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); /** Utilities */ const isArray_1 = __importDefault(require("lodash/isArray")); const isNumber_1 = __importDefault(require("lodash/isNumber")); const isPlainObject_1 = __importDefault(require("lodash/isPlainObject")); const isString_1 = __importDefault(require("lodash/isString")); /* eslint-disable-next-line no-control-regex */ const FIRST_CHAR_REGEXP = /^[\x20\x09\x0a\x0d]*(.)/; const NULLISH_VALUES = ['null', 'undefined']; const BOOLEAN_VALUES = ['false', 'true']; /** * Verifies if supplied payload is valid by defined type. */ function isValid(isTypeof, value, options = {}) { const { allowEmpty } = options; if (value == null) { return allowEmpty === true ? true : false; } switch (isTypeof) { case 'array': return (0, isArray_1.default)(value) && (!!value.length || allowEmpty === true); case 'jsonStr': { if (!value || !(0, isString_1.default)(value)) { return false; } const firstChar = FIRST_CHAR_REGEXP.exec(value)?.[1]; const lowerCaseValue = value.toLowerCase(); return (firstChar === '{' || firstChar === '[' || NULLISH_VALUES.includes(lowerCaseValue) || BOOLEAN_VALUES.includes(lowerCaseValue)); } case 'number': return (0, isNumber_1.default)(value) && (value !== 0 || allowEmpty === true); case 'object': return ((0, isPlainObject_1.default)(value) && (!!Object.keys(value).length || allowEmpty === true)); case 'string': if (!(0, isString_1.default)(value) || NULLISH_VALUES.includes(value.toLowerCase())) { return false; } return !!value.length || allowEmpty === true; } } exports.default = isValid;