Relay Node Interface

Clone the code (optional)

The code for this tutorial is available under , and tagged (using Git) in each step. If you want to skip the basic setup and start with the initial version of the GraphQL server, you can clone the repository and checkout as follows:

  1. git clone git@github.com:a8m/ent-graphql-example.git
  2. cd ent-graphql-example
  3. go run ./cmd/todo/
  1. +interface Node {
  2. + id: ID!
  3. +}
  4. -type Todo {
  5. +type Todo implements Node {
  6. id: ID!
  7. createdAt: Time
  8. status: Status!
  9. priority: Int!
  10. text: String!
  11. parent: Todo
  12. }
  13. type Query {
  14. todos: [Todo!]
  15. + node(id: ID!): Node
  16. + nodes(ids: [ID!]!): [Node]!
  17. }

Then, we tell gqlgen that Ent provides this interface by editing the gqlgen.yaml file as follows:

To apply these changes, we must rerun the gqlgen code-gen. Let’s do that by running:

  1. go generate ./...

Like before, we need to implement the GraphQL resolve in the todo.resolvers.go file, but that’s simple. Let’s replace the default resolvers with the following:

  1. func (r *queryResolver) Node(ctx context.Context, id int) (ent.Noder, error) {
  2. return r.client.Noder(ctx, id)
  3. }
  4. func (r *queryResolver) Nodes(ctx context.Context, ids []int) ([]ent.Noder, error) {
  5. return r.client.Noders(ctx, ids)
  6. }

Query Nodes

Running the Nodes API on one of the todo items will return:

  1. query {
  2. ... on Todo {
  3. text
  4. }
  5. }
  6. }
  7. # Output: { "data": { "node": { "id": "1", "text": "Create GraphQL Example" } } }

Running the Nodes API on one of the todo items will return:

  1. query {
  2. nodes(ids: [1, 2]) {
  3. id
  4. ... on Todo {
  5. text
  6. }
  7. }
  8. }
  9. # Output: { "data": { "nodes": [ { "id": "1", "text": "Create GraphQL Example" }, { "id": "2", "text": "Create Tracing Example" } ] } }

Well done! As you can see, by changing a few lines of code our application now implements the Relay Node Interface. In the next section, we will show how to implement the Relay Cursor Connections spec using Ent which is very useful if we want our application to support slicing and pagination of query results.