Search code examples
ruby-on-railsgraphql-ruby

How to set the complexity of __typename in graphql-ruby


In a Rails application using the graphql-ruby gem, how do I make it so that the __typename does not add up to the complexity of the query?

By default, the complexity of all fields is 1, but I want to override it (customize it) so that it's 0.

We are tweaking our complexity calculation and we are trying to make all scalar fields cost 0. How do I do that?


Solution

  • I ended up creating a child class of DynamicFields where I can override the complexity of the typename field.

    # Redefines DynamicFields to set a custom complexity to the __typename field.
    # This module is then used in the schema definition.
    #
    # Doc:
    # https://graphql-ruby.org/schema/introspection#extending-a-built-in-type
    #
    # Original:
    # https://github.com/rmosolgo/graphql-ruby/blob/master/lib/graphql/introspection/dynamic_fields.rb
    
    module Introspection
      class DynamicFields < GraphQL::Introspection::DynamicFields
        field :__typename, String, null: false, complexity: 0, description: 'The name of this type'
      end
    end
    

    And then I had to use the introspection keyword to use it:

    class MySchema < GraphQL::Schema
      introspection(Introspection)
    end
    

    Reference: https://graphql-ruby.org/schema/introspection#extending-a-built-in-type