Reputation:
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:
using global variables
add the instance to the request object
add the instance to the response locals
add the instance to the app locals
What is the best way/practice to transport variables from one file to the whole application?
Upvotes: 1
Views: 422
Reputation: 8152
Use service architecture or dependency injection.
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
...
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
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