Skip to content

2. Usage Examples

Douglas Rafael edited this page Feb 24, 2019 · 7 revisions

You can use the default middleware settings or customize them according to the needs of your application.

1. The middleware configuration

The middleware uses the following defaults:

options = {
    use_page: false,
    client_db: 'mongodb',
    date_fields: {
        'start_at': 'created_at',
        'end_at': 'created_at'
    },
    default: {
        fields: {},
        sort: {},
        filters: {},
        pagination: {
            limit: Number.MAX_SAFE_INTEGER,
            skip: 0,
            page: 1
        }
    }
}

These settings can be customized by the user, as long as they follow the standard defined in the middleware. Below we have the description of each of the parameters, as well as the definition of their default values.

use_page:

Defines whether query pagination will be done using page if the value is true, or skip if this value is false. By default, this parameter is set to false.

client_db:

Defines which database is being used. Based on this parameter, the queries are treated in different ways. By default, this parameter is set to 'mongodb'.

date_fields:

Defines the name of the parameter that will be used in Date filters.

  • start_at: Defines the name of the parameter set with start date of the filter. By default, this parameter is set to 'created_at'.

  • end_at: Defines the name of the parameter set with end date of the filter. By default, this parameter is set to 'created_at'.

default:

  • fields: Allows you to retrieve only the information you want. To do this, simply provide the attribute/property names separated by commas. By default, there is no field selection defined.

  • sort: Allows to apply sorting rules. To do this, simply provide the attribute/property names that will be used to sort the query result separated by comma. By default, there is no pre-defined sort parameter.

  • filters: It consists of limiting the number of resources requested by specify some attributes and their expected values. It's possible to filter a collection by multiple attributes at the same time and allow to filter multiple values for an attribute. By default, there is no pre-defined filter parameter.

  • pagination: Paging works in conjunction with two query strings: limit, skip/page.

    • limit Determines the maximum number of items that the query should return, limit=30 returns a maximum of 30 items.
      • Default value: limit: MAX_SAFE_INTEGER (constant value for 9007199254740991)

    Pagination with skip

    • skip Determines the number of items you want to skip in the query, skip=20 ignore the first 20 items.
      • Default value: skip: 0

    Pagination with page

    • page Determines the page number to return with the requested resource. The number of available pages is dynamic according to the number of records on the server and the limit per page set.
      • Default value: page: 1

2. Using default configurations

To use the default settings, just do as described in the example below:

const express = require('express')
const qs = require('query-strings-parser')
const app = express()

app.use(qs()) // middleware query-strings-parser

app.listen(3000, (req, res) => {
    console.log('app listening on port 3000')
})

app.get('/', (req, res) => {
    res.send('the query is:' + JSON.stringify(req.query))
})

When a query with query strings is performed, the request query parameter is updated, and transformed into a JSON object containing the following information:

/**
 * Request: http://localhost:3000?fields=name,age&skip=10&limit=10&sort=created_at
 * Result (req.query):
 * {
 *    fields: { name: 1, age: 1 },
 *    sort: { created_at: 'asc' }
 *    filters: {},
 *    pagination: {
 *        skip: 10,
 *        limit: 10
 *    },
 *    original: '?fields=name,age&skip=10&limit=10&sort=created_at'
 * }
 */

2. Using custom configurations:

const express = require('express')
const qs = require('query-strings-parser')
const app = express()

app.use(qs({
  use_page: true,
  client_db: 'mongodb',
  date_field: 'created_at'
  default: {
      fields: {_id: 0},
      sort: { created_at: 'desc' },
      filters: {},
      pagination: {
          page: 1,
          limit: 100
      }
  }
}))

/**
 * Request: http://localhost:3000?fields=name,age&age=30
 * Result (req.query):
 * {
 *    fields: {_id: 0, name: 1, age: 1},
 *    sort: { created_at: 'desc' }
 *    filters: {age: 30},
 *    pagination: {
 *        limit: 100,
 *        page: 1
 *    },
 *    original: '?fields=name,age&age=30'
 * }
 */

Notes:

  • The default query strings defined by you must follow the return pattern defined in client_db (default value mongodb) to ensure the correct operation of queries:

    • For fileds, the default values ​​should be attribute: 1 if the attribute should be selected, and attribute: 0, otherwise.
    • For sort, the default value should be attribute: 'asc' for ascending order and attribute: 'desc' for descending order.
    • For filters, the middleware return format defined in client_db should be used.
    • For pagination, the value of the limit, skip and page parameters must be positive integers 0-N.
  • Default values are used only when they are not passed in the query string, but has priority when the query contains the same parameter as defined by default. For example, if you set the default value { age: 'desc' } (age in descending order) and your client makes a request with ?sort=age (agein ascending order), you will get in req.query the value { sort: { age: 'desc' } }, since the values defined in default will always have preference.

  • Remember to set whether to use the page or not in the options. If you do not configure use_page: true, the parser will ignore the page parameter, since skip will be used.

  • The configurations that you don't set in middleware options it will be the default settings.