raml-validator-loader
v0.1.11
Published
Converts RAML document to javascript validation functions
Downloads
3
Maintainers
Keywords
Readme
raml-validator-loader
A webpack plugin that converts RAML rules into pure javascript-only validation routines
Usage
import TypeValidators from './ramls/myTypes.raml';
// The raml-validator-loader will convert the RAML document into an object with
// a validation function for every type defined in your RAML.
var userInput = read_user_input();
var validationErrors = TypeValidators.MyType(userInput);
// Display errors
validationErrors.forEach((error) => {
console.log('Error message: /' + error.path.join('/'));
console.log(' Error path : ' + error.message);
});
Customizing validator
It is possible to customize the validator instance in order for example to provide custom error messages:
import TypeValidators from './ramls/myTypes.raml';
/**
* You can clone the default validator instance and customize it
*/
const CustomTypeValidators = TypeValidators.clone({
'errorMessages': {
// You can provide a string override
TYPE_NOT_OBJECT: 'Expecting an object here',
// Or a function override if you want more control over
// the error message
STRING_PATTERN: (templateVars, path) => {
if (path[0] == 'name') {
return 'Name must only contain letters';
}
return `Must match '${templateVars.pattern}'`;
}
}
});
Installation
First install the module
npm install --save-dev raml-validator-loader
And then use it in your webpack.config.js
like so:
module: {
loaders: [
{ test: /\.raml$/, loader: "raml-validator-loader" }
]
}
API Reference
When you are importing a .raml
document you will end-up loading an instance of a RAMLValidator
class and all the RAML types are exposed as instance property functions.
import TypeValidators from './ramls/myTypes.raml';
RAMLValidator
Class
A default instance of RAMLValidator
class is returned when importing a RAML file. You don't have access to it's constructor directly.
Function .clone([config])
Creates a new instance of RAMLValidator
allowing further customisations to the configuration. Parameters not overriden through the configuration will be kept intact.
const CustomValidator = TypeValidators.clone({
errorMessages: { ... }
});
Parameters
- config - [Optional] An object with the new configuration parameters to pass down to the new validator instance. Accepts the following properties:
errorMessages
: An object with custom error messages. The value to the error message can either be a string, or a function with the following signature:(messageVariables, path)
that returns an error string. For the full list of error messages you can refer to the end of this documentation.
Returns
- RAMLValidator - Returns a new
RAMLValidator
instance
Function .<TypeName>(input)
For each type in the RAML document, a validation function will be created with the above signature. You can call this function, passing it the data you want to validate and it will return an array with the errors found in it.
const errors = TypeValidators.SomeRAMLType(userData);
if (errors.length > 0) {
throw new TypeError('You must provide some valid data');
}
Parameters
- input - The data to validate. Can be anything
Returns
- [RAMLError] - Returns an array of
RAMLError
instances, one for every error encountered in the input data.
module.exports = {
/**
* For every type in the RAML document, an equivalent validation function
* will be generated by the loader.
*/
RamlTypeName: function( validatorInput ) {
...
// Each validation function will return an array of RAMLError objects
// with the information for the validation errors occured.
return [ RAMLError() ];
},
}
RAMLError
Class
This class is instantiated by the type validator function and it contains the information to locate and describe an error in the type.
const errors = TypeValidators.SomeRAMLType(userData);
if (errors.length > 0) {
const error = errors[0];
console.log('Error path = ', error.path);
console.log('Error message = ', error.message);
}
Property .path
- Array - Returns the path in the object where the validation error ocurred, as an array of path components. For example:
['objects', 0, 'name']
Property .type
- String - Returns the type of the error as a string. For example
"PROP_IS_MISSING"
Property .variables
- Object - Returns an object with the template variable values for the error message. For example
{value: 2}
for theITEMS_MAX
error type, in order to be able to compose the dynamic result of"Must contain at most 2 items in the array"
.
Property .message
- String - Returns the human-readable description of the error. For example:
Missing property 'name'
.
Error Messages
The following error messages are used by the RAML validator. You can override them using the .clone({errorMessages: ...})
function.
Function Overrides
If you want more control over the error message, you can use a function instead of string for the error message. The parameters passed to the function are the messageVariables
that provide some contextualization to the error message, and the path
of the error.
For example:
const CustomTypeValidators = TypeValidators.clone({
'errorMessages': {
STRING_PATTERN: (templateVars, path) => {
switch (path.join('.')) {
case 'name':
return 'Name must only contain numbers and letters'
case 'file.name':
return 'All file names must only contain numbers and letters'
default:
return `Must match ${templateVars.pattern}`;
}
}
}
});
Work in progress
The following facets are not yet implemented:
The following types are not yet implemented:
The following concepts are not yet implemented: