Created
November 13, 2017 21:57
-
-
Save tiegz/acfaa012c971b470af397b33589d5963 to your computer and use it in GitHub Desktop.
CountLoader
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
# Param-based count loader (for params and foreign keys). | |
# | |
# Example: | |
# CountLoader.for(Category).load(category_id) | |
# | |
class CountLoader < GraphQL::Batch::Loader | |
def initialize(model, param: :id, scope: nil) | |
@model = model | |
@param = param | |
@scope = case scope | |
when Symbol | |
scope.to_proc | |
when Hash | |
->(mod) { mod.where(scope) } | |
when ActiveRecord::Relation | |
->(_) { scope } | |
end | |
end | |
def perform(ids) | |
scope = @scope ? @scope.call(@model) : @model | |
scope.where(@param => ids).group(@param).count | |
.each_pair { |record_id, count| fulfill(record_id.to_s, count) } | |
ids.each { |id| | |
id_ = id.to_s | |
fulfill(id_, nil) unless fulfilled?(id_) | |
} | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment