Skip to content

Commit

Permalink
fix: apply context.bind where the context was lost
Browse files Browse the repository at this point in the history
Patch with code from PR loopbackio#275.
  • Loading branch information
Tom Kirkpatrick committed Jul 12, 2017
1 parent 507c0af commit a5c83f8
Showing 1 changed file with 20 additions and 4 deletions.
24 changes: 20 additions & 4 deletions lib/mongodb.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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);
}
Expand All @@ -1085,7 +1101,7 @@ MongoDB.prototype.all = function all(model, filter, options, callback) {
} else {
callback(null, objs);
}
});
}));
}
};

Expand Down Expand Up @@ -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);
}
Expand All @@ -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) {
Expand Down

0 comments on commit a5c83f8

Please sign in to comment.