@codeparticle/formal
Version:
A <2kb library for validating data of any kind
1 lines • 2.31 kB
Source Map (JSON)
{"version":3,"sources":["../src/fail.ts"],"sourcesContent":["/**\n * @file class to describe validation failures.\n * @name Failure.js\n * @author Nick Krause\n * @license MIT\n */\nimport { checkIsValidationM } from './internal/utils'\nimport { ValidationActions, ValidationM } from './types'\n\nclass Fail implements Fail {\n static of(value: any, errors: string[] = []) {\n return new Fail(value, errors)\n }\n\n value: any = null\n errors: string[] = []\n isSuccess = false\n\n /**\n * This constructor allows us to coalesce errors from multiple failed checks into\n * one, used when we fold out of this context.\n *\n */\n constructor(value: any, errors: string[] = []) {\n this.value = value\n this.errors = errors\n }\n\n /**\n * The map function for Fail preserves the value without mapping anything over it, and accumulates errors on the side.\n */\n map() {\n return new Fail(this.value, this.errors)\n }\n\n /**\n * The .chain() for Fail takes another Success or Fail, then combines the results.\n */\n chain(validationM: (v: any, e?: string[]) => ValidationM): ValidationM {\n try {\n const result = validationM(this.value, this.errors)\n\n checkIsValidationM(result)\n\n return new Fail(result.value, [...this.errors, ...(result?.errors ?? [])])\n } catch (error) {\n console.error(error.message)\n console.error(error.stack)\n }\n }\n\n /**\n * After checks are done, this method is used to extract the value\n * with a function that operates on it.\n */\n fold({ onFail }: ValidationActions) {\n return onFail(this.errors)\n }\n}\n\nexport { Fail }\n"],"mappings":";;;;;AAAA,AASA,iBAA2B;AAAA,EAczB,YAAY,OAAY,SAAmB,CAAC,GAAG;AAT/C,iBAAa;AACb,kBAAmB,CAAC;AACpB,qBAAY;AAQV,SAAK,QAAQ;AACb,SAAK,SAAS;AAAA,EAChB;AAAA,SAhBO,GAAG,OAAY,SAAmB,CAAC,GAAG;AAC3C,WAAO,IAAI,KAAK,OAAO,MAAM;AAAA,EAC/B;AAAA,EAmBA,MAAM;AACJ,WAAO,IAAI,KAAK,KAAK,OAAO,KAAK,MAAM;AAAA,EACzC;AAAA,EAKA,MAAM,aAAiE;AAtCzE;AAuCI,QAAI;AACF,YAAM,SAAS,YAAY,KAAK,OAAO,KAAK,MAAM;AAElD,yBAAmB,MAAM;AAEzB,aAAO,IAAI,KAAK,OAAO,OAAO,CAAC,GAAG,KAAK,QAAQ,GAAI,uCAAQ,WAAR,YAAkB,CAAC,CAAE,CAAC;AAAA,IAC3E,SAAS,OAAP;AACA,cAAQ,MAAM,MAAM,OAAO;AAC3B,cAAQ,MAAM,MAAM,KAAK;AAAA,IAC3B;AAAA,EACF;AAAA,EAMA,KAAK,EAAE,UAA6B;AAClC,WAAO,OAAO,KAAK,MAAM;AAAA,EAC3B;AACF;","names":[]}