I am playing around with node.js and based on this wonderful tutorial I created two providers (SchemaProvider and EntityProvider).
They look both like:
var Db = require('mongodb').Db;
var Connection = require('mongodb').Connection;
var Server = require('mongodb').Server;
var BSON = require('mongodb').BSON;
var ObjectID = require('mongodb').ObjectID;
EntityProvider = function(host, port) {
this.db = new Db('timerange', new Server(host, port, {auto_reconnect: true}, {}));
this.db.open(function() {
console.log("Schema Provider has connected and may be used as of now.");
});
};
EntityProvider.prototype.getCollection = function(callback) {
this.db.collection('entity', function(error, collection) {
if (error) {
callback(error)
} else {
callback(null, collection);
}
});
};
EntityProvider.prototype.findById = function(id /* The id to be found */, callback) {
this.getCollection(function(error, collection) {
if (error) {
callback(error);
} else {
collection.findOne({_id: id}, function(error, result) {
if (error) {
callback (error);
} else {
callback(null, result);
}
});
}
});
};
In app.js I require('provider') where both providers are defined.
Then I do:
schemaProvider = new SchemaProvider('192.168.0.50', 27017);
entityProvider = new EntityProvider('192.168.0.50', 27017);
Now, I created a module named dao
(I come from a java/spring perspective :-)). As I didn't use "var", both variables and hence providers are accessible in my DAO. If I used "var", the providers wouldn't be accessible.
My question is :
If I wanted to use only one instance of the provider throughout the whole application, how would I do that?
Thanks in advance!
Setting globals (not using var) is a really bad practice, you should always avoid that.
If you want to have only an instance of the provider in your whole application you can do something like this:
provider.js
var providerInstance;
// define provider here
module.exports = function() {
providerInstance = providerInstance || new Provider('192.168.0.50', 27017);
return providerInstance;
}
That way the provider object gets created only once and then reused each time you require it:
app.js
var provider = require('./provider')();
app2.js
// using the same object as in app.js
var provider = require('./provider')();