RStankov / SearchObjectGraphQL

GraphQL plugin for SearchObject gem
MIT License
159 stars 25 forks source link

N+1 Queries fix for Resolver #6

Closed panbanda closed 6 years ago

panbanda commented 6 years ago

Greetings! This is an amazing library thank you.

Is there a way to override the resolver to allow for batching or something like graphql-query-resolver? I don't want to mess up the searchobject resolver and also want to help my database breath a bit too...

Thanks

RStankov commented 6 years ago

Yes, you can 😀

Overwrite fetch_results and plug there. I have done in How to GraphQL tutorial here.

You can create a module for that:

module WithQueryResolver
  def fetch_results
    # NOTE: Don't run QueryResolver during tests
    return super unless context.present?

    GraphQL::QueryResolver.run(Link, context, Types::LinkType) do
      super
    end
  end
end

And use it like this:

class SearchResolver 
  include SearchObject.module(:graphql)
  include WithQueryResolver
end
panbanda commented 6 years ago

Thats fantastic. Works perfectly thank you.

panbanda commented 6 years ago

Just in case this helps anyone, here is the resolver I am using. If there are any tips I welcome them.

require 'search_object/plugin/graphql'
require 'graphql/query_resolver'

module Resolvers
  class BaseSearchResolver
    include ::SearchObject.module(:graphql)

    protected

    def self.use_query_resolver obj, obj_type
      define_method("resolver_obj") { obj }
      define_method("resolver_obj_type") { obj_type }
      include ClassMethods
    end

    module ClassMethods
      def fetch_results
        # NOTE: Don't run QueryResolver during tests
        return super unless context.present?

        GraphQL::QueryResolver.run(resolver_obj, context, resolver_obj_type) do
          super
        end
      end
    end
  end
end

module Resolvers
  class CategorySearchResolver < Resolvers::BaseSearchResolver
    use_query_resolver ::Category, Types::CategoryType

    # ...
  end
end
RStankov commented 6 years ago

@jylinman Thanks 🙌