Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bind context where it was lost #275

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 20 additions & 4 deletions lib/mongodb.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,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 @@ -258,6 +273,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);
var context = {
model: model,
collection: collection, req: {
Expand Down Expand Up @@ -847,7 +863,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 @@ -870,7 +886,7 @@ MongoDB.prototype.all = function all(model, filter, options, callback) {
} else {
callback(null, objs);
}
});
}));
}
};

Expand Down Expand Up @@ -1000,7 +1016,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 @@ -1012,7 +1028,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);
});
}));
};

/**
Expand Down