diff --git a/lib/middleware.ts b/lib/middleware.ts index cf64a01..5073a46 100644 --- a/lib/middleware.ts +++ b/lib/middleware.ts @@ -1,5 +1,6 @@ import type { RequestHandler } from "express"; import { AsyncLocalStorage } from "node:async_hooks"; +import { createTraceparent } from "./traceparent"; type Store = { traceparent?: string; @@ -10,7 +11,7 @@ type Store = { const storage = new AsyncLocalStorage(); export const middleware: RequestHandler = (req, _res, next) => { - const traceparent = req.header("traceparent"); + const traceparent = req.header("traceparent") || createTraceparent(); storage.run({ traceparent }, () => { next(); diff --git a/test/unit/middleware.test.ts b/test/unit/middleware.test.ts index c2dd2a0..285ebfd 100644 --- a/test/unit/middleware.test.ts +++ b/test/unit/middleware.test.ts @@ -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({}); });