@codeparticle/formal
Version:
A <2kb library for validating data of any kind
1 lines • 2.25 kB
Source Map (JSON)
{"version":3,"sources":["../src/rule.ts"],"sourcesContent":["/**\n * @file Rule class for use with createRule and withMessage\n * @author Nick Krause\n */\nimport { Fail } from './fail'\nimport { Success } from './success'\nimport {\n CustomValidatorOptions,\n ValidationCheck,\n ValidationRule,\n} from './types'\n\nclass Rule implements ValidationRule {\n message: string | ((v: any) => string)\n opts: CustomValidatorOptions\n\n constructor(opts: CustomValidatorOptions) {\n this.opts = opts\n }\n\n check: ValidationCheck = (value) => {\n if (this.opts.condition(value)) {\n // Rule and createRule accept an optional function (delayed) parameter\n // called transform that allows us to change the value\n // before it is passed onto the next check.\n if (this.opts.transform) {\n return Success.of(this.opts.transform(value))\n }\n\n return Success.of(value)\n } else {\n return typeof this.opts.message === `function`\n ? Fail.of(value, [this.opts.message(value)].flat())\n : Fail.of(value, [this.opts.message].flat())\n }\n }\n}\n\n/**\n * Exposed interface to create a rule\n */\nconst createRule: (opts: CustomValidatorOptions) => ValidationRule = (opts) => {\n return new Rule(opts)\n}\n\n/**\n * Method to overwrite the message of a rule.\n * Useful if you'd like to use a built-in, but want to change the ultimate message\n * that comes out of a failed check.\n * @param message\n */\nconst withMessage =\n (message: string | ((v?: any) => string)) => (rule: ValidationRule) =>\n new Rule({ ...rule.opts, message })\n\nexport { createRule, Rule, withMessage }\n"],"mappings":";;;;;;;;;;;;AAYA,iBAAqC;AAAA,EAInC,YAAY,MAA8B;AAI1C,iBAAyB,CAAC,UAAU;AAClC,UAAI,KAAK,KAAK,UAAU,KAAK,GAAG;AAI9B,YAAI,KAAK,KAAK,WAAW;AACvB,iBAAO,QAAQ,GAAG,KAAK,KAAK,UAAU,KAAK,CAAC;AAAA,QAC9C;AAEA,eAAO,QAAQ,GAAG,KAAK;AAAA,MACzB,OAAO;AACL,eAAO,OAAO,KAAK,KAAK,YAAY,aAChC,KAAK,GAAG,OAAO,CAAC,KAAK,KAAK,QAAQ,KAAK,CAAC,EAAE,KAAK,CAAC,IAChD,KAAK,GAAG,OAAO,CAAC,KAAK,KAAK,OAAO,EAAE,KAAK,CAAC;AAAA,MAC/C;AAAA,IACF;AAlBE,SAAK,OAAO;AAAA,EACd;AAkBF;AAKA,IAAM,aAA+D,CAAC,SAAS;AAC7E,SAAO,IAAI,KAAK,IAAI;AACtB;AAQA,IAAM,cACJ,CAAC,YAA4C,CAAC,SAC5C,IAAI,KAAK,iCAAK,KAAK,OAAV,EAAgB,QAAQ,EAAC;","names":[]}