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) {
    id
    full_name
    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])
    }
end

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