exframe-request-validator
TypeScript icon, indicating that this package has built-in type declarations

1.10.2 • Public • Published

exframe-request-validator

Wraps ajv to validate requests and produce human readable error messages when validation fails.

Example - validate requests

const validator = require('exframe-request-validator');

const sampleSchema = {
  $schema: 'http://json-schema.org/draft-07/schema#',
  title: 'Sample Validation Schema',
  type: 'object',
  required: [ 'thing1' ],
  properties: {
    thing1: { type: 'string' },
    thing2: { type: 'string', minLength: 1 }
  }
};

const validateSchema = (schema) => {
  const validate = validator.generateValidator(schema);

  return async (context, obj) => {
    validate({ log: context.log }, obj);
  };
};

return validateSchema(sampleSchema)(context, requestBody)
  .then(()) => {
    // Passed validation - do something awesome
  }
  .catch(err => {
    // One or more things failed validation.
    // err.status = 400
    // err.message = Human readable message
    // err.validationErrors = Array of validation failures
  });

custom error messages can also be used against specific properties / items use https://github.com/epoberezkin/ajv-errors for reference

Schema Dependencies

An optional second parameter can be passed to the generateValidator() function. It must be an array of schema dependencies which will be added via ajv.addSchema(). Each of these schemas must contain an $id. More information about addSchema() can be found here.

Example

  const validate = validator.generateValidator(schema, [referenceSchema1, referenceSchema2]);

Readme

Keywords

none

Package Sidebar

Install

npm i exframe-request-validator

Weekly Downloads

404

Version

1.10.2

License

ISC

Unpacked Size

22.5 kB

Total Files

11

Last publish

Collaborators

  • exzeo_usa
  • exzeodevops