Skip to content

Commit

Permalink
updates for release
Browse files Browse the repository at this point in the history
  • Loading branch information
evanshortiss committed Apr 17, 2017
1 parent 35038d8 commit 30af429
Show file tree
Hide file tree
Showing 7 changed files with 165 additions and 55 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@

# 0.1.0 (16th April 2017)

* Initial release.
22 changes: 22 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
(The MIT License)

Copyright (c) 2017 Evan Shortiss <[email protected]>

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
79 changes: 68 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,25 +3,41 @@
![TravisCI](https://travis-ci.org/evanshortiss/express-joi-validation.svg) [![npm version](https://badge.fury.io/js/express-joi-validation.svg)](https://badge.fury.io/js/express-joi-validation) [![Coverage Status](https://coveralls.io/repos/github/evanshortiss/express-joi-validation/badge.svg?branch=master)](https://coveralls.io/github/evanshortiss/express-joi-validation?branch=master)

A middleware for validating express inputs using Joi schemas. Fills some of the
voids I found that other Joi middleware miss:

* Allows the developers to specify the order in which request inputs are validated in a clear manner.
* Replaces the `req.body` and others with converted Joi values. The same applies for headers, query, and params, but...
* Retains the original `req.body` inside a new property named `req.originalBody`. The same applies for headers, query, and params using the `original` prefix.
* Passes sensible default options to Joi for headers, params, query, and body. These are detailed below.
voids I found that other Joi middleware miss such as:

* Allow the developers to easily specify the order in which request inputs are
validated.
* Replaces the `req.body` and others with converted Joi values. The same applies
for headers, query, and params, but...
* Retains the original `req.body` inside a new property named `req.originalBody`
. The same applies for headers, query, and params using the `original` prefix,
e.g `req.originalQuery` will contain the `req.query` as it looked *before*
validation.
* Passes sensible default options to Joi for headers, params, query, and body.
These are detailed below.
* Uses `peerDependencies` to get a Joi instance of your choosing instead of
using a fixed version.



## Install

You need to install `joi` along with this module for it to work since it relies
on it as a peer dependency. Currently this module has only been tested with joi
version 10.0 and higher.

```
# remember, you need to install joi too
# we install our middleware AND joi since it's required by our middleware
npm i express-joi-validation joi --save
```


## Example Code

An example application can be found in the [example/](https://github.com/evanshortiss/express-joi-validation/tree/master/example)
folder of this repository.


## Usage

```js
Expand All @@ -37,7 +53,12 @@ const querySchema = Joi.object({
to: Joi.date().iso().min(Joi.ref('from')).required()
});

app.get('/orders', validator.query(querySchema), (req, res, next) => {
// Allow unknown fields in the query. This is not allowed by default
const joiOpts = {
allowUnknown: true
};

app.get('/orders', validator.query(querySchema, {joi: joiOpts}), (req, res, next) => {
console.log(
`Compare the incoming query ${JSON.stringify(req.originalQuery)} vs. the sanatised query ${JSON.stringify(req.query)}`
);
Expand All @@ -53,7 +74,8 @@ app.get('/orders', validator.query(querySchema), (req, res, next) => {

### Joi Versioning
This module uses `peerDependencies` for the Joi version being used. This means
whatever Joi version is in the `dependencies` of your `package.json` will be used by this module.
whatever Joi version is in the `dependencies` of your `package.json` will be
used by this module.

### Validation Ordering
If you'd like to validate different request inputs in differing orders it's
Expand Down Expand Up @@ -125,6 +147,43 @@ The following sensible defaults are applied if you pass none:
* abortEarly: false


## Custom Express Error handler

If you don't like the default error format returned by this module you can
override it like so:

```js
const validator = require('express-joi-validation')({
passError: true // NOTE: this tells the module to pass the error along for you
});

const app = require('express')();
const orders = require('lib/orders');

app.get('/orders', validator.query(require('./query-schema')), (req, res, next) => {
// if we're in here then the query was valid!
orders.getForQuery(req.query)
.then((listOfOrders) => res.json(listOfOrders))
.catch(next);
});

// After your routes add a standard express error handler. This will be passed the Joi
// error, plus an extra "type" field so we can tell what type of validation failed
app.use((err, req, res, next) => {
if (err.error.isJoi) {
// we had a joi error, let's return a custom 400 json response
res.status(400).json({
type: err.type, // will be "query" here, but could be "headers", "body", or "params"
message: err.error.toString()
});
} else {
// pass on to another error handler
next(err);
}
});
```


## API

### module(config)
Expand Down Expand Up @@ -169,7 +228,6 @@ The `instance.params` middleware is a little different to the others. It _must_
be attached directly to the route it is related to. Here's a sample:

```js

const schema = Joi.object({
id: Joi.number().integer().required()
});
Expand All @@ -184,5 +242,4 @@ app.get('/orders/:id', (req, res, next) => {
app.get('/orders/:id', validator.params(schema), (req, res, next) => {
// This WILL have a validated "id"
})

```
2 changes: 2 additions & 0 deletions example/server.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
'use strict';

process.title = 'express-joi-validation';

const port = 8080;

const app = require('express')();
Expand Down
92 changes: 53 additions & 39 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,53 @@
'use strict';

// These represent the incoming data containers that we might need to validate
const containers = {
query: {
storageProperty: 'originalQuery',
joi: {
convert: true,
allowUnknown: false,
abortEarly: false
}
},
body: {
storageProperty: 'originalBody',
joi: {
convert: true,
allowUnknown: false,
abortEarly: false
}
},
headers: {
storageProperty: 'originalHeaders',
joi: {
convert: true,
allowUnknown: true,
stripUnknown: false,
abortEarly: false
}
},
params: {
storageProperty: 'originalParams',
joi: {
convert: true,
allowUnknown: false,
abortEarly: false
}
}
};

function buildErrorString (err, container) {
let ret = `Error validating request ${container}.`;
let details = err.error.details;

for (let i = 0; i < details.length; i++) {
ret += ` ${details[i].message}.`;
}

return ret;
}

module.exports = function generateJoiMiddlewareInstance (cfg) {
cfg = cfg || {}; // default to an empty config

Expand All @@ -8,43 +56,6 @@ module.exports = function generateJoiMiddlewareInstance (cfg) {
// We'll return this instance of the middleware
const instance = {};

// These represent the incoming data containers that we might need to validate
const containers = {
query: {
storageProperty: 'originalQuery',
joi: {
convert: true,
allowUnknown: false,
abortEarly: false
}
},
body: {
storageProperty: 'originalBody',
joi: {
convert: true,
allowUnknown: false,
abortEarly: false
}
},
headers: {
storageProperty: 'originalHeaders',
joi: {
convert: true,
allowUnknown: true,
stripUnknown: false,
abortEarly: false
}
},
params: {
storageProperty: 'originalParams',
joi: {
convert: true,
allowUnknown: false,
abortEarly: false
}
}
};

Object.keys(containers).forEach((type) => {
// e.g the "body" or "query" from above
const container = containers[type];
Expand All @@ -60,9 +71,12 @@ module.exports = function generateJoiMiddlewareInstance (cfg) {
req[type] = ret.value;
next();
} else if (opts.passError || cfg.passError) {
next(ret.error);
ret.type = type;
next(ret);
} else {
res.status(opts.statusCode || cfg.statusCode || 400).end(ret.error.toString());
res
.status(opts.statusCode || cfg.statusCode || 400)
.end(buildErrorString(ret, type));
}
};
};
Expand Down
15 changes: 11 additions & 4 deletions index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -173,18 +173,25 @@ describe('express joi', function () {
key: Joi.string().required().valid('only-this-is-valid')
}));

mw({query: {key: 'not valid'}}, {}, () => {
mw({query: {key: 'not valid'}}, {}, (err) => {
expect(err.type).to.equal('query');
expect(err.error.isJoi).to.be.true;
expect(err.value).to.be.an('object');
done();
});
});

it('should use supplied config.joi and config.statusCode', function (done) {
const errStr = 'a fake joi error';
const errStr = '"id" is required';
const statusCode = 403;

const joiStub = {
validate: sinon.stub().returns({
error: errStr
error: {
details: [{
message: errStr
}]
}
})
};

Expand All @@ -196,7 +203,7 @@ describe('express joi', function () {
end: (str) => {
expect(joiStub.validate.called).to.be.true;
expect(resStub.status.calledWith(statusCode)).to.be.true;
expect(str).to.equal(errStr);
expect(str).to.equal(`Error validating request query. ${errStr}.`);
done();
}
};
Expand Down
6 changes: 5 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,13 @@
"description": "validate express application inputs and parameters using joi",
"main": "index.js",
"scripts": {
"unit": "mocha index.test.js",
"unit": "mocha *.test.js",
"test": "npm run cover && nyc check-coverage --statements 100 --lines 100 --functions 100 --branches 100",
"cover": "nyc --reporter=lcov --produce-source-map=true npm run unit",
"example": "nodemon example/server.js",
"coveralls": "npm run cover && cat coverage/lcov.info | coveralls"
},
"files": ["index.js"],
"keywords": [
"joi",
"express",
Expand Down Expand Up @@ -42,5 +43,8 @@
},
"peerDependencies": {
"joi": "*"
},
"engines": {
"node": ">=4.0.0"
}
}

0 comments on commit 30af429

Please sign in to comment.