Skip to content

Instantly share code, notes, and snippets.

@marcoskubis
Forked from fabien/gist:76c28baa99de1bbdc141
Last active October 18, 2016 20:33
Show Gist options
  • Save marcoskubis/2cb04996a5b40cec7cd3b3d841dda8b4 to your computer and use it in GitHub Desktop.
Save marcoskubis/2cb04996a5b40cec7cd3b3d841dda8b4 to your computer and use it in GitHub Desktop.
Mixin for query scope on rest for loopback
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 (_.includes(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);
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment