Created
November 29, 2014 11:48
-
-
Save fabien/76c28baa99de1bbdc141 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice mixin, that works good. Thanks.
Obs: in this line
include()
should beincludes()