Graphql relationships: Difference between revisions

From wikinotes
Line 35: Line 35:
= Edges/Connections =
= Edges/Connections =
<blockquote>
<blockquote>
Connections and Edges '''are not''' a part of graphql syntax,<br>
they are a schema design-pattern that is '''sometimes implemented in API libraries'''.
{{ TODO |
{{ TODO |
This is unconfirmed and unclear. redo }}
This is unconfirmed and unclear. redo }}

Revision as of 18:56, 4 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.

TODO:

This is unconfirmed and unclear. redo

See https://graphql.org/learn/pagination/#end-of-list-counts-and-connections

# NOTE: UNTESTED
type Class {
  subject: String
  students(              # a connection -- define supplemental query-params
    age: Int
  ) StudentConnection!
}


type StudentConnection {
  edges: [StudentEdge]
  nodes: [Student]
}


type StudentEdge {
  node: Student
}


type Student {
  firstname: String!
  lastname: String!
  age: Int!
}
# untested, probably wrong
query MathClassStudents {
  Class(subject: "Math") {
    students(first: 2, age: 25) {
      edges {
        Student
      }
    }
  }
}