nodejs-1440x900

Node.js – Database connection depends on environments

I hate when I need to use the same password on all of my computers only because I develop on multiple machines. For instance, I want to connect to the +MySQL database from my +node.js application , but my local configuration differs from the production environment (surprising thing is not it?).

// If DB env does not exists we need to declare
if (typeof process.env.DB == "undefined" || !process.env.DB ) {
  // Clockwork is my personal computer where I code primarily
  process.env.DB = "clockwork";
}

 

// If DB env has an unknown value
// override it
if (process.env.DB !== “clockwork” &&
process.env.DB !== “yitsushisa” &&
process.env.DB !== “production”) {
process.env.DB = “clockwork”;
}

// configurations
var connections = {
clockwork: {
host: “localhost”,
name: “xxxxxx”,
password: “xxxxxxx”,
username: “xxxxxxx”
},
yitsushisa: {
host: “localhost”,
name: “xxxxxxyy”,
password: “xxxxxxx”,
username: “yyyyyyy”
},
production: {
host: “master.db.host”,
name: “zzzzzzzz”,
password: “xzzzxzxxxz”,
username: “zzxyxxzxyz”
}
};

module.exports = (function() {
return {
wsdl: {
priceList: “https://xxxx:xxxx@xxxxxx/ws/pricelist.asmx?WSDL”
},
xhr: {
priceList: “https://xxxxxx:443/ws/pricelist.asmx”,
resources: “https://xxxxxx:443/ws/resources.asmx”,
order: “https://xxxxxx:443/ws/Order.asmx”
},
auth: {
username: “xxxxxx”,
password: “xxxxxx”
},
sql: {
prefix: “abhu-“,
database: connections[process.env.DB],
margin: 1.06
}
};
})();
// EOF

So I created a simple method to solve it. Now when I call this configuration file then I can point to properties directly.

var configuration = require('../etc/mymodule.js');
console.log(configuration.sql.database.username);

The only thing I need to call the main application like this:

DB="production" node app.js parameters

If you have got a better but simple solution, please tell it :)

Related Posts:

Balazs Nadasdi

Developer, Project Manager, Blogger, Dad... or sometihng like these