Curry pattern for reading config files (NodeJS)
The curry pattern can be used to read once a configuration file, then use it every time you need it.
Here's a node module to read a configuration file, use it to connect to Mongo, then for each
update
we're using the curried result.Note that
promise
s can only be resolved once, so this ensures then we only connect to Mongo once. This may or may not be exactyl what you want (think db.close()
)
"use strict";
var fs = require('fs');
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var getDb;
function curriedConnection() {
var config = JSON.parse(fs.readFileSync('./config/mongoconfig.json'));
return MongoClient.connect('mongodb://' + config.url + ':' + config.port + '/' + config.dbname);
}
function init() {
getDb = curriedConnection();
return Promise.resolve();
}
function updateDb() {
return new Promise(function (resolve, reject) {
getDb
.then(function (db) {
var collection = db.collection("notescollection");
return collection.find({
uri: "shoes-note"
}).toArray();
})
.then(resolve)
.catch(resolve);
});
}
exports.updateDb = updateDb;
exports.init = init;
and more general tests (paste to JS Bin). Note that both mypromise
and getConfig
will only run once:
function promisedCalc(avalue){
return mypromise.then(function(thisresult){
return avalue * thisresult;
});
}
var mypromise = new Promise(function(resolve){
console.log("called");
setTimeout(resolve(12),100);
});
function getConfig(){
console.log("getting config");
return 3;
}
var dbConnection;
function curriedDb() {
var myconfig = getConfig();
return promisedCalc;
}
dbConnection = curriedDb();
function logger(avalue){
console.log(avalue);
}
dbConnection(4).then(logger);
dbConnection(5).then(logger);
dbConnection(6).then(logger);
dbConnection(7).then(logger);