From a5c83f8e89e85e274da71e36d4ad20fa9cb16959 Mon Sep 17 00:00:00 2001 From: Tom Kirkpatrick Date: Wed, 12 Jul 2017 09:28:19 +0200 Subject: [PATCH] fix: apply context.bind where the context was lost Patch with code from PR #275. --- lib/mongodb.js | 24 ++++++++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/lib/mongodb.js b/lib/mongodb.js index 95179c273..060833326 100644 --- a/lib/mongodb.js +++ b/lib/mongodb.js @@ -56,6 +56,21 @@ function generateMongoDBURL(options) { } } +/*! + * Tries to get the context and patch the function passed as argument + * @param {Function} the function to patch + * @param {String} [scopeName=loopback] the scope name + * @returns {Function} the function patched + */ +function patchWithContext(fn, scopeName) { + scopeName = scopeName || 'loopback'; + var ns = process && process.context && process.context[scopeName]; + if (ns && ns.bind) { + fn = ns.bind(fn); + } + return fn; +} + /** * Initialize the MongoDB connector for the given data source * @param {DataSource} dataSource The data source instance @@ -285,6 +300,7 @@ MongoDB.prototype.execute = function(model, command) { var args = [].slice.call(arguments, 2); // The last argument must be a callback function var callback = args[args.length - 1]; + callback = patchWithContext(callback); // Topology is destroyed when the server is disconnected // Execute if DB is connected and functional otherwise connect/reconnect first @@ -1061,7 +1077,7 @@ MongoDB.prototype.all = function all(model, filter, options, callback) { } else if (filter.offset) { cursor.skip(filter.offset); } - cursor.toArray(function(err, data) { + cursor.toArray(patchWithContext(function(err, data) { if (self.debug) { debug('all', model, filter, err, data); } @@ -1085,7 +1101,7 @@ MongoDB.prototype.all = function all(model, filter, options, callback) { } else { callback(null, objs); } - }); + })); } }; @@ -1229,7 +1245,7 @@ MongoDB.prototype.updateAttributes = function updateAttrs(model, id, data, optio this.execute(model, 'findAndModify', { _id: oid }, [ ['_id', 'asc'], - ], data, {}, function(err, result) { + ], data, {}, patchWithContext(function(err, result) { if (self.debug) { debug('updateAttributes.callback', model, id, err, result); } @@ -1241,7 +1257,7 @@ MongoDB.prototype.updateAttributes = function updateAttrs(model, id, data, optio self.setIdValue(model, object, id); object && idName !== '_id' && delete object._id; cb && cb(err, object); - }); + })); }; function errorIdNotFoundForUpdate(modelvalue, idValue) {