1

I have a Node REST API using Express and JavaScript. I created a Database class that is able to connect, disconnect and execute the queries. My app.js (the entry file) creates an instance database of this and launches the express server. On requests I have the following flow:

  • requests call the middleware functions and finally the controller
  • the controller calls some other classes and passes in the data
  • Lastly these classes call the query files to access the database

The query files themselves need to access the instance of the database class. They can call the query function and pass in their prepared statement. I am not sure how to transport the instance database from my app.js (entry file) all the way to those query files.

I found multiple solutions:

What is the best way/practice to transport variables from one file to the whole application?

UtkarshPramodGupta
  • 7,486
  • 7
  • 30
  • 54
  • yes, sorry, your answer is a good one but I think dependency injection fits better. But I am waiting for a response from indabz. But +1 for yours :) –  Aug 19 '19 at 06:24

2 Answers2

2

Use service architecture or dependency injection.

Service architecture Way:

Make a directory structure like this:

root (directory)
|
|-->app.js
|-->controllers (directory)
|-->services (directory)
      |
      |-> DatabaseService.js
      |-> XYZService.js
      |-> index.js

Now in your index.js file require the service classes and export the instances of those classes, like so:

var Database =  require('./DatabaseService')
var XYZ = require('./XYZService')

module.exports = {
    database: new Database(),
    xyz: new XYZ()
}

Now, require these services wherever you want in your code, like so:

// SomeController.js
var database = require('../services').database

...
// DO WHATEVER YOU WANT WITH 'database' variable
...

Dependency Injection Way:

I'm assuming you are using express routes. Do a dependency injection by wrapping your route-controller inside a lambda function, like so:

api.get('/user/:id', function (req, res) { // <-- wrapping 
   var database = new Database()
   return yourRouteController(req, res, database) // <-- Inject your database instance here
})

PS I personally prefer the Service way as it's more modular and readable.

UtkarshPramodGupta
  • 7,486
  • 7
  • 30
  • 54
1

The only other solution I've seen for something like this is using dependency injection. It's still using the global variable but instead of tossing it down the line from one class to the other, you could call up that particular instance of your db connection at any point while your app is runnning.

indabz
  • 11
  • 1
  • thanks for your reply. Would you mind providing an example for this? I think using dependency injection should be the correct answer –  Aug 19 '19 at 06:05