As modern web applications grow in complexity, RESTful APIs often suffer from over-fetching unnecessary data or under-fetching, which forces multiple sequential round-trips to assemble a single screen. GraphQL eliminates these pain points by allowing client applications to request precisely the data fields they need through a unified, strongly typed query language.
Core Concepts: Schema, Queries, and Resolvers
A GraphQL service revolves around a clearly defined Schema Definition Language (SDL) that serves as a strict contract between front-end consumers and backend databases. Resolvers are functions responsible for fetching and transforming data for each field defined in your schema.
Setting Up Apollo Server with TypeScript
Apollo Server provides an industry-standard, production-ready foundation with built-in support for caching, performance telemetry, and express integration. Here is a clean setup featuring books and author models:
import { ApolloServer } from '@apollo/server';
import { startStandaloneServer } from '@apollo/server/standalone';
const typeDefs = `#graphql
type Author {
id: ID!
name: String!
books: [Book!]!
}
type Book {
id: ID!
title: String!
publishedYear: Int
author: Author!
}
type Query {
books: [Book!]!
book(id: ID!): Book
authors: [Author!]!
}
input CreateBookInput {
title: String!
authorId: ID!
publishedYear: Int
}
type Mutation {
createBook(input: CreateBookInput!): Book!
}
`;
const authorsData = [
{ id: '1', name: 'Ada Lovelace' },
{ id: '2', name: 'Alan Turing' }
];
const booksData = [
{ id: '101', title: 'Algorithms and Analysis', publishedYear: 1843, authorId: '1' },
{ id: '102', title: 'Computing Machinery and Intelligence', publishedYear: 1950, authorId: '2' }
];
const resolvers = {
Query: {
books: () => booksData,
book: (_, { id }) => booksData.find((b) => b.id === id),
authors: () => authorsData,
},
Book: {
author: (parent) => authorsData.find((a) => a.id === parent.authorId),
},
Author: {
books: (parent) => booksData.filter((b) => b.authorId === parent.id),
},
Mutation: {
createBook: (_, { input }) => {
const newBook = { id: String(Date.now()), ...input };
booksData.push(newBook);
return newBook;
}
}
};
const server = new ApolloServer({ typeDefs, resolvers });
const { url } = await startStandaloneServer(server, { listen: { port: 4000 } });
console.log(`🚀 Apollo GraphQL Server ready at: ${url}`);Solving the N+1 Query Problem with DataLoader
When resolving nested relationships, such as fetching all authors and their associated books, naive resolvers execute an individual SQL query for each author. Integrating Facebook’s DataLoader library batches individual requests into a single grouped database query, keeping database overhead predictable and scalable under high load.


Leave a Reply