raml-validator-loader

0.1.11 • Public • Published

raml-validator-loader Velocity

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 the ITEMS_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.

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:

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:

Readme

Keywords

none

Package Sidebar

Install

npm i raml-validator-loader

Weekly Downloads

5

Version

0.1.11

License

Apache-2.0

Last publish

Collaborators

  • juliangieseke
  • billaraw
  • philipnrmn
  • specone
  • johnfurrow
  • mlunoe
  • rcorral
  • orlandohohmeier
  • nlight
  • icharala