-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvalid-param.min.js
1 lines (1 loc) · 1.56 KB
/
valid-param.min.js
1
import{throwRequiredParamError,throwTypeError}from"./errors.js";export default class{constructor(parameters,type_assignment){isObject(parameters)||throwTypeError("parameters","object"),isObject(parameters)||throwTypeError("type_assignment","object"),this.params=parameters,this.assignments=type_assignment,this.validate()}validate(){for(const key in this.assignments){let value=this.params[key],type=typeof value,string=this.assignments[key];string||(string="null"),isNullable(string)||value||throwRequiredParamError(key),isNullable(string)&&(string=handleNull(string));let types=string.split("|");isValid(value,types)||throwTypeError(key,types,type)}}}function isNullable(str){return"?"==str.charAt(0)||str.includes("null")}function handleNull(str){return str.includes("?")&&(str=str.replace("?","")),str.includes("null")||(str=`${str}|null`),str}function capitalizeFirstLetter(str){return str.charAt(0).toUpperCase()+str.slice(1)}function isValid(str,types){const available_types=[["string","str"],["number","num","int"],["boolean","bool"],["array","arr"],["object","obj"],["null","undefined"]];let bool=!1;return types.forEach((function(type){available_types.forEach((function(variations){variations.forEach((function(variation){type==variation&&eval(`is${capitalizeFirstLetter(variations[0])}(str)`)&&(bool=!0)}))}))})),bool}const isString=value=>"string"==typeof value,isNumber=value=>"number"==typeof value,isBoolean=value=>"boolean"==typeof value,isArray=value=>Array.isArray(value),isObject=value=>"[object Object]"===Object.prototype.toString.call(value),isNull=value=>!value||void 0===value;