Skip to content

Commit a5c83f8

Browse files
author
Tom Kirkpatrick
committed
fix: apply context.bind where the context was lost
Patch with code from PR loopbackio#275.
1 parent 507c0af commit a5c83f8

File tree

1 file changed

+20
-4
lines changed

1 file changed

+20
-4
lines changed

lib/mongodb.js

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,21 @@ function generateMongoDBURL(options) {
5656
}
5757
}
5858

59+
/*!
60+
* Tries to get the context and patch the function passed as argument
61+
* @param {Function} the function to patch
62+
* @param {String} [scopeName=loopback] the scope name
63+
* @returns {Function} the function patched
64+
*/
65+
function patchWithContext(fn, scopeName) {
66+
scopeName = scopeName || 'loopback';
67+
var ns = process && process.context && process.context[scopeName];
68+
if (ns && ns.bind) {
69+
fn = ns.bind(fn);
70+
}
71+
return fn;
72+
}
73+
5974
/**
6075
* Initialize the MongoDB connector for the given data source
6176
* @param {DataSource} dataSource The data source instance
@@ -285,6 +300,7 @@ MongoDB.prototype.execute = function(model, command) {
285300
var args = [].slice.call(arguments, 2);
286301
// The last argument must be a callback function
287302
var callback = args[args.length - 1];
303+
callback = patchWithContext(callback);
288304

289305
// Topology is destroyed when the server is disconnected
290306
// Execute if DB is connected and functional otherwise connect/reconnect first
@@ -1061,7 +1077,7 @@ MongoDB.prototype.all = function all(model, filter, options, callback) {
10611077
} else if (filter.offset) {
10621078
cursor.skip(filter.offset);
10631079
}
1064-
cursor.toArray(function(err, data) {
1080+
cursor.toArray(patchWithContext(function(err, data) {
10651081
if (self.debug) {
10661082
debug('all', model, filter, err, data);
10671083
}
@@ -1085,7 +1101,7 @@ MongoDB.prototype.all = function all(model, filter, options, callback) {
10851101
} else {
10861102
callback(null, objs);
10871103
}
1088-
});
1104+
}));
10891105
}
10901106
};
10911107

@@ -1229,7 +1245,7 @@ MongoDB.prototype.updateAttributes = function updateAttrs(model, id, data, optio
12291245

12301246
this.execute(model, 'findAndModify', { _id: oid }, [
12311247
['_id', 'asc'],
1232-
], data, {}, function(err, result) {
1248+
], data, {}, patchWithContext(function(err, result) {
12331249
if (self.debug) {
12341250
debug('updateAttributes.callback', model, id, err, result);
12351251
}
@@ -1241,7 +1257,7 @@ MongoDB.prototype.updateAttributes = function updateAttrs(model, id, data, optio
12411257
self.setIdValue(model, object, id);
12421258
object && idName !== '_id' && delete object._id;
12431259
cb && cb(err, object);
1244-
});
1260+
}));
12451261
};
12461262

12471263
function errorIdNotFoundForUpdate(modelvalue, idValue) {

0 commit comments

Comments
 (0)