Parameterized GraphQL Fields!?!?!

Do you love GraphQL, but lament the inability to query values that depend on passed-in parameters? Great news, there is a solution: Parameterized GraphQL Fields!

Consider a query which returns some fun things about the user. One of which is their favorites! Favorites can return different categories of a user’s favorite things. For example you could pass in ‘books’ as a category, and get a list of the user’s favorite books. Or ‘cuisines’ to get a list of the user’s favorite… well you see where this is going!

Here’s the frontend code:

query user($user_id: ID, $category?: String) {
 user(user_id: $user_id) {
    favorites(category: $category)

And the backend code, using graphql-ruby.

field :favorites, FavoriteType, 'Favorite things belonging to the user' do
argument :category, types.String
    resolve ->(user, args, ctx) {
      return user.favorites.where(category: args[:category])

It’s just that easy—you really can have it all!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s