npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

exp-correlator

v1.0.0

Published

Correlation-id handler and Express middleware

Downloads

7,656

Readme

exp-correlator

Test application

Keep track of correlation id through a series of async operations. Either using a handler or an Express middleware. Uses async_hooks.

Table of contents

Installation

npm install exp-correlator

Usage

If an execution is started using either attachCorrelationIdHandler or occurs after the middleware is attached (when the execution is part of the call chain of a Express request) any call to getId during that execution will return the same correlation id. Example of use-cases may be to pass a correlation-id onto subsequent requests to other systems or to be able to group log messages during the same request without passing on a correlation id between each function call.

Async handler

The async handler will set the correlation id to the supplied or generate a new uuid v4 if not supplied.

const { attachCorrelationIdHandler, getId } = require("exp-correlator");
const logThis = async function (msg) {
  const correlationId = getId(); 
  console.log({correlationId, msg});
}
const f = async function () {
  ...
  logThis("epic message");
  logThis("epic message2");
  ...
};

await attachCorrelationIdHandler(f);

In the example above all the log messages produced by logThis can be grouped together by the correlation id without having to pass the correlation id as an argument every time.

Express middleware

The Express middleware will set the correlation id from the correlation-id or x-correlation-id header if available. Otherwise a new uuid v4 will be generated. The middleware also assigns the correlation-id to the response, matching the header of incoming correlation-id if it's available.

const { middleware, getId } = require("exp-correlator");
const express = require("express");
const app = express();
const logThis = async function (msg) {
  const correlationId = getId(); 
  console.log({correlationId, msg});
}

const callToExternalSystem () {
  const correlationId = getId(); 
  await ... // call to an external system setting correlationId as a header
}

app.use(middleware);
app.get("/", (req, res) => {
  const correlationId = getId();
  await callToExternalSystem();
  logThis("epic message");
  res.json({ correlationId });
  ...
});

In the example above the middleware set the correlation id based on the incoming header, it will then be passed on when doing calls to callToExternalSystem and logThis without being explicitly passed.

Logging with pino

To add correlationId when logging using pino do the following:

const { getId } = require("exp-correlator");
const pino = require("pino");
const logger = pino({mixin: () => {return { correlationId: getId() };}});

In the example above the correct correlation id will be added each time a log function is called when the express middleware or the async handler is used.

Making requests with exp-fetch

To add a correlation id when fetching using exp-fetch do the following:

const { getId } = require("exp-correlator");
const fetchBuilder = require("exp-fetch);
const fetch = fetchBuilder({ getCorrelationId: getId }).fetch;
await fetch("http://foo.bar");

In the example above the correlation id will be added to the outgoing requests headers as correlation-id.

Known issues

Using bodyParser after using correlation middleware will cause the async local storage to be undefined. This applies to any middleware that is derived from bodyParser as well (i.e. urlencoded).

const { middleware, getId } = require("exp-correlator");
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
const logThis = async function (msg) {
  const correlationId = getId(); // correlationId will be null here
  console.log({correlationId, msg});
}

app.use(middleware);

// this won't work, bodyParser is used after correlation middleware for this route
app.post("/", bodyParser.json(), (req, res) => {
  const correlationId = getId();
  await callToExternalSystem();
  logThis("epic message");
  res.json({ correlationId });
  ...
});

// workaround add the correlation middleware after the bodyParser
app.post("/", bodyParser.json(), middleware, (req, res) => {
  const correlationId = getId();
  await callToExternalSystem();
  logThis("epic message");
  res.json({ correlationId });
  ...
});

Changelog

Can be found here.

License

Released under the MIT license.