-
-
Save marcoskubis/2cb04996a5b40cec7cd3b3d841dda8b4 to your computer and use it in GitHub Desktop.
Mixin for query scope on rest for loopback
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 (_.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