Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

raml-validator-loader

Package Overview
Dependencies
Maintainers
9
Versions
3
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

raml-validator-loader

Converts RAML document to javascript validation functions

  • 0.1.11
  • latest
  • npm
  • Socket score

Version published
Maintainers
9
Created
Source

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 TypeDefault Value
ENUMMust be one of {{values}}
ITEMS_MAXMust contain at most {{value}} items in the array
ITEMS_MINMust contain at least {{value}} items in the array
ITEMS_UNIQUEMust contain only unique items
LENGTH_MAXMust be at most {{value}} characters long
LENGTH_MINMust be at least {{value}} characters long
NUMBER_MAXMust be smaller than or equal to {{value}}
NUMBER_MINMust be bigger than or equal to {{value}}
NUMBER_MULTIPLEOFMust be multiple of {{value}}
NUMBER_TYPEMust be of type `{{type}}`
PROPS_MAXMust contain at most {{value}} properties
PROPS_MINMust contain at least {{value}} properties
PROP_ADDITIONAL_PROPSContains extraneous property `{{name}}`
PROP_IS_MISSINGMust be defined
PROP_MISSINGMust define property `{{name}}`
PROP_MISSING_MATCHMust contain a property that matches `{{pattern}}`
STRING_PATTERNMust match the pattern `{{pattern}}`
TYPE_NOT_ARRAYMust be an array
TYPE_NOT_BOOLEANMust be a boolean value
TYPE_NOT_DATETIMEMust be a date/time string
TYPE_NOT_INTEGERMust be an integer number
TYPE_NOT_NULLMust be null
TYPE_NOT_NUMBERMust be a number
TYPE_NOT_OBJECTMust be an object
TYPE_NOT_STRINGMust 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:

FAQs

Package last updated on 29 Jan 2018

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc