Recently, I am implementing API using graphql-ruby
. In the beginning, I wrote the logic in query_type.rb
. But when the number of queries is large, it's hard to see!
Therefore, I would like to explain how to divide each query without writing logic in query_type.rb
.
First, suppose query_type.rb, which originally wrote the query, looks like this.
types/query_type.rb
module Types
class Query < Types::BaseObject
field :user, ObjectTypes::UserType, null: false do
argument :id, ID, required: true
end
def user(id:)
User.find(id)
end
field :post, ObjectTypes::PostType, null: false do
argument :id, ID, required: true
end
def post(id:)
Post.find(id)
end
end
It's a simple query that takes an id as an argument and returns user and post. I would like to split each query that returns this user and post into two files (user.rb, post.rb).
Now let's split the query. First, change query_types.rb as follows.
types/query_type.rb
module Types
class QueryType < Types::BaseObject
field :user, resolver: Queries::User #Define a query that returns user
field :post, resolver: Queries::Post #Define a query that returns a post
end
Define only field in query_type.rb as above. Use resolever to specify where the actual logic is. Next, define the actual logic (resolver). This time, I created a folder called queries directly under the graphql folder.
queries/user.rb
module Queries
class User < BaseQuery
type ObjectTypes::UserType, null: false
argument :id, ID, required: true
def resolve(id:)
User.find(id)
end
end
Now that we have written the resolver defined in query_type.rb, we can get the user. There is no problem if you prepare post.rb for post as well. I personally highly recommend it because it will be much easier to see just by splitting the file!
Recommended Posts