@ctx/express
TypeScript icon, indicating that this package has built-in type declarations

1.1.0 • Public • Published

@ctx/express

Build Status Dependency Status

Middlewares to make using context's easier in Express applications.

See the typedoc for API documentation.

Example

The timeout middleware attaches a context with a fixed timeout to every incoming request. We can use this to implement a timeout for our users; if the context times out, return an error message.

const express = require('express')
const expressCtx = require('@ctx/express')
const context = require('@ctx/context')

const app = express()
app.use(expressCtx.timeout(1000))
app.get('/', async (req, res) => {
  try {
    const data = await doSomething(req.ctx, req.body)
    res.json(data).end()
  } catch (err) {
    if (err === context.DeadlineExceeded) {
      res.status(500).end('timed out')
    } else {
      res.status(500).end('internal server error')
    }
  })
})

The addHeader reads headers from the request object and attaches them to the context. This can ease some of the burden of passing values down through the stack. For example,

const express = require('express')
const expressCtx = require('@ctx/express')
const context = require('@ctx/context')

const app = express()
app.use(expressCtx.addHeader(['x-user-id']))
app.get('/', async (req, res) => {
  const data = await doSomething(req.ctx, req.body)
  res.json(data).end()
})

function doSomething (ctx, body) {
  ...
  const username = getUsername(ctx)
  ...
}

function getUsername (ctx) {
  return usernames[ctx.Value('x-user-id')]
}

Other useful cases for this include passing a "request id" header to downstream services for tracing and distributed logging.

Readme

Keywords

none

Package Sidebar

Install

npm i @ctx/express

Weekly Downloads

1

Version

1.1.0

License

MIT

Last publish

Collaborators

  • lclarkmichalek