Graphql relationships

From wikinotes

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

schema {
  query: QueryRoot
}

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 more examples of an implementation of this pattern.