lundi 18 octobre 2021

What is the best practice to pass db and logger to routes in Express

Using Express, to pass single instance references like a logger and/or db to routes, I see three options currently.

First is to attach it to the request object via a middleware:

app.use(function(req,res,next){
req.db = db; //this db comes from app.js context where you define it
next();
});

or in app as:

app.set('db', db) // db was previously set
...
app.get('user/:id', users.getUser);

then inside your route function call to use:

module.export.getUser = (req,res) {
...
req.app.get('db').user.find(request.params.id)

Next way is to call some init method on the controller, ie:

const users = require('user.js);
... //setup logger, setup db, then call:
users.init(logger,db); // init method sets local logger/database inside user.js

Last is a variation on the above which forces init to happen once when the module is required:

// setup db and logger, then later call:
require('user.js')(db, logger) //not great style-wise by not having all requires near the top of doc

and in your user.js, set your export like so:

module.exports = (db, logger) => { // returning public functions

This is what I really hate about vanilla JS, and even a framework like Express. It's part of the reason why frameworks like React are so popular because there are set ways to do things or at least commonly accepted patterns.

Ok, back to the topic. What's the best practice for passing single instance things like a logger and database to all your routes/controllers? One of the above or something better?

Unfortunately if you search for "express best practices for routers", you'll get dozens of variations. Is there some goto reference/bible? Some best practice or best pattern guide?

Thanks for any advise/feedback, Paul

Aucun commentaire:

Enregistrer un commentaire