@codeparticle/formal
Version:
A <2kb library for validating data of any kind
1 lines • 1.84 kB
Source Map (JSON)
{"version":3,"sources":["../src/validation.ts"],"sourcesContent":["import { pipeValidators, ValidationError } from './internal/utils'\nimport { ValidationActions, ValidationM, ValidationRuleset } from './types'\n\n/**\n * convenience method to generate a Success or Fail with a custom message (or message function),\n * based on the passing of a supplied condition\n *\n */\n\nclass Validator implements Validator {\n static of(...rules: ValidationRuleset) {\n return new Validator(...rules)\n }\n\n rules: ValidationRuleset = []\n result: ValidationM | null = null\n\n constructor(...rules: ValidationRuleset) {\n this.rules = rules.flat()\n }\n\n /**\n * Run all of the supplied validators against the value that Validator() was supplied with,\n * then operate on the results based on whether this succeeded or failed.\n * @param {Object} opts\n * @property {Function} onSuccess\n * @property {Function} onFail\n *\n * @returns {Any} result\n */\n validate(value: any): Validator {\n this.result = pipeValidators(this.rules)(value)\n\n return this\n }\n\n // eslint-disable-next-line unicorn/no-thenable\n then(opts: ValidationActions) {\n if (this.result) {\n return this.result.fold(opts)\n } else {\n throw new ValidationError(\n `Validator failed to run - did you supply rules and use validate() first?`\n )\n }\n }\n}\n\nexport { Validator }\n"],"mappings":";;;;;;AASA,sBAAqC;AAAA,EAQnC,eAAe,OAA0B;AAHzC,iBAA2B,CAAC;AAC5B,kBAA6B;AAG3B,SAAK,QAAQ,MAAM,KAAK;AAAA,EAC1B;AAAA,SATO,MAAM,OAA0B;AACrC,WAAO,IAAI,UAAU,GAAG,KAAK;AAAA,EAC/B;AAAA,EAkBA,SAAS,OAAuB;AAC9B,SAAK,SAAS,eAAe,KAAK,KAAK,EAAE,KAAK;AAE9C,WAAO;AAAA,EACT;AAAA,EAGA,KAAK,MAAyB;AAC5B,QAAI,KAAK,QAAQ;AACf,aAAO,KAAK,OAAO,KAAK,IAAI;AAAA,IAC9B,OAAO;AACL,YAAM,IAAI,gBACR,0EACF;AAAA,IACF;AAAA,EACF;AACF;","names":[]}