dcos/raml-validator-loader

Name: raml-validator-loader

Owner: DC/OS

Description: A webpack plugin that converts RAML rules into pure javascript-only validation routines

Created: 2017-01-09 16:17:08.0

Updated: 2017-05-12 07:28:56.0

Pushed: 2018-01-29 14:06:21.0

Homepage: null

Size: 158

Language: JavaScript

GitHub Committers

UserMost Recent Commit# Commits

Other Committers

UserEmailMost Recent Commit# Commits

README

raml-validator-loader Velocity

A webpack plugin that converts RAML rules into pure javascript-only validation routines

Usage
rt TypeValidators from './ramls/myTypes.raml';

he raml-validator-loader will convert the RAML document into an object with
 validation function for every type defined in your RAML.

userInput = read_user_input();
validationErrors = TypeValidators.MyType(userInput);

isplay errors
dationErrors.forEach((error) => {
nsole.log('Error message: /' + error.path.join('/'));
nsole.log('  Error path : ' + error.message);

Customizing validator

It is possible to customize the validator instance in order for example to provide custom error messages:

rt TypeValidators from './ramls/myTypes.raml';


ou can clone the default validator instance and customize it

t 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

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.

rt 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.

t CustomValidator = TypeValidators.clone({
errorMessages: { ... }

Parameters Returns 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.

t errors = TypeValidators.SomeRAMLType(userData);
errors.length > 0) {
throw new TypeError('You must provide some valid data');

Parameters Returns
le.exports = {

*
 For every type in the RAML document, an equivalent validation function
 will be generated by the loader.
/
mlTypeName: 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.

t errors = TypeValidators.SomeRAMLType(userData);
errors.length > 0) {
const error = errors[0];
console.log('Error path = ', error.path);
console.log('Error message = ', error.message);

Property .path Property .type Property .variables Property .message
Error Messages

The following error messages are used by the RAML validator. You can override them using the .clone({errorMessages: ...}) function.

Error Type Default Value
ENUM Must be one of {{values}}
ITEMS_MAX Must contain at most {{value}} items in the array
ITEMS_MIN Must contain at least {{value}} items in the array
ITEMS_UNIQUE Must contain only unique items
LENGTH_MAX Must be at most {{value}} characters long
LENGTH_MIN Must be at least {{value}} characters long
NUMBER_MAX Must be smaller than or equal to {{value}}
NUMBER_MIN Must be bigger than or equal to {{value}}
NUMBER_MULTIPLEOF Must be multiple of {{value}}
NUMBER_TYPE Must be of type `{{type}}`
PROPS_MAX Must contain at most {{value}} properties
PROPS_MIN Must contain at least {{value}} properties
PROP_ADDITIONAL_PROPS Contains extraneous property `{{name}}`
PROP_IS_MISSING Must be defined
PROP_MISSING Must define property `{{name}}`
PROP_MISSING_MATCH Must contain a property that matches `{{pattern}}`
STRING_PATTERN Must match the pattern `{{pattern}}`
TYPE_NOT_ARRAY Must be an array
TYPE_NOT_BOOLEAN Must be a boolean value
TYPE_NOT_DATETIME Must be a date/time string
TYPE_NOT_INTEGER Must be an integer number
TYPE_NOT_NULL Must be null
TYPE_NOT_NUMBER Must be a number
TYPE_NOT_OBJECT Must be an object
TYPE_NOT_STRING Must be a string
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:

t 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:


This work is supported by the National Institutes of Health's National Center for Advancing Translational Sciences, Grant Number U24TR002306. This work is solely the responsibility of the creators and does not necessarily represent the official views of the National Institutes of Health.