puzpuzpuz / cls-rtracer

Request Tracer - CLS-based request id generation for Express, Fastify, Koa and Hapi, batteries included
MIT License
311 stars 24 forks source link

Dynamically add values to the current rTracer Ids #76

Closed OllyNural closed 5 months ago

OllyNural commented 5 months ago

Is there any way to add new Ids to the existing ones that are already set up with rTracer?

e.g after having set it up with

    app.use(rTracer.koaMiddleware({
        requestIdFactory: (req) => ({
          correlationId: req.get('X-CorrelationId') || randomUUID(),
          otherVars...
        }),
      }));

And then later on, for example after we finish some authentication middleware, and we want to store some extra information only available after that middleware has completed.

So after we can add like Third Party contextual information or where the request came from etc.

Thanks!

puzpuzpuz commented 5 months ago

You can simply access the object you've generated as the request id and mutate it. Think of the object as if it were request context.

const requestCtx = rTracer.id();
console.log(requestCtx.correlationId); // this is your request id
requestCtx.otherVars = 'foobar'; // this field will be stored in the object
OllyNural commented 5 months ago

Ah brilliant, that's easy enough. Thank you very much, appreciate that, I'll give that a go

Very nice, simple but clean library.

OllyNural commented 5 months ago

The above example works perfect! I'll close this, thanks for the very speedy response :)