npm.io
2.1.1 • Published 6 years ago

@ezy/coerce-middleware

Licence
MIT
Version
2.1.1
Deps
1
Size
23 kB
Vulns
0
Weekly
0

coerce middleware

coerce req.query, req.params or req.body

License CircleCI codecov Docs: typedoc GitHub issues Maintainability Dependencies status Dev Dependencies status Made with: typescript Code style: prettier Runkit: try now minified size minzipped size

Why

Validation logic become simpler when it's possible to expect "typed" datas, but datas parsed from url like req.query or req.params are strings.

Install

npm i @ezy/coerce-middleware

Usage

Common
import { coerce } from '@ezy/coerce-middleware';
import express from 'express';
const app = express();

app.use(coerce('query'));

app.get('/', (req, res) => {
  res.send(JSON.stringify(req.query));
});

app.listen(3000);

// GET /?id=30&is_admin=true&name=awesome%20title
// => {
//   name: 'awesome title',
//   id: 30,
//   is_admin: true
// }
use a custom coercePrimitive function
import { coerce } from '@ezy/coerce-middleware';
import express from 'express';
const app = express();

app.use(coerce('query', value => '(^^)'));

app.get('/', (req, res) => {
  res.send(JSON.stringify(req.query));
});

app.listen(3000);

// GET /?id=30&is_admin=true&nested[name]=awesome%20title
// => {
//   nested: {
//      name: '(^^)'
//   },
//   id: '(^^)',
//   is_admin: '(^^)'
// }