Tony Ward

Tony Ward

Parameter Validator Using ES6

May 23, 2017

Are you looking for a module that will verify an object contains certain properties? What if you want to validate a function received valid parameters? Look no further —  parameter-validator has you covered. I’ve started adopting this parameter validator in some of my personal projects recently. We use it at the company I work for all of the time.

I don’t want to reiterate what the readme already includes, but it is really simple to use. To verify an object contains the correct properties, here’s a simple example:

let params = { name: 'Paula PureCloud', id: 'user1' };
// ES6 Destructuring assignment here
let { name, id } = validate(params, ['name', 'id']);

If our params object does not contain a name or id property (say we did a ‘delete person.name;’ before calling validate), a ParameterValidationError will be thrown with a message ”Invalid value of ‘undefined’ was provided for parameter ‘name’ ”. Pretty easy, right? This comes in handy to ensure the objects we are instantiating have everything they need. It can also set properties for the class via adding a ‘this’ as an argument. Check out the example:

import { validate } from 'parameter-validator';
export default class MarvelClient {
  constructor(params) {
    validate(params, ['logger', 'apiKey'], this);
  }
}
// The validator would assign logger from params to 'this.logger'
// The validator would assign apiKey from params to 'this.apiKey'
/**
    Use:
    let marvelClient = new MarvelClient({
        logger: new WinstonLoggerWrapper(),
        apiKey: process.env.MarvelApiKey
    });
*/

Another great use case is validating parameters sent to a particular function:

/**
* @param  {Object}  person
* @param  {String}  person.name
* @param  {String}  person.id
* @throws {ParameterValidationError}
*/
doSomeMagic(person) {
    let { name, id } = validate(person, [
        'name',
        'id'
    ]);
    // Your magic business logic here
}

If the person object does not have the name or id properties defined, it will throw an error. I’ve found this to be helpful when writing unit tests. There’s an async version if you need to ensure that any errors thrown are wrapped in a Promise.

Just thought I’d share a neat module I use on a daily basis. Thanks!