DEV Community

Discussion on: Tracing requests in Node.js?

Collapse
 
fernandocalsa profile image
Fernando Calvo • Edited

Hi! pretty late but maybe this helps others, what I usually try is to inject the models or the services in the request, so from your router code you can do something like

app.get(
    '/api/v1/customer/:id',
    async (req, res, next) => {
        const id = req.params.id
        const customer = req.context.customerService.get(id)
        /// ... process and return response
    }
)

You should create the customerService in a previous middleware and inject it to the context, so you can access to it from the context, and the service can access to the context as well.

I wrote a blog post about it here dev.to/fernandocalsa/sharing-the-c...