Skip to content

Commit

Permalink
Make the middleware create a new traceparent if no header was provided
Browse files Browse the repository at this point in the history
  • Loading branch information
kristofferjansson committed Nov 8, 2024
1 parent 25bb7b7 commit 16e3078
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
3 changes: 2 additions & 1 deletion lib/middleware.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { RequestHandler } from "express";
import { AsyncLocalStorage } from "node:async_hooks";
import { createTraceparent } from "./traceparent";

type Store = {
traceparent?: string;
Expand All @@ -10,7 +11,7 @@ type Store = {
const storage = new AsyncLocalStorage<Store>();

export const middleware: RequestHandler = (req, _res, next) => {
const traceparent = req.header("traceparent");
const traceparent = req.header("traceparent") || createTraceparent();

storage.run({ traceparent }, () => {
next();
Expand Down
11 changes: 11 additions & 0 deletions test/unit/middleware.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,17 @@ describe("Express middleware", () => {
});
});

it("should create a new traceparent and store it in the store if no traceparent header was provided", () => {
const req = { header: () => {} };

// @ts-expect-error - We don't need the full Express Request object
middleware(req, {}, () => {
const traceparent = getStore().traceparent;
expect(traceparent).to.not.equal(undefined);
expect(traceparent.length).to.equal(55);
});
});

it("should return an empty object if the middleware is not used", () => {
expect(getStore()).to.deep.equal({});
});
Expand Down

0 comments on commit 16e3078

Please sign in to comment.