Sha256: fbe7f43ed3b21fa2ccee0f85f40cfae948784baf3f97d0495bf58a946b63acfd

Contents?: true

Size: 1.15 KB

Versions: 1

Compression:

Stored size: 1.15 KB

Contents

# frozen_string_literal: true

# preload resolver for mutations
Rails.application.config.to_prepare do
  GraphQL::Schema::Mutation.class_eval do
    # TODO: auto recover type_klass using result key
    # Add corresponding preloads to mutation results
    # @param query_key (String | Sym)
    # @param collection (ActiveCollection)
    # @param type_klass (GQL TypeClass)
    def include_gql_preloads(collection, query_key:, type_klass: nil)
      gql_result_key = GraphQL::Schema::Member::BuildType.camelize(query_key.to_s)
      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

    def preload_find_node(key)
      main_node = context.query.document.definitions.first.selections.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

1 entries across 1 versions & 1 rubygems

Version Path
graphql_preload_queries-0.4.0 config/initializers/add_mutation_helper.rb