I’m trying to wrap my head around GraphQL/Relay and I’m finding hard to get started on how to correctly setup a Relay compliant GraphQL API using Ruby on Rails.
I’ve found multiple tutorials on how to do this:
https://medium.com/react-weekly/relay-facebook-on-rails-8b4af2057152#.gd8p6tbwi
https://medium.com/@gauravtiwari/graphql-and-relay-on-rails-getting-started-955a49d251de#.m05xjvi82
But they all refer to a graphql-relay
gem that doesn’t seem to be available at this moment: https://github.com/rmosolgo/graphql-relay-ruby
The grahql-ruby
gem has a section in the documentation specific to relay, but I’m finding hard to understand what is needed to set this up to be consumed by a Relay client.
What is necessary to implement a GraphQL API for a Relay client in Rails?
2
Answers
I just want to leave here my findings for anyone who gets stuck with this in the future and wants to get pointed to a better direction.
First, the
graphql-ruby
gem includes everything that is needed to implement a Relay compatible GraphQL API. In includes everything that was before in thegraphql-relay
gem.You need to provide 2 things in your Schema in order to make the Relay refetching feature to work well, an
id_from_object
method that converts an object in your domain, into a global id and also aobject_from_id
method that will decode the global id into an object in your application:Also, all your types should implement the
NodeInterface
provided by the ruby gem, and expose aglobal_id_field
instead of an ID type:This will allow Relay to refetch data like this:
Relay also uses a
babel-relay-plugin
which requires a schema.json to be generated and available to the client, if you're building an isolated API with no view rendering, the way to go is to let the clients fetch the schema and not to do that work in the server, something like apollo-codegen can work. However, if you are building a rails app and need the schema in the same app, then you can run an instrospection query and save the result to a json file using a rake task:Lastly, you'll need to understand that Relay expresses one-to-many relationships with connections:
Connections support some arguments out of the box, you can use
first
,last
,before
andafter
in your connection queries:All of this is documented in the Relay documentation so make sure you read it as well as the graphql-ruby documentation.
have you tried installing it?
in Gemfile: