Express Query Params
Express.js middleware implementing the API Query Spec, converting the query to something that can be used to look up the resource.
It works for MongoDB and SQL.
Installing
npm i --save express-query-params
yarn add express-query-params
Basic Usage
This middleware can just be plugged into your stack like so:
const express = require('express')
const queryParams = require('express-query-params')
const app = express()
app.use(queryParams())
Inside any downstream middleware, this plugin will create a parsedQuery
prop on request
, so you should be able to access it via request.parsedQuery
.
Advanced Usage
The middleware accepts a few options to make your life easier:
app.use(queryParams({
dateFormat: 'ISO8601',
returnJSDate: false|true,
format: 'mongo',
blacklistParams: [ 'limit' ],
whitelistParams: []
}));
Formats
So far, this middleware supports mongodb
, sql
and sequelize
as output formats.
mongodb
the output is a javascript object that can be used to query MongoDb.sql
it will output an object with the following props:
query
- this contains a tokenised query (ie. $1
replaces raw params)values
- this is an array of typecast values you can use in your query runner to coincide with the query
prop
sequelize
outputs an object usable as a where clause in a Sequelize lookup
A Note About v1
This module has endured a complete re-write from version 0.4.0
to 1.0.0
. Their APIs are only partially compatible now, so please ensure you read the following differences before upgrading:
- The SQL format now returns an object with a tokenised query and an array of corresponding values, and before it used to return a complete query. This was done because it is out of scope of this module to protect your application from SQL injection, and this is a real conern with a raw query. You can plug these props right into something like Sequelize to make them work! That has built in parameter sanitisation.
- The
dateFormat
option now works differently, please read about it above if you need it to do something besides default. moment
is no longer required for this module, it uses only native JS date.
Contributing
Do you have a database that is not SQL or Mongo? Would love to have your contribution in the form of a PR! Please include a test.
Tests
npm run test