One of the key features of a thorin app is the way you validate your input data by using sanitizers. Since sanitizers are pure synchronous functions, given an input value it will check if it's valid or not, and if it is, return the validated version.
So, the dispatcher.validate()
function will return a a ThorinIntentValidator
instance
that you can use to specify additional information about your input set. The validator's functionality is available below.
val
value in the intent's input value
for the failed key (see example below)
INPUT.NOT_VALID
error.
validatorObj.error('errorCode, 'errorMessage', statusCode)
, the validator will automatically create the error instance for you.
'use strict'
const dispatcher = thorin.dispatcher;
dispatcher
.addAction('some.action')
.input({
name: dispatcher
.validate('STRING', {min: 2})
.default('John')
.promise((inputName) => {
log.info('Todo some async operation');
return Promise.resolve('Doe');
});
})
.use((intentObj) => {
log.info(intentObj.input('name')); // should output Doe
intentObj.send():
});
promise()
, used for asynchronous validations, the callback function will be called with the input value and a done
function that should be called with the standard (err, result)
The dispatcher will automatically handle input data when used in an action or a middleware context. However,
you can also use thorin to validate data outside the scope of an action or middleware, by using a special sanitization
function found under thorin.sanitize
.
null
'use strict'
thorin.sanitize('STRING', 'myString'); // => 'myString'
thorin.sanitize('NUMBER', '30'); // => 30
thorin.sanitize('IP', 'a.b.c.d', '127.0.0.1'); // => '127.0.0.1'
'use strict';
const dispatcher = thorin.dispatcher;
dispatcher
.addAction('my.action')
.input({
name: dispatcher.validate('STRING', {min: 3, max: 20}).default('John'),
age: dispatcher.validate('NUMBER', {min: 13}).error('INVALID.AGE', 'Please provide a valid age', 400),
gender: dispatcher.validate('ENUM', ['male', 'female']).error('INVALID.GENDER', 'Please select a gender')
});
You can always create a new issue on GitHub or contact one of the core founders by chat.