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
?
You can write middleware function to set db connection: