node express routing pass variable to required module

202 views Asked by At

I have a main index.js file as:

var express = require('express')

require("dotenv").config();

const db = require('./services/db_service').db_connection()

const customers = require('./routes/customers');

var app = express();

app.use('/customers', customers)(db) <--- I suppose something like this

app.listen(process.env.PORT, function () {
  console.log(`Example app listening on port ${process.env.PORT}!`)
})

And in routes/customers.js:

var express = require('express');
const router = express.Router();

router.get('/' , (req, res) => {
    db.query('SELECT * FROM customers', (err, rows, fields) => { <-- db.query
        if (!err)
            res.send(rows);
        else
            console.log(err);
    })
} );

Is there a way to pass db to routes/customers from index?

1

There are 1 answers

0
Quang Huy On BEST ANSWER

You can write middleware function to set db connection:

// index.js
app.use(function (req, res, next) {
  req.db = db
  next()
})

// routes/customers.js
router.get('/' , (req, res) => {
    req.db.query('SELECT * FROM customers', (err, rows, fields) => { <-- db.query
        if (!err)
            res.send(rows);
        else
            console.log(err);
    })
} );