1.0.7 • Published 1 year ago

quick-validate v1.0.7

Weekly downloads
2
License
MIT
Repository
github
Last release
1 year ago

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

namepurpose
typedatatype of attribute
lengthlength of 'String' type attribute
minlengthmin length of 'String' type attribute
maxlengthmax length of 'String' type attribute
regexspecifies a pattern to match with
enumValsspecifies a set of enums to match with
missing_err_codeerror code to return if missing
invalid_err_codeerror code to return if datatype is invalid

Supported 'type'(s)

typepurpose
StringAny string
Numberint, float or any string representing same
booleanboolean
ArrayAny array
ObjectAny Object
emailvalid email
passwordmatches strict password policy
enummatches a set of given values
regexmatches 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"]
      }
    }
  }
}
1.0.7

1 year ago

1.0.6

4 years ago

1.0.5

4 years ago

1.0.4

4 years ago

1.0.3

4 years ago

1.0.2

4 years ago

1.0.1

4 years ago

1.0.0

4 years ago

0.0.5

4 years ago

0.0.6

4 years ago

0.0.4

4 years ago

0.0.3

4 years ago

0.0.2

4 years ago

0.0.1

4 years ago