Graphql relationships: Difference between revisions
From wikinotes
Line 40: | Line 40: | ||
* Edges are connections between two nodes. (ex: Task and assigned User) | * Edges are connections between two nodes. (ex: Task and assigned User) | ||
* Connections contain a list of edges, and a cursor to iterate through them | * Connections contain a list of edges, and a cursor to iterate through them | ||
Sample Schema extract | |||
<syntaxhighlight lang="python"> | |||
type QueryRoot { | |||
users( | |||
after: String # elements after cursor. | |||
before: String # elements before cursor. | |||
first: Int # first N elements from list | |||
last: Int # last N elements from list | |||
): UserConnection! | |||
} | |||
type User { | |||
id: Int! | |||
name: String! | |||
} | |||
type UserConnection { | |||
edges: [UserEdge] | |||
nodes: [User] | |||
pageInfo: PageInfo! | |||
} | |||
type UserEdge { | |||
cursor: String! | |||
node: User | |||
} | |||
</syntaxhighlight> | |||
Sample query | |||
<syntaxhighlight lang=""> | |||
query { | |||
users(first: 2) { | |||
edges { | |||
cursor | |||
nodes { | |||
id | |||
name | |||
} | |||
} | |||
} | |||
} | |||
</syntaxhighlight> | |||
See [[graphql-ruby connections]] for an example implementation of this pattern. | See [[graphql-ruby connections]] for an example implementation of this pattern. | ||
</blockquote><!-- Edges/Connections --> | </blockquote><!-- Edges/Connections --> |
Revision as of 21:06, 6 September 2021
Interfaces
In graphql, an interface is a group of fields that multiple objects may use.
A type that implements that interface must define all fields required by the interface.
Note you can implement multiple interfaces.# schema interface Animal { species: String! age: Int! } type Duck implements Animal { species: String! age: Int! quack: String! }You can return an
Animal
(which really returns any of the subtypes).
When referring to fields not part of the return type, you need to specify the object it belongs to.{ animal { species age ... on Duck { quack } } }
Edges/Connections
Connections and Edges are not a part of graphql syntax,
they are a schema design-pattern that is sometimes implemented in API libraries.
- Edges are connections between two nodes. (ex: Task and assigned User)
- Connections contain a list of edges, and a cursor to iterate through them
Sample Schema extract
type QueryRoot { users( after: String # elements after cursor. before: String # elements before cursor. first: Int # first N elements from list last: Int # last N elements from list ): UserConnection! } type User { id: Int! name: String! } type UserConnection { edges: [UserEdge] nodes: [User] pageInfo: PageInfo! } type UserEdge { cursor: String! node: User }Sample query
query { users(first: 2) { edges { cursor nodes { id name } } } }See graphql-ruby connections for an example implementation of this pattern.