npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

raml-validator-loader

v0.1.11

Published

Converts RAML document to javascript validation functions

Downloads

3

Readme

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.

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: