user9945420
user9945420

Reputation:

How to make variables of one file accessible along the entire application?

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:

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?

Upvotes: 1

Views: 422

Answers (2)

UtkarshPramodGupta
UtkarshPramodGupta

Reputation: 8152

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.

Upvotes: 2

indabz
indabz

Reputation: 11

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.

Upvotes: 1

Related Questions