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

ajv-request-validator

v0.2.0

Published

Validates the `request` object of popular Node.js web frameworks with Ajv

Downloads

19

Readme

ajv-request-validator

npm Version Build Status Coverage Status dependencies Status

Validates the request object of popular Node.js web frameworks with Ajv.

Installation

npm install ajv-request-validator --save
# or
yarn add ajv-request-validator

Usage

Example with Express:

const RequestValidator = require('ajv-request-validator');
const express = require('express');

const app = express();
const reqValidator = new RequestValidator();

app.post(
  '/user',
  reqValidator.compile({
    body: {
      type: 'object',
      properties: {
        name: { type: 'string' },
        age: { type: 'number' }
      }
    }
  }),
  function handler(req, res, next) {
    // Will only be called if `req.body` matches the schema
  }
);

Example with Medley (works exactly the same with Fastify):

const RequestValidator = require('ajv-request-validator');
const medley = require('@medley/medley');

const app = medley();
const reqValidator = new RequestValidator();

app.route({
  method: 'POST',
  path: '/user',
  preHandler: reqValidator.compile({
    body: {
      type: 'object',
      properties: {
        name: { type: 'string' },
        age: { type: 'number' }
      }
    }
  }),
  handler: function(req, res) {
    // Will only be called if `req.body` matches the schema
  }
});

API

new RequestValidator([options])

The ajv-request-validator module exports a class. The class constructor can optionally be passed either an Ajv options object or an existing ajv instance.

const RequestValidator = require('ajv-request-validator');

// No options (use Ajv defaults)
const reqValidator = new RequestValidator();

// With Ajv options
const reqValidator = new RequestValidator({
  removeAdditional: true,
  useDefaults: true,
  coerceTypes: true,
});

// With an existing AjV instance
const Ajv = require('ajv');
const ajv = new Ajv();

const reqValidator = new RequestValidator(ajv);

console.log(reqValidator.ajv === ajv); // true

reqValidator.ajv

The ajv instance that the reqValidator will use to compile validation functions.

reqValidator.ajv.addSchema({
  $id: 'user',
  type: 'object',
  properties: {
    name: { type: 'string' },
    age: { type: 'number' }
  }
});

reqValidator.ajv.addFormat('userID', /[0-9]{9,16}/);

reqValidator.compile(schema[, options])

  • schema - And Object mapping request properties to an Ajv schema.
  • options - Optional options Object.
    • options.middleware - If false, a function that directly validates the request object will be returned. Defaults to true.

Compiles a middleware function that validates the req object and then calls next() with the result (either a validation error or null on success). The keys of the schema object correspond with the names of the properties on the req object to validate (usually body or query).

const middleware = reqValidator.compile({
  body: {
    type: 'object',
    properties: {
      name: { type: 'string' },
      age: { type: 'number' }
    }
  }
});

// Use in Express
app.post('/user', middleware, (req, res, next) => {
  // This middleware is only called if `req.body` matches the schema
});

The middleware function is an Express-style middleware function with the signature:

function middleware(req, res, next) { }

When the middleware option is false, .compile() returns a function that directly validates the request object.

function validate(req) { } // Returns `null` or an Error
const validate = reqValidator.compile({
  body: {
    type: 'object',
    properties: {
      name: { type: 'string' },
      age: { type: 'number' }
    }
  }
}, {middleware: false});

app.post('/user', (req, res, next) => {
  const result = validate(req);
  // `result` will be `null` or an Error
});

This is useful when using this module with frameworks that do not have Express-like middleware (see below for more info).

Usage with other frameworks

Since the .compile() method returns an Express-style middleware function, it is not initially compatible with frameworks that have a different middleware signature.

If a different form of middleware is needed, the RequestValidator class can be subclassed to override the .compile() method to return a function compatible with a specific framework.

Here's an example of extending RequestValidator to work with Koa:

const RequestValidator = require('ajv-request-validator');

class KoaRequestValidator extends RequestValidator {
  compile(schema) {
    const validate = super.compile(schema, {middleware: false});

    return async function koaMiddleware(ctx, next) {
      const err = validate(ctx.request);
      if (err !== null) {
        throw err;
      }
      await next();
    };
  }
}

const reqValidator = new KoaRequestValidator();