DEV Community

Discussion on: Tracing requests in Node.js?

 
qm3ster profile image
Mihail Malo • Edited

@sathishkumarsoundharajan When it comes in as a constructor parameter or method parameter, to have it be typed in your editor/IDE, you have to annotate it in place.
@henryjw posed a particular problem, where they didn't want type annotations inside the handler method files. In order to still have types available, the logger must be imported instead of injected. So, we import a function that provides the logger.
How does it tie the logger to the current context? Well, why not use the request.
So, we import the logger "factory", give it the untyped "req" object, and get back a strongly typed (in terms of editor autocompletion) logger object.
Can do it like this if we don't want to have a special middleware createing the logger first:

// logger.js
const map = new WeakMap

export const get = req => {
  const logger = map.get(req)
  if (logger) return logger
  const newLogger = new Logger(req.something, req.somethingElse)
  map.set(req, newLogger)
  return newLogger
}

So, if your whole project is in TypeScript or something, it isn't a big advantage.
And if you don't care about typings, it isn't a big advantage.
But it solves the unique specific problem posed in the post.

It's still less coupling/boilerplate than providing specifically the logger as a service constructor argument or method argument. All mentions of "logger" will disappear from the routing glue code (except where you want to log for routing reasons).