Skip to content

Instantly share code, notes, and snippets.

@fabien
Created November 29, 2014 11:48
Show Gist options
  • Save fabien/76c28baa99de1bbdc141 to your computer and use it in GitHub Desktop.
Save fabien/76c28baa99de1bbdc141 to your computer and use it in GitHub Desktop.
module.exports = function(Model, options) {
var mergeQuery = require('loopback-datasource-juggler/lib/utils').mergeQuery;
var _ = require('lodash');
var scopes = options.scopes || _.keys(Model.scopes);
var validScopes = {};
_.each(Model.scopes, function(scope, name) {
if (scope.modelFrom === Model && scope.modelFrom === scope.modelTo) {
if (_.include(scopes, name)) validScopes[name] = scope;
}
});
Model.mergeScopes = function(scopes) {
var self = this;
scopes = _.flatten(arguments);
var merged = {};
_.each(scopes, function(scope) {
var definition = validScopes[scope];
if (definition && _.isFunction(definition.params)) {
mergeQuery(merged, definition.params.call(self) );
} else if (definition && _.isObject(definition.params)) {
mergeQuery(merged, definition.params);
}
});
return merged;
};
var applyScope = Model.applyScope;
Model.applyScope = function(query) {
var scopes = [].concat(query.scopes || query.scope || []);
if (!_.isEmpty(scopes)) {
mergeQuery(query, this.mergeScopes(scopes));
}
applyScope.call(this, query);
};
};
@marcoskubis
Copy link

Nice mixin, that works good. Thanks.
Obs: in this line include() should be includes()

@fabien
Copy link
Author

fabien commented Oct 14, 2016

@marcoskubis you're welcome! _.include vs. _.includes depends on the lodash version used.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment