You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I have a need of composing two validators, ie the value can satisfy either of validators. My use-case is origin url for cors setup - it can either be an actual url or a string '*' to allow any origin.
Here is my take on this:
// #region `oneOf` definitiontypeMkValidator<T>=(spec?: Spec<T>)=>ValidatorSpec<T>;// helper function to encapsulate usage of internalsfunctionparse<T>(val: ValidatorSpec<T>,x: string): T{constres=val._parse(x);if(val.choices){if(val.choices.indexOf(res)===-1){thrownewError(`Value "${x}" not in choices: [${val.choices.join(", ")}]`);}else{returnres;}}else{returnres;}}// define `oneOf` combinatorconstoneOf=<T>(val: ValidatorSpec<T>,
...vals: ValidatorSpec<T>[]): MkValidator<T>=>{constall=[val, ...vals];// I went with simpler approach to specify all documentary stuff on resulting validator// and reject all these properties on sub validators.for(constvofall){if(v.default!==undefined){thrownewError(`'default' property is not supported in oneOf sub validators.`);}if(v.devDefault!==undefined){thrownewError(`'devDefault' property is not supported in oneOf sub validators.`);}if(v.desc!==undefined){thrownewError(`'desc' property is not supported in oneOf sub validators.`);}if(v.docs!==undefined){thrownewError(`'docs' property is not supported in oneOf sub validators.`);}if(v.example!==undefined){thrownewError(`'example' property is not supported in oneOf sub validators.`);}}consttypes=all.map(v=>v.type);consttype=`oneOf: [${types.join(", ")}]`;returnmakeValidator(x=>{try{returnparse(val,x);}catch(err){consterrs=[err];for(constvofvals){try{returnparse(v,x);}catch(e){errs.push(e);continue;}}thrownewError(`oneOf validator failed: [\n${errs.map(e=>e.message).join(",\n")}\n]`);}},type);};// #endregion
And here is the usage:
// creating `origin` validator using `oneOf` combinatorconstorigin=oneOf(url(),str({choices: ["*"]}));exportdefaultcleanEnv(process.env,{// example usage of newly created validatorFRONTEND_ORIGIN: origin({devDefault: "*",example: "http://localhost:3000"})});
The text was updated successfully, but these errors were encountered:
This is a neat trick, but I don't think it's going to be used commonly enough to justify inclusion in the library itself. As a result I'm going to close this issue, but thanks for posting this, I think some people might find it useful 👍
I have a need of composing two validators, ie the value can satisfy either of validators. My use-case is origin url for cors setup - it can either be an actual url or a string '*' to allow any origin.
Here is my take on this:
And here is the usage:
The text was updated successfully, but these errors were encountered: