record_loader.rb 842 B

1234567891011121314151617181920212223242526272829
  1. # Copyright (C) 2012-2023 Zammad Foundation, https://zammad-foundation.org/
  2. # https://github.com/Shopify/graphql-batch/blob/af45e5b9e560abb8eb2b97657928e460d4dcf96a/examples/record_loader.rb
  3. class Gql::RecordLoader < GraphQL::Batch::Loader # rubocop:disable GraphQL/ObjectDescription
  4. def initialize(model, column: model.primary_key, where: nil)
  5. super()
  6. @model = model
  7. @column = column.to_s
  8. @column_type = model.type_for_attribute(@column)
  9. @where = where
  10. end
  11. def load(key)
  12. super(@column_type.cast(key))
  13. end
  14. def perform(keys)
  15. query(keys).each { |record| fulfill(record.public_send(@column), record) }
  16. keys.each { |key| fulfill(key, nil) if !fulfilled?(key) }
  17. end
  18. private
  19. def query(keys)
  20. scope = @model
  21. scope = scope.where(@where) if @where
  22. scope.where(@column => keys)
  23. end
  24. end