Back to results for “GraphQL”
Node.js › GraphQL

How would you set up a basic GraphQL server in Node.js using Apollo Server, defining a schema and resolvers?

Intermediate

Answer

Apollo Server requires a GraphQL schema (defined using the Schema Definition Language, describing available types, queries, and mutations) and a corresponding set of resolver functions that implement how each field in the schema is actually populated -- for a query field, the resolver typically fetches data from a database or another service; the resolver's return value must match the type declared in the schema.
const { ApolloServer, gql } = require('apollo-server-express');

const typeDefs = gql`
  type User { id: ID!, name: String!, email: String! }
  type Query { user(id: ID!): User }
`;

const resolvers = {
  Query: { user: async (_, { id }) => db.users.findById(id) },
};

const server = new ApolloServer({ typeDefs, resolvers });
await server.start();
server.applyMiddleware({ app });
Real-world example A team building a new API defines their User type and a 'user(id: ID!): User' query in their schema, then implements a resolver that fetches the corresponding user record from their database, giving GraphQL clients a strongly-typed way to query for user data.

Common follow-ups: How does a resolver for a nested field (like a User's list of orders) differ from a top-level Query resolver?;What happens if a resolver's return value doesn't match the type declared in the schema?