TExcelTAD
Home › GraphQL › Resolvers & Code-First Schemas

Resolvers & Code-First Schemas

There are two ways to build a schema in graphql-js, and you'll see both in real projects:

Style You write Resolvers live
SDL-first SDL text with buildSchema (or makeExecutableSchema in graphql-tools) in a separate object (root value or resolver map)
Code-first new GraphQLObjectType({ … }) objects next to each field, as resolve

So far we used buildSchema with a root value. That's great for learning, but it has limits: only top-level fields get resolvers directly, and nested types need methods on the data objects. This lesson shows the alternatives.

Code-first with GraphQLObjectType

Each type is a JavaScript object; each field declares its type, optional args and a resolve(parent, args, context, info) function:

js · try it yourself
import {
  graphql, GraphQLSchema, GraphQLObjectType, GraphQLString, GraphQLInt,
  GraphQLList, GraphQLNonNull, GraphQLID, printSchema,
} from 'graphql';

const db = {
  teams: [{ id: 't1', name: 'Falcons' }, { id: 't2', name: 'Otters' }],
  players: [
    { id: 'p1', name: 'Ines', goals: 12, teamId: 't1' },
    { id: 'p2', name: 'Kofi', goals: 7, teamId: 't1' },
    { id: 'p3', name: 'Mara', goals: 9, teamId: 't2' },
  ],
};

const Player = new GraphQLObjectType({
  name: 'Player',
  fields: () => ({
    id: { type: new GraphQLNonNull(GraphQLID) },
    name: { type: new GraphQLNonNull(GraphQLString) },
    goals: { type: GraphQLInt },
    team: { type: Team, resolve: (player) => db.teams.find((t) => t.id === player.teamId) },
  }),
});

const Team = new GraphQLObjectType({
  name: 'Team',
  fields: () => ({
    id: { type: new GraphQLNonNull(GraphQLID) },
    name: { type: GraphQLString },
    players: {
      type: new GraphQLList(Player),
      resolve: (team) => db.players.filter((p) => p.teamId === team.id),
    },
    totalGoals: {
      type: GraphQLInt,
      resolve: (team) =>
        db.players.filter((p) => p.teamId === team.id).reduce((sum, p) => sum + p.goals, 0),
    },
  }),
});

const Query = new GraphQLObjectType({
  name: 'Query',
  fields: {
    teams: { type: new GraphQLList(Team), resolve: () => db.teams },
    player: {
      type: Player,
      args: { id: { type: new GraphQLNonNull(GraphQLID) } },
      resolve: (_parent, { id }) => db.players.find((p) => p.id === id),
    },
  },
});

const schema = new GraphQLSchema({ query: Query });

const result = await graphql({
  schema,
  source: '{ teams { name totalGoals players { name } } player(id: "p3") { name team { name } } }',
});
console.log(JSON.stringify(result.data, null, 2));
console.log(printSchema(schema));
{
  "teams": [
    {
      "name": "Falcons",
      "totalGoals": 19,
      "players": [
        {
          "name": "Ines"
        },
        {
          "name": "Kofi"
        }
      ]
    },
    {
      "name": "Otters",
      "totalGoals": 9,
      "players": [
        {
          "name": "Mara"
        }
      ]
    }
  ],
  "player": {
    "name": "Mara",
    "team": {
      "name": "Otters"
    }
  }
}
type Query {
  teams: [Team]
  player(id: ID!): Player
}

type Team {
  id: ID!
  name: String
  players: [Player]
  totalGoals: Int
}

type Player {
  id: ID!
  name: String!
  goals: Int
  team: Team
}

Two details worth noticing:

  • fields: () => ({ … }) is a thunk (a function returning the fields). It lets Player refer to Team before Team is defined, which you need for any cycle.
  • The database rows store teamId, not a team object. The team resolver turns the id into the related object, which keeps your data and your schema decoupled.

SDL-first with a resolver map

Many teams prefer writing SDL and supplying resolvers as a map { TypeName: { fieldName: fn } }. That's what makeExecutableSchema from @graphql-tools/schema (used by Apollo Server, GraphQL Yoga, …) does:

js
import { makeExecutableSchema } from '@graphql-tools/schema';

const schema = makeExecutableSchema({
  typeDefs: `type Team { name: String, players: [Player] } ...`,
  resolvers: {
    Query: { teams: () => db.teams },
    Team: { players: (team) => db.players.filter((p) => p.teamId === team.id) },
  },
});

It's only a few lines to do the same with plain graphql-js: build the schema, then copy each function onto the matching field's resolve:

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

function makeExecutableSchema({ typeDefs, resolvers }) {
  const schema = buildSchema(typeDefs);
  for (const [typeName, fieldResolvers] of Object.entries(resolvers)) {
    const fields = schema.getType(typeName).getFields();
    for (const [fieldName, resolve] of Object.entries(fieldResolvers)) {
      fields[fieldName].resolve = resolve;
    }
  }
  return schema;
}

const db = {
  teams: [{ id: 't1', name: 'Falcons' }, { id: 't2', name: 'Otters' }],
  players: [
    { name: 'Ines', teamId: 't1' },
    { name: 'Kofi', teamId: 't1' },
    { name: 'Mara', teamId: 't2' },
  ],
};

const schema = makeExecutableSchema({
  typeDefs: `
    type Team { name: String!, players: [Player!]!, size: Int! }
    type Player { name: String!, team: Team! }
    type Query { teams: [Team!]! }
  `,
  resolvers: {
    Query: {
      teams: () => db.teams,
    },
    Team: {
      players: (team) => db.players.filter((p) => p.teamId === team.id),
      size: (team) => db.players.filter((p) => p.teamId === team.id).length,
    },
    Player: {
      team: (player) => db.teams.find((t) => t.id === player.teamId),
    },
  },
});

const result = await graphql({ schema, source: '{ teams { name size players { name team { name } } } }' });
console.log(JSON.stringify(result.data));
{"teams":[{"name":"Falcons","size":2,"players":[{"name":"Ines","team":{"name":"Falcons"}},{"name":"Kofi","team":{"name":"Falcons"}}]},{"name":"Otters","size":1,"players":[{"name":"Mara","team":{"name":"Otters"}}]}]}

Team.name has no resolver in the map, so the default resolver reads team.name from the row. You only write resolvers for fields that need logic.

Which style should you use?

  • SDL-first: the schema is easy to read and review, and non-JS teams can share it. Risk: SDL and resolvers can drift apart (a typo in a resolver map key is silently ignored unless your tooling checks it).
  • Code-first: types and resolvers live together, and TypeScript tools (Pothos, Nexus, TypeGraphQL) can infer types end to end. The SDL is generated with printSchema.

Both produce the same GraphQLSchema object, and clients can't tell the difference.

Tip: Keep resolvers thin. A resolver should translate between GraphQL and your business logic (orderService.cancel(id, user)), not contain the business logic itself. This makes the logic reusable and much easier to test.

Test yourself

Why is fields often written as a function () => ({ … })?

  1. For performance
  2. So types can reference each other before they're defined
  3. It's required for scalars
  4. To make fields private

In a resolver map, what happens to a field that has no resolver?

  1. It always returns null
  2. The default resolver reads the property with the same name from the parent
  3. Schema building fails
  4. It returns the field's type

What is the key difference between SDL-first and code-first?

  1. Only code-first supports resolvers
  2. How the schema is authored; both yield the same GraphQLSchema
  3. SDL-first can't have mutations
  4. Code-first doesn't validate queries