ruby-on-railsrubygraphqlgraphql-ruby

Add an additional field to associated GraphQL field return type


I have this GraphQL type in my application.

module Types
  module MyApp
    class MembersStatus < Types::Base::Object
      field :active, [Types::MyApp::User], null: true
      field :on_leave, [Types::MyApp::User], null: true
      field :status_unknown, [Types::MyApp::User], null: true
    end
  end
end

I want to add an additional field to the associated User Type for the on_leave field.

For example, for the on_leave field, I want to have the associated User to have an additional field leave_duration

field :leave_duration, Integer, null: true

So that, I can make queries like below:

query memberStatus{
  memberStatus {
    active { name }
    onLeave { name leaveDuration }
    statusUnknown { name } 
  }
}

I have looked into https://graphql-ruby.org/type_definitions/extensions.html#customizing-fields this doc but can't implement it yet. Can this be done? Please help.


Solution

  • Just as you described, you need to add the leave_duration field to the user type.

    module Types
      module MyApp
        class UserType
          # other stuff
          field :leave_duration, GraphQL::Types::ISO8601Date, null: true
    
          # Optional: Define leave_duration if it isn't already a field on the model:
          def leave_duration
            # implementation that returns a date
          end
        end
      end
    end
    

    It looks like you may have had a typo in the field() call, where :leave_duration should be a symbol, not a variable or method. That is fixed in the above snippet.

    Edit: Regarding your question about conditionally having leave_duration only when on_leave, I would suggest this:

    def leave_duration
      return nil unless object.on_leave
    
      # implementation that returns a date
    end
    

    There is a way to hide the field from the schema, which is described here: https://github.com/rmosolgo/graphql-ruby/issues/893

    But it seems way too overkill to me to hide a field based on the presence of another field. I think this is mainly intended to hide fields like is_admin for non-admin users.