sfcode
An Online Competing and Development Environment
|
Validate arguments input in public API endpoints.
For validation of more sophisticated input structures (as deeply nested configuration objects) it's recommended to consider more powerful schema based utlities (as AJV or @hapi/joi)
Bulletproof input arguments normalization and validation:
Aside of general `ensure` validation util, following kind of utilities for recognized JavaScript types are provided:
*/coerce
Restricted coercion into primitive type. Returns coerced value or null
if value is not coercible per rules.
*/is
Object type/kind confirmation, returns either true
or false
.
*/ensure
Value validation. Returns input value (in primitive cases possibly coerced) or if value doesn't meet the constraints throws TypeError
.
Each */ensure
utility, accepts following options (eventually passed with second argument):
isOptional
- Makes null
or undefined
accepted as valid value. In such case instead of TypeError
being thrown, null
is returned.default
- A value to be returned if null
or undefined
is passed as an input value.errorMessage
- Custom error message. Following placeholders can be used:v
- To be replaced with short string representation of invalid valuen
- To be replaced with meaninfgul name (to be passed with name
option) of validated value. Not effective if name
option is not presentname
- Meaningful name for validated value, to be used in error message, assuming it contains n
placeholderobject/is
object/ensure
number/coerce
number/ensure
function/is
function/ensure
$ npm test