1.0.2 • Published 7 years ago

@gradient/query-array-parser v1.0.2

Weekly downloads
3
License
MIT
Repository
github
Last release
7 years ago

Query Array Parser

Middleware to parse comma separated query params into string arrays.

This provides an alternative method for passing arrays as query parameters within express applications.

The default express system requires you to pass up arrays like this:

https://myapp.io?arr=valueOne&arr=valueTwo&arr=valueThree

With this middleware, you can use a comma separated single parameter instead such as this:

https://myapp.io?arr=valueOne,valueTwo,valueThree

Installation

npm install @gradient/query-array-parser --save

Usage

As global middleware

const express = require('express');
const queryArrayParser = require('@gradient/query-array-parser');

const app = express();

// queryArrayParser accepts either a single string, or an array of
// strings. These strings denote the query parameter name, which will
// be transformed into a string.
app.use(queryArrayParser('categories'));

app.get('/', (req, res, next) => {
  // req.params.categories is an array
  console.log(req.params.categories);
  res.json(req.params.categories).end();
});

app.listen(3000, () => {
  console.log('listening');
});

As route specific middleware

const express = require('express');
const queryArrayParser = require('@gradient/query-array-parser');

const app = express();

// queryArrayParser accepts either a single string, or an array of
// strings. These strings denote the query parameter name, which will
// be transformed into a string.
const options = {
  paramNames: ['categories', 'owners'],
  delim: ','
};

app.get('/', queryArrayParser(options), (req, res, next) => {
  console.log(req.params.categories);
  console.log(req.params.owners);
  res.json({categories: req.query.categories, tags: req.query.owners});
});

app.listen(3000, () => {
  console.log('listening');
});

API

queryArrayParser takes either a string or an options object as below:

  • queryArrayParser(string) - The name of the single query parameter that should be parsed with the default delimiter.
  • queryArrayParser(object) - An options object

Options

  • paramNames - A single string or array of strings denoting the query parameter(s) to be parsed.
  • delim - The delimiter that will be used in the query parameters to be parsed. Defaults to ,.

Licence & Copyright

Copyright (c) 2017 Gradient Limited - Released under the MIT license.