I'd like to remove some of the repeated code in my mongo data access layer. The code is all the same except for these key areas:
- Function signature parameters differ between
collectionFind
andcollectionDistinct
though they both have a callbackcb
. - The line below
// HERE IS THE LINE THAT VARIES
I suspect I can use a closure to pass in cb
to the (innerErr, result)
callback but that only solves part of the problem so was curious about other ideas.
collectionFind: function collectionFind(collectionName, query, fields, options, cb) {
var url = getUrl();
if (!url) {
logger.error('No mongodb connection set');
} else {
getConnection(url, (err, db) => {
if (err) {
logger.error(`Cannot connect to mongo: ${err}`);
clearConnection();
} else {
// HERE IS THE LINE THAT VARIES
find(db, collectionName, query, fields, options, (innerErr, result) => {
if (innerErr) {
clearConnection();
cb(innerErr);
} else {
cb(null, result);
}
});
}
});
}
},
collectionDistinct: function collectionDistinct(collectionName, field, filter, cb) {
let url = getUrl();
if (!url) {
logger.error('No mongodb connection set');
} else {
getConnection(url, (err, db) => {
if (err) {
logger.error(`Cannot connect to mongo: ${err}`);
} else {
// HERE IS THE LINE THAT VARIES
distinctDocuments(db, collectionName, field, filter, (innerErr, result) => {
if (innerErr) {
clearConnection();
cb(innerErr);
} else {
cb(null, result);
}
});
}
});
}
}