Graphql-ruby: Modularize query_type.rb/mutation_type.rb

Created on 1 Jun 2018  路  2Comments  路  Source: rmosolgo/graphql-ruby

Hello everybody!

I'm using graphql-ruby with Rails API mode.

Is there a possibility to extract fields from query_type.rb/mutation_type.rb so you don't have one big file where all your fields are defined?

Like some kind of module where you define related fields and this module get included then in your query_type.rb.

Right now i didn't find anything regarding that in the documentation.

This could help to keep your code more organized.

For example from this:

class Types::QueryType < Types::BaseObject
  field :show_post, ....
  field :all_posts, ....  
  field :update_post, ...
  field :delete_post, .... 

  field :all_categories, ....  
  field :show_category, ....
  field :update_category, ...
  field :delete_category, .... 
  ...and so on
end

to something like this:

class Types::QueryType < Types::BaseObject
  include PostFields
  include CategoryFields
   ...and so on
end

If this isn't possible yet, maybe it would be a nice enhancement. What do you think @rmosolgo?

Thanks for your efforts in advance! :-)

Most helpful comment

Since you're using Rails you could use ActiveSupport::Concern e.g.

module PostFields
  extend ActiveSupport::Concern

  included do
    field :posts, [Post], null: false
  end

  def posts
    Posts.all
  end
end

class Types::QueryType < Types::BaseObject
  include PostFields
end

All 2 comments

Since you're using Rails you could use ActiveSupport::Concern e.g.

module PostFields
  extend ActiveSupport::Concern

  included do
    field :posts, [Post], null: false
  end

  def posts
    Posts.all
  end
end

class Types::QueryType < Types::BaseObject
  include PostFields
end

Ah thanks @jturkel,

that did the trick!

At first i tried to extract that stuff in a plain module. Like

module PostFields
  field :posts, [Post], null: false

  def posts
    Posts.all
  end
end

class Types::QueryType < Types::BaseObject
  include PostFields
end

But I didn't think it through correctly, and Ruby complained about a missing "field" method. The evaluation in the context of the class was wrong, which i later recognized.

After reading about concerns, I found another solution too, which I want to leave here, if somebody doesn't want to / can't use concerns:

module PostFields
  def self.included(mod)
    mod.class_eval do
      field :posts, [Post], null: false

      def posts
        Posts.all
      end
    end
  end
end

class Types::QueryType < Types::BaseObject
  include PostFields
end
Was this page helpful?
0 / 5 - 0 ratings

Related issues

dsgoers picture dsgoers  路  3Comments

ecomuere picture ecomuere  路  3Comments

rmosolgo picture rmosolgo  路  4Comments

peterphan1996 picture peterphan1996  路  3Comments

crice88 picture crice88  路  3Comments