exframe-request-validator

Validates requests and returns pretty(ish) error messages

Usage no npm install needed!

<script type="module">
  import exframeRequestValidator from 'https://cdn.skypack.dev/exframe-request-validator';
</script>

README

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.validateSchema(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