Sha256: 0bff2dec8adea6a89e099ec4cc977fc8e3d0a7a2789da13c6de7323f342ce6d9

Contents?: true

Size: 1.18 KB

Versions: 4

Compression:

Stored size: 1.18 KB

Contents

# frozen_string_literal: true

# preload resolver for queries
Rails.application.config.to_prepare do
  Types::QueryType.class_eval do
    # TODO: auto recover type_klass using result key
    # Add corresponding preloads to query results
    #   Note: key is automatically calculated based on method name
    # @param gql_result_key (String | Sym)
    # @param collection (ActiveCollection)
    # @param type_klass (GQL TypeClass, default: calculates using return type)
    def include_gql_preloads(gql_result_key, collection, type_klass = nil)
      type_klass ||= preload_type_klass(gql_result_key.to_s)
      klass = GraphqlPreloadQueries::Extensions::Preload
      ast_node = preload_find_node(gql_result_key)
      klass.preload_associations(collection, ast_node, type_klass)
    end

    private

    # @param key: Symbol
    def preload_find_node(key)
      main_node = context.query.document.definitions.first
      main_node.selections.find { |node_i| node_i.name == key.to_s }
    end

    # @param result_key: String
    def preload_type_klass(result_key)
      res = self.class.fields[result_key].instance_variable_get(:@return_type_expr)
      res.is_a?(Array) ? res.first : res
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
graphql_preload_queries-0.3 config/initializers/add_query_helper.rb
graphql_preload_queries-0.2.2 config/initializers/add_query_helper.rb
graphql_preload_queries-0.2.1 config/initializers/add_query_helper.rb
graphql_preload_queries-0.2.0 config/initializers/add_query_helper.rb