Skip to content

🏁 express.js middleware that validates body, params, query of request according to JSONSchema and is extremely fast

Notifications You must be signed in to change notification settings

voronianski/is-express-schema-valid

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

45 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

is-express-schema-valid

build status npm version Dependency Status Download Count

Middleware to validate json schema of req.body, req.params and req.query. It is based on JSONSchema spec and is-my-schema-valid module.

Install

npm install is-express-schema-valid --save

Usage

isExpressSchemaValid({ payload, query, params }, options)

Create schema validation middleware using the specified keys for each type of request data:

  • payload schema object validates req.body
  • params schema object validates req.params
  • query schema object validates req.query

Options

  • filter - filter away fields that are not in the schema, defaults to false
  • filterReadonly - filter away fields that are marked as readonly: true in schema, defaults to false

Example

import express from 'express';
import bodyParser from 'body-parser';
import validate from 'is-express-schema-valid';

const app = express();

const loginSchema = {
    payload: {
        email: {
            type: 'string',
            required: true,
            format: 'email'
        },
        password: {
            type: 'string',
            required: true,
            minLength: 1
        }
    }
};

app.use(bodyParser.json());
app.post('/login',
    validate(loginSchema),
    findAndLoginUser
);
app.use(handleErrors);

function findAndLoginUser (req, res, next) {
    // if schema validation fails 
    // this middleware won't be called
}

function handleErrors (err, req, res, next) {
    // validation error will be passed as first argument
    // you can return it or match with your api responses
}

app.listen(3000);

Define schemas

When defining a schema for request's payload / params / query you are able to pass a plain object. In this case is-express-schema-valid will automagically populate your schema with default object properties:

const schema = {
    payload: {
        foo: {
            type: 'string',
            required: true
        }
    }
};

// will be passed to validator as:
// { 
//   type: 'object', 
//   required: true, 
//   additionalProperties: false, 
//   properties: { 
//     foo: { 
//       type: 'string', 
//       required: true 
//     }
//   }
// }

In other cases when you need a different type use a full schema. For example, when payload needs to be an array:

const schema = {
    payload: {
        type: 'array',
        uniqueItems: true,
        items: {
            type: 'number'
        }
    }
};

// it will be used as is by validator

Formats

There are several additional formats added for easy validating the requests:

  • "mongo-object-id" - check if the string is a valid hex-encoded representation of a MongoDB ObjectId
  • "alpha" - check if the string contains only letters (a-zA-Z)
  • "alphanumeric" - check if the string contains only letters and numbers
  • "numeric" - check if the string contains only numbers
  • "hexadecimal" - check if the string is a hexadecimal number
  • "hexcolor" - check if the string is a hexadecimal color
  • "base64" - check if a string is Base64 encoded
  • "decimal" - check if a string is a decimal number, such as 0.1, .3, 1.1, 1.00003, 4.0, etc.
  • "int" - check if a string is an integer
  • "float" - check if a string is a float
  • "uuid" - check if the string is UUID

In the example below we can ensure that id passed as param is valid MongoDB ObjectId:

import validate from 'is-express-schema-valid';

const schema = {
    params: {
        id: {
            type: 'string',
            format: 'mongo-object-id'
        }
    }
};

app.get('/items/:id',
    validate(schema) 
    //...
);

Just a reminder that there are default built-in formats supported by JSONSchema:

Errors

If provided data doesn't match provided schema is-express-schema-valid middleware passes instance of SchemaValidationError class down to your app's error handler middleware:

import { SchemaValidationError } from 'is-express-schema-valid';

function errorHandlerMiddleware (err, req, res, next) {
    // handle schema validation error
    if (err instanceof SchemaValidationError) {
        // check lists of errors for each schema
        console.log(err.errors);
        // { payload: [...], query: [...], params: [...] }
    }
}

JSONSchema

In order to get comfortable with JSONSchema spec and its' features I advice you to check the book "Understanding JSON Schema" (also PDF version) or look at examples.


MIT Licensed

About

🏁 express.js middleware that validates body, params, query of request according to JSONSchema and is extremely fast

Resources

Stars

Watchers

Forks

Packages

No packages published