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

quick-validate

v1.0.7

Published

Express middleware for codeless configuration-driven API validations

Downloads

25

Readme

quick-validate

Quick configurable API validations for Express.js

npm version Travis Build Coverage Status Known Vulnerabilities Codacy Badge License: MIT

Features

  • Simple - Provides a simple and quick way to configure API validations.
  • Clean - Unlike other libraries, quick-validate does not require you to write a lot of code for adding simple validations. It uses simple JSON configuration files which do not pollute application code.
  • Readable - The validations are much more readable and comprehensible.

Installation

npm install quick-validate --save

Usage

  • Create a directory named validations inside root of your project. This is not required but is recommended as a good practice.

  • Create 2 files inside the validations directory - apiValidations.json and validationSchema.json

apiValidations.json should specify validations for each endpoint. validationSchema.json should specify type and other constraints about each attribute to be validated.

apivalidations.json

{
  "POST": {
    "/product": {
      "body": {
        "required": ["title", "img_url", "price", "availability_status"],
        "optional": ["description"]
      }
    }
  },
  "PUT": {
    "/product/:product_id": {
      "body": {
        "optional": [
          "title",
          "img_url",
          "price",
          "availability_status",
          "description"
        ]
      }
    }
  },
  "GET": {
    "/products": {
      "query": {
        "required": ["q"]
      }
    }
  },
  "DELETE": {
    "/product/:product_id": {
      "headers": {
        "required": ["admin_token"]
      }
    }
  }
}

As shown in above example, the configuration object structure should be

{
  "httpMethod": {
    "endpoint_path1": {
      "required": ["attr1", "attr2"],
      "optional": ["attr3"]
    },
    "endpoint_path2": {
      "required": ["attr1", "attr2"],
      "optional": ["attr3"]
    }
  }
}

validationSchema.json

{
  "title": {
    "type": "String"
  },
  "img_url": {
    "type": "String"
  },
  "price": {
    "type": "Number"
  },
  "availability_status": {
    "type": "regex",
    "regex": "^(IN_STOCK|OUT_OF_STOCK)$"
  },
  "description": {
    "type": "String"
  },
  "q": {
    "type": "String",
    "minlength": 3,
    "maxlength": "50"
  },
  "admin_token": {
    "type": "String",
    "length": 32
  }
}
  • Import and use quick-validate in your app.js

Using ES6 (Recommended)

import * as quickValidate from "quick-validate";
import apiValidations from "./validations/apiValidations.json";
import validationSchema from "./validations/validationSchema.json";
import express from "express";

const app = express();
app.use(express.json());

quickValidate.enableValidations(app, apiValidations, validationSchema, true);

Good ol' way

var quickValidate = require("quick-validate");
var apiValidations = require("./validations/apiValidations.json");
var validationSchema = require("./validations/validationSchema.json");
var express = require("express");

var app = express();
app.use(express.json());

quickValidate.enableValidations(app, apiValidations, validationSchema, true);

The last argument is a boolean which tells quick-validate if extra attributes which are not specified in the validation config for an endpoint, should be removed. This should be usually set to true.

  • Intercept validation errors with middleware
app.use(function (err, req, res, next) {
  res.json({
    ok: false,
    error: {
      code: err.code,
      reason: err.message,
    },
  });
});

Schema Properties

Click on property name to see example

| name | purpose | | -------------------------------- | :------------------------------------------ | | type | datatype of attribute | | length | length of 'String' type attribute | | minlength | min length of 'String' type attribute | | maxlength | max length of 'String' type attribute | | regex | specifies a pattern to match with | | enumVals | specifies a set of enums to match with | | missing_err_code | error code to return if missing | | invalid_err_code | error code to return if datatype is invalid |

Supported 'type'(s)

| type | purpose | | -------- | :----------------------------------------- | | String | Any string | | Number | int, float or any string representing same | | boolean | boolean | | Array | Any array | | Object | Any Object | | email | valid email | | password | matches strict password policy | | enum | matches a set of given values | | regex | matches a given regex pattern |

Examples

length

{
  "otp": {
    "type": "String",
    "length": 4
  }
}

minlength maxlength

{
  "username": {
    "type": "String",
    "minlength": 5,
    "maxlength": 15
  }
}

regex

{
  "ip": {
    "type": "regex",
    "regex": "^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$"
  }
}

enumVals

{
  "availability_status": {
    "type": "enum",
    "enumVals": ["IN_STOCK", "OUT_OF_STOCK"]
  }
}

Putting it all together

validationSchema.json

{
  "username": {
    "type": "String",
    "minlength": 5,
    "maxlength": 15
  },
  "password": {
    "type": "password"
  },
  "email": {
    "type": "email"
  },
  "gender": {
    "type": "enum",
    "enumVals": ["M", "F", "T"]
  },
  "age": {
    "type": "Number"
  },
  "is_married": {
    "type": "boolean"
  },
  "name": {
    "type": "String",
    "minlength": 5,
    "maxlength": 40
  },
  "x-forwarded-for": {
    "type": "regex",
    "regex": "^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$"
  }
}

apivalidations.json

{
  "POST": {
    "/user/signup": {
      "body": {
        "required": ["username", "password", "email", "gender", "age", "name"],
        "optional": ["is_married"]
      },
      "headers": {
        "required": ["x-forwarded-for"]
      }
    },
    "/user/login": {
      "body": {
        "required": ["username", "password"]
      }
    }
  }
}