Chapter 10: GraphQL Introduction
Chapter 10 of 14
Chapter 10: GraphQL Introduction
10.1 GraphQL Basics
GraphQL is a query language for APIs that allows clients to request exactly the data they need.
// GraphQL schema
const { buildSchema } = require('graphql');
const schema = buildSchema(`
type User {
id: ID!
name: String!
email: String!
posts: [Post!]!
}
type Post {
id: ID!
title: String!
content: String!
author: User!
}
type Query {
user(id: ID!): User
users: [User!]!
}
type Mutation {
createUser(name: String!, email: String!): User!
}
`);
10.2 GraphQL Queries
// Client query
query {
user(id: "1") {
name
email
posts {
title
content
}
}
}
// Resolver implementation
const root = {
user: async ({ id }) => {
return await User.findById(id);
},
users: async () => {
return await User.findAll();
}
};
10.3 GraphQL vs REST
GraphQL Advantages:
- Fetch only needed data
- Single endpoint
- Strong typing
- Real-time subscriptions
REST Advantages:
- Simpler for simple use cases
- Better caching
- More mature ecosystem
- Easier to understand