Skip to content

Latest commit

 

History

History
42 lines (32 loc) · 1.56 KB

README.md

File metadata and controls

42 lines (32 loc) · 1.56 KB

Commitizen friendly Coverage Status ci

route-param-alias

Express.js middleware to substitute route parameters with values from other parts of the request.

Currently, this is supported in the form of JSON Web Tokens in the request headers or as query parameters.

Usage

const routeParamAlias = require('route-param-alias')
const meConverter = routeParamAlias({
  alias: 'me',
  paramName: 'id',
  tokenLocation: 'header',
  tokenName: 'Authorization',
  payloadKey: 'sub'
})

app.get('/:id', (req, res) => {
  const payload = jwt.decode(req.headers.authorization)

  /// Assertions before applying middleware
  assert.equals(req.params.id, 'me')
  assert.not.equals(req.params.id, payload.sub)

  meConverter(req, res, () => {
    /// Assertions after applying middleware
    assert.not.equals(req.params.id, 'me')
    assert.equals(req.params.id, payload.sub)
    ...
  })
})

URL rewriting

In order to match up with downstream middleware or handlers, this middleware also rewrites the url variables on the Express.js request object.

This is done by rewriting req.url, which is parsed to produce req.path. This does not modify req.baseUrl or req.originalUrl.