nixgadgets nixgadgets - 6 months ago 20
Javascript Question

Get environment specific configuration from a JSON object using Lodash

Given that I have the following JSON object,

dbConfig = {
"db": "default",
"default": {
"defaultDB": "sqlite",
"init": "init",
"migrations": {
"directory": "migrations",
"tableName": "migrations"
},
"pool": {
"min": "2",
"max": "10"
},
"sqlite": {
"client": "sqlite3",
"connection": {
"filename": "data/default/sqlitedb/test.db"
}
},
"oracle": {
"client": "oracledb",
"config": {
"development": {
"user": "test",
"pass": "test",
"db": "test"
},
"production": {
"user": "test",
"pass": "test",
"db": "test"
},
"test": {
"user": "test",
"pass": "test",
"db": "test"
}
}
}
}
};


Using Node & Lodash, is there any possibility of getting either
connection
or
config.
depending on what
dbConfig.default[dbConfig.default.defaultDB]
is set to.

So for instance if i set
dbConfig.default.defaultDB=oracledb
and
process.env.NODE_ENV=development
I want to be able to get
dbConfig.default[dbConfig.default.defaultDB].config.development


Or if I set
dbConfig.default.defaultDB=sqlite
just to get
dbConfig.default[dbConfig.default.defaultDB].connection


In other words, if the database has environment specific configuration then this will be in
"config": {}
and if not in
"connection": {}


It doesn't have to be Lodash. It can also be plain javascript.

Answer

Solution without lodash

var defaultDbName = dbConfig.default[dbConfig.default.defaultDB];

var db;
if (defaultDb === 'sqllite') {
  db = dbConfig.default[defaultDb].connection;
} else {
  var env = process.env.NODE_ENV;
  db = dbConfig.default[defaultDb].config[env];
}

Solution with lodash

Here I'm using lodash get function to get object field value or null if it doesn't exist. Also I'm using template string syntax: ${val} to format field path.

var defaultDbName = dbConfig.default[dbConfig.default.defaultDB];
var defaultDbConf = dbConfig.default[defaultDb];
var env = process.env.NODE_ENV;

var db = defaultDbConf.connection || _.get(defaultDbConf, `config.${env}`);

Btw, your configuration json is too complex, much better to have configuration per environment.

Comments