1.0.0 • Published 9 years ago
express-utilities v1.0.0
Express Utilities
Various helpful middleware that I keep rewriting for every single project
Installation
npm install express-utilities
Usage
Requiring Parameters on Requests
'use strict';
const { requireParams } = require('express-utils');
const parser = require('body-parser');
const app = require('express')();
app.use(parser.json());
app.post('/data', requireParams({
body: [
'username',
'email'
]
}), (req, res) => {
// req.body.username and req.body.email are definitely here if
// the request made it this far
});
app.listen(8080);Error Handling
Given that my target was initially Ember, errors will currently be returned as follows:
{
"errors": [
{ "message": "invalid type for parameter age: asdf" },
{ "message": "missing parameter: body.username" }
]
}Handling Types
Sometimes you need to specify a type so that you don't have to do a bunch of work in each endpoint to coerce a value and you can do that using this same method.
Given the endpoint:
app.post('/data', requireParams({
query: [
{
name: 'active',
type: 'boolean'
}
],
body: [
'username',
{
name: 'email',
type: 'string'
},
{
name: 'age',
type: 'number'
}
]
}), (req, res) => {
});And the request:
POST /data?active=true
{
"username": "test-user",
"email": "test-email@domain.com",
"age": "19"
}req.query.active would be true (rather than 'true'), age would be 19 (rather than '19') so long
as the provided values are actually able to be converted i.e. not NaN or something other than 1/0/true/false
in the case of a boolean.
1.0.0
9 years ago