Scalable and flexible async validation solution
npm install --save trus
express extension available here
const validate = require("trus").validate;
const { condition } = require("trus").methods;
var validateEven = validate(
condition( i => i&2 == 0 )
);
validateEven(4).then().catch() // resolves
validateEven(5).then().catch() // rejects
validate is a function that gets a method and generates a validation function, using this method.
Validates are simple. For instance, the default validate function looks like:
var validate = method => context => method(context);
It returns a function that gets an input and returns a promise, wich will be resolved/rejected depending on supplied method's behavior.
const trus = require("trus");
var allowOnly5 = trus.validate( trus.methods.condition( i => i==5 ) );
only5( 5 )
.then( () => onValidationSuccess() ) // <=
.catch( e => onValidationFail(e) )
A trus method is a logic unit, formed as a function, that gets an input (from the validate function), and returns a Promise. The method decides weather to resolve or reject, depending on injected context.
For example, the any method that resolves for any input, looks like:
var any = context => Promise.resolve(true);
Sometimes methods are factories, that generates the methods itself, letting you pass values into it. For example, the allOf method lets you pass in as many sub-methods as you want, and will resolve since all of them did resolved.
validate( allOf( any, none ) )
Factories methods looks like:
var myMethod = (params...) => context => {...};
For example, a method that checks if the context is matching a value will look like:
var myMethod = allowedValue => async context => {
if(context != allowedValue)
throw new Error(context + " != " + allowedValue)
});
var only3 = validate( myMethod(3) )
only3( 2 )
.then()
.catch() // <-- will reject
Name | Description | Usage |
---|---|---|
any | Allow any input | validate( any ) |
none | Block any input | validate( none ) |
allOf | pass if all of the above has passed | validate( allOf( any, any ) ) |
someOf | pass if at least one of the above has passed | validate( someOf( any, none ) ) |
condition | runs a condition function as a validation | validate( condition( context => context == 1 ) ) |
not | returns the opposite from inner method | validate( not( any ) ) |
Trus methods and validate functions are extremely extensible, feel free to extend them yourself.