TExcelTAD
Home › GraphQL › Interfaces

Interfaces

An interface is an abstract type that lists fields several object types have in common. A field that returns an interface can give back any type that implements it. Think of a media library: books, films and podcasts all have a title and a year, but each has its own extra fields.

Declaring an interface

graphql
interface Media {
  id: ID!
  title: String!
  year: Int
}

type Book implements Media {
  id: ID!
  title: String!
  year: Int
  pages: Int!
}

type Film implements Media {
  id: ID!
  title: String!
  year: Int
  minutes: Int!
}

Each implementing type must repeat all the interface's fields (with compatible types) and may add its own.

Querying an interface

On an interface field you can select the shared fields directly. To get type-specific fields, use inline fragments ... on Type. Because the engine must know which concrete type each object is, our data carries a __typename property; graphql-js's default type resolver reads it:

js · try it yourself
import { graphql, buildSchema } from 'graphql';

const schema = buildSchema(`
  interface Media { id: ID!, title: String!, year: Int }
  type Book implements Media { id: ID!, title: String!, year: Int, pages: Int! }
  type Film implements Media { id: ID!, title: String!, year: Int, minutes: Int! }
  type Query { library: [Media!]! }
`);

const library = [
  { __typename: 'Book', id: 'b1', title: 'Solaris', year: 1961, pages: 204 },
  { __typename: 'Film', id: 'f1', title: 'Stalker', year: 1979, minutes: 162 },
  { __typename: 'Book', id: 'b2', title: 'Roadside Picnic', year: 1972, pages: 145 },
];

const query = `{
  library {
    __typename
    title
    year
    ... on Book { pages }
    ... on Film { minutes }
  }
}`;

const result = await graphql({ schema, source: query, rootValue: { library } });
for (const item of result.data.library) console.log(JSON.stringify(item));
{"__typename":"Book","title":"Solaris","year":1961,"pages":204}
{"__typename":"Film","title":"Stalker","year":1979,"minutes":162}
{"__typename":"Book","title":"Roadside Picnic","year":1972,"pages":145}

Each item only got the fields of its own type. Asking for pages outside a fragment fails validation, because not every Media has pages.

Telling the engine the concrete type

Instead of storing __typename in your data, you can decide the type in code. In the code-first API an interface takes a resolveType function; with buildSchema you can attach it afterwards:

js · try it yourself
import { graphql, buildSchema } from 'graphql';

const schema = buildSchema(`
  interface Media { title: String! }
  type Book implements Media { title: String!, pages: Int! }
  type Film implements Media { title: String!, minutes: Int! }
  type Query { search(text: String!): [Media!]! }
`);

// Decide the type from the shape of the data.
schema.getType('Media').resolveType = (value) => ('pages' in value ? 'Book' : 'Film');

const items = [
  { title: 'Dune', pages: 412 },
  { title: 'Dune', minutes: 155 },
  { title: 'Arrival', minutes: 116 },
];

const result = await graphql({
  schema,
  rootValue: { search: ({ text }) => items.filter((i) => i.title.includes(text)) },
  source: `{
    search(text: "Dune") {
      kind: __typename
      title
      ... on Book { pages }
      ... on Film { minutes }
    }
  }`,
});
console.log(JSON.stringify(result.data.search));
[{"kind":"Book","title":"Dune","pages":412},{"kind":"Film","title":"Dune","minutes":155}]

Interfaces can implement interfaces

Since the 2020 spec, interfaces can build on each other. A common pattern is a Node interface for anything with a global id:

graphql
interface Node { id: ID! }

interface Media implements Node {
  id: ID!
  title: String!
}

type Podcast implements Media & Node {
  id: ID!
  title: String!
  episodes: Int!
}

A type that implements Media must also list Node. The & separates multiple interfaces.

Mistakes the schema validator catches

js · try it yourself
import { buildSchema, validateSchema } from 'graphql';

const schema = buildSchema(`
  interface Media { title: String!, year: Int }
  type Song implements Media { title: String }
  type Query { songs: [Song] }
`);

for (const error of validateSchema(schema)) console.log(error.message);
Interface field Media.title expects type String! but Song.title is type String.
Interface field Media.year expected but Song does not provide it.

buildSchema only parses the SDL; validateSchema runs the type-system rules (graphql-js also runs them automatically before the first query and refuses to execute). Here they caught two problems: Song dropped year and weakened title from String! to String.

Interface or union?

Use an interface when… Use a union (next lesson) when…
the types share meaningful fields the types have nothing in common
clients often select only the shared fields clients always branch by type
e.g. Media, Node, Account e.g. SearchResult = User | Repo | Issue

Test yourself

How do you select a field that exists only on Film from a [Media] list?

  1. Just write minutes
  2. ... on Film { minutes }
  3. Film.minutes
  4. @include(type: Film) minutes

What must a type that implements an interface do?

  1. Nothing; fields are inherited
  2. Declare every interface field with a compatible type
  3. Use the same name as the interface
  4. Have no extra fields

How does graphql-js's default type resolver find an object's concrete type?

  1. From the JavaScript class name
  2. From the __typename property (or isTypeOf checks)
  3. From the first field
  4. Randomly