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:
git clone git@github.com:a8m/ent-graphql-example.git
cd ent-graphql-example
go run ./cmd/todo/
+interface Node {
+ id: ID!
+}
-type Todo {
+type Todo implements Node {
id: ID!
createdAt: Time
status: Status!
priority: Int!
text: String!
parent: Todo
}
type Query {
todos: [Todo!]
+ node(id: ID!): Node
+ nodes(ids: [ID!]!): [Node]!
}
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:
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:
func (r *queryResolver) Node(ctx context.Context, id int) (ent.Noder, error) {
return r.client.Noder(ctx, id)
}
func (r *queryResolver) Nodes(ctx context.Context, ids []int) ([]ent.Noder, error) {
return r.client.Noders(ctx, ids)
}
Query Nodes
Running the Nodes API on one of the todo items will return:
query {
... on Todo {
text
}
}
}
# Output: { "data": { "node": { "id": "1", "text": "Create GraphQL Example" } } }
Running the Nodes API on one of the todo items will return:
query {
nodes(ids: [1, 2]) {
id
... on Todo {
text
}
}
}
# 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.