Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Possibility to use predefined schema for all validation checks (new ajv version as well) #55

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,28 @@ Validator.validate({
requestProperty: schemaToUse
});
```
5. It is possible to use a predefined schema and validate on element:
```js
const schemas = {
element: {
type: 'object',
properties: {
prop: {
type: "string"
}
}
}
}
const validator = new Validator({ schemas: schemas });
validator.validate({ body: "element" });

```
6. *Optional* - from version 3.0.0 (ajv 7) additional formats are separated. To use:
```js
const addFormats = require("ajv-formats");
const validator = new Validator();
addFormats(validator.ajv);
```

Example: Validate `req.body` against `bodySchema`

Expand Down
74 changes: 58 additions & 16 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "express-json-validator-middleware",
"version": "2.1.0",
"version": "3.0.0",
"description": "An Express middleware to validate requests against JSON Schemas",
"main": "src/index.js",
"author": "Josef Vacek",
Expand Down Expand Up @@ -44,7 +44,7 @@
"prettier": "^1.19.1"
},
"dependencies": {
"ajv": "^6.6.2",
"ajv": "^7.0.3",
"@types/express": "^4.17.3",
"@types/json-schema": "^7.0.4",
"@types/express-serve-static-core": "^4.17.2"
Expand Down
6 changes: 4 additions & 2 deletions src/index.d.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { RequestHandler } from "express-serve-static-core";
import { JSONSchema4, JSONSchema6, JSONSchema7 } from "json-schema";
import { ErrorObject, Options as AjvOptions } from "ajv";
import Ajv, { ErrorObject, Options as AjvOptions } from "ajv";

declare module "express-json-validator-middleware" {
type OptionKey = "body" | "params" | "query";
Expand All @@ -11,14 +11,16 @@ declare module "express-json-validator-middleware" {

export type ValidateFunction =
| Function
| String
| JSONSchema4
| JSONSchema6
| JSONSchema7;

export class Validator {
ajv: Ajv
constructor(options: AjvOptions);

validate(rules: List<ValidateFunction>): RequestHandler;
validate (rules: List<ValidateFunction>): RequestHandler;
}

export class ValidationError extends Error {
Expand Down
28 changes: 18 additions & 10 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
var Ajv = require("ajv");
var Ajv = require("ajv").default;

/**
* Express middleware for validating requests
Expand All @@ -23,16 +23,23 @@ class Validator {

// Cache validate functions
const validateFunctions = Object.keys(options)
.map(function(
.map(function (
requestProperty
) {
const schema = options[requestProperty];
if (typeof schema === "function") {
) {
const schema = options[requestProperty];
let validateFunction = null;
switch (typeof schema) {
case "function":
return { requestProperty, schemaFunction: schema };
}
const validateFunction = this.ajv.compile(schema);
return { requestProperty, validateFunction };
},
case "string":
validateFunction = (toValidate) => this.ajv.validate(schema, toValidate);
break;
default:
validateFunction = this.ajv.compile(schema);
break;
}
return { requestProperty, validateFunction };
},
self);

// The actual middleware function
Expand All @@ -53,7 +60,8 @@ class Validator {
// Test if property is valid
const valid = validateFunction(req[requestProperty]);
if (!valid) {
validationErrors[requestProperty] = validateFunction.errors;
validationErrors[requestProperty]
= validateFunction.errors ? validateFunction.errors : this.ajv.errors;
}
}

Expand Down
74 changes: 72 additions & 2 deletions test/middleware-test.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
const expect = require("chai").expect;
const { Validator, ValidationError } = require("../src");

const ajv = require("ajv");
const ajv = require("ajv").default;

describe("Simulated Middleware", () => {
describe("Basic Use Case", () => {
Expand Down Expand Up @@ -108,8 +108,78 @@ describe("Simulated Middleware", () => {
});
});

describe("Predefined Schema", () => {

const schemas = {
something: {
type: 'object',
required: ['prop'],
properties: {
prop: {
type: 'integer'
}
}
},
otherthing: {
type: 'object',
required: ['name', 'proptwo'],
additionalProperties: false,
properties: {
name: {
type: 'string'
},
proptwo: {
"$ref": "something"
}
}
}
};

const middleware = new Validator({ schemas: schemas }).validate({
body: 'otherthing'
});

it("should throw ValidationError on bad data", () => {
expect(() =>
middleware(
{
body: {}
},
{},
function next(err) {
throw err;
}
)
)
.to
.throw(ValidationError);
});

it("should call next() on good data", () => {
let nextCalled = false;
expect(() =>
middleware(
{
body: {
name: "nikolay",
proptwo: 123
}
},
{},
function next() {
nextCalled = true;
}
)
)
.not
.to
.throw();
expect(nextCalled).to.be.true;
});
});

describe("Validator instance", () => {
it("should be able to acesss ajv instance at Validator.ajv", () => {
it("should be able to access ajv instance at Validator.ajv", () => {
expect(new Validator())
.to
.haveOwnProperty("ajv");
Expand Down