GraphQL Expert
Expert guidance for GraphQL API development, schema design, resolvers, subscriptions, and best practices for building type-safe, efficient APIs.
Core Concepts
Schema Design
- Type system and schema definition language (SDL)
- Object types, interfaces, unions, and enums
- Input types and custom scalars
- Schema stitching and federation
- Modular schema organization
Resolvers
- Resolver functions and data sources
- Context and info arguments
- Field-level resolvers
- Resolver chains and data loaders
- Error handling in resolvers
Queries and Mutations
- Query design and naming conventions
- Mutation patterns and best practices
- Input validation and sanitization
- Pagination strategies (cursor-based, offset)
- Filtering and sorting
Subscriptions
- Real-time updates with WebSocket
- Subscription resolvers
- PubSub patterns
- Subscription filtering
- Connection management
Performance
- N+1 query problem and DataLoader
- Query complexity analysis
- Depth limiting and query cost
- Caching strategies (field-level, full response)
- Batching and deduplication
GraphQL Federation
Federated Schema
// Users service
import { buildSubgraphSchema } from '@apollo/subgraph';
const typeDefs = gql`
extend schema @link(url: "https://specs.apollo.dev/federation/v2.3")
type User @key(fields: "id") {
id: ID!
email: String!
name: String!
}
type Query {
user(id: ID!): User
users: [User!]!
}
`;
const resolvers = {
User: {
__resolveReference: async (reference, { dataSources }) => {
return dataSources.userAPI.getUserById(reference.id);
},
},
Query: {
user: (_, { id }, { dataSources }) => dataSources.userAPI.getUserById(id),
users: (_, __, { dataSources }) => dataSources.userAPI.getUsers(),
},
};
// Posts service
const typeDefs = gql`
extend schema @link(url: "https://specs.apollo.dev/federation/v2.3")
type Post @key(fields: "id") {
id: ID!
title: String!
content: String!
author: User!
}
extend type User @key(fields: "id") {
id: ID! @external
posts: [Post!]!
}
type Query {
post(id: ID!): Post
posts: [Post!]!
}
`;
const resolvers = {
Post: {
author: (post) => ({ __typename: 'User', id: post.authorId }),
},
User: {
posts: (user, _, { dataSources }) =>
dataSources.postAPI.getPostsByAuthorId(user.id),
},
};
// Gateway
import { ApolloGateway, IntrospectAndCompose } from '@apollo/gateway';
const gateway = new ApolloGateway({
supergraphSdl: new IntrospectAndCompose({
subgraphs: [
{ name: 'users', url: 'http://localhost:4001/graphql' },
{ name: 'posts', url: 'http://localhost:4002/graphql' },
],
}),
});
const server = new ApolloServer({ gateway });
Anti-Patterns to Avoid
❌ Exposing internal IDs: Use opaque IDs or UUIDs
❌ Overly nested queries: Limit query depth
❌ No pagination: Always paginate lists
❌ Resolving in mutations: Keep mutations focused
❌ Exposing database schema directly: Design API-first
❌ No DataLoader: Leads to N+1 queries
❌ Generic error messages: Provide actionable errors
❌ No versioning strategy: Plan for schema evolution
Testing
import { ApolloServer } from '@apollo/server';
import { describe, it, expect } from 'vitest';
describe('GraphQL Server', () => {
it('should fetch user by id', async () => {
const server = new ApolloServer({ typeDefs, resolvers });
const response = await server.executeOperation({
query: `
query GetUser($id: ID!) {
user(id: $id) {
id
name
email
}
}
`,
variables: { id: '1' },
});
expect(response.body.kind).toBe('single');
expect(response.body.singleResult.data?.user).toEqual({
id: '1',
name: 'Alice',
email: 'alice@example.com',
});
});
it('should create post', async () => {
const response = await server.executeOperation({
query: `
mutation CreatePost($input: CreatePostInput!) {
createPost(input: $input) {
id
title
}
}
`,
variables: {
input: {
title: 'Test Post',
content: 'Content',
},
},
});
expect(response.body.singleResult.data?.createPost).toHaveProperty('id');
});
});
Reference Documentation
Detailed material lives alongside this skill and is read on demand:
- Common Patterns — Relay Cursor Pagination, File Upload
- Best Practices — Schema Design, Performance Optimization, Security
- Modern GraphQL Development — Apollo Server 4, DataLoader for N+1 Prevention, GraphQL Codegen, Error Handling, Authentication & Authorization, Subscriptions with WebSocket, GraphQL Client (Apollo Client), Query Complexity & Depth Limiting
Resources
1---
2name: graphql-expert
3version: 1.1.0
4description: >-
5 Expert-level GraphQL API development with schema design, resolvers, and subscriptions.
6 Use when the user mentions API, apollo, schema, resolvers, subscriptions, or relay, or
7 when the task involves Schema Design, Queries and Mutations, Apollo Server 4, or
8 DataLoader for N+1 Prevention.
9category: api
10tags: [graphql, api, apollo, schema, resolvers, subscriptions, relay]
11allowed-tools:
12 - Read
13 - Write
14 - Edit
15 - Bash(node:*, npm:*, npx:*)
16metadata:
17 source: https://skillmd.com/skills/personamanagmentlayer/graphql-expert
18---
19
20# GraphQL Expert
21
22Expert guidance for GraphQL API development, schema design, resolvers, subscriptions, and best practices for building type-safe, efficient APIs.
23
24## Core Concepts
25
26### Schema Design
27
28- Type system and schema definition language (SDL)
29- Object types, interfaces, unions, and enums
30- Input types and custom scalars
31- Schema stitching and federation
32- Modular schema organization
33
34### Resolvers
35
36- Resolver functions and data sources
37- Context and info arguments
38- Field-level resolvers
39- Resolver chains and data loaders
40- Error handling in resolvers
41
42### Queries and Mutations
43
44- Query design and naming conventions
45- Mutation patterns and best practices
46- Input validation and sanitization
47- Pagination strategies (cursor-based, offset)
48- Filtering and sorting
49
50### Subscriptions
51
52- Real-time updates with WebSocket
53- Subscription resolvers
54- PubSub patterns
55- Subscription filtering
56- Connection management
57
58### Performance
59
60- N+1 query problem and DataLoader
61- Query complexity analysis
62- Depth limiting and query cost
63- Caching strategies (field-level, full response)
64- Batching and deduplication
65
66## GraphQL Federation
67
68### Federated Schema
69
70```typescript
71// Users service
72import { buildSubgraphSchema } from '@apollo/subgraph';
73
74const typeDefs = gql`
75 extend schema @link(url: "https://specs.apollo.dev/federation/v2.3")
76
77 type User @key(fields: "id") {
78 id: ID!
79 email: String!
80 name: String!
81 }
82
83 type Query {
84 user(id: ID!): User
85 users: [User!]!
86 }
87`;
88
89const resolvers = {
90 User: {
91 __resolveReference: async (reference, { dataSources }) => {
92 return dataSources.userAPI.getUserById(reference.id);
93 },
94 },
95 Query: {
96 user: (_, { id }, { dataSources }) => dataSources.userAPI.getUserById(id),
97 users: (_, __, { dataSources }) => dataSources.userAPI.getUsers(),
98 },
99};
100
101// Posts service
102const typeDefs = gql`
103 extend schema @link(url: "https://specs.apollo.dev/federation/v2.3")
104
105 type Post @key(fields: "id") {
106 id: ID!
107 title: String!
108 content: String!
109 author: User!
110 }
111
112 extend type User @key(fields: "id") {
113 id: ID! @external
114 posts: [Post!]!
115 }
116
117 type Query {
118 post(id: ID!): Post
119 posts: [Post!]!
120 }
121`;
122
123const resolvers = {
124 Post: {
125 author: (post) => ({ __typename: 'User', id: post.authorId }),
126 },
127 User: {
128 posts: (user, _, { dataSources }) =>
129 dataSources.postAPI.getPostsByAuthorId(user.id),
130 },
131};
132
133// Gateway
134import { ApolloGateway, IntrospectAndCompose } from '@apollo/gateway';
135
136const gateway = new ApolloGateway({
137 supergraphSdl: new IntrospectAndCompose({
138 subgraphs: [
139 { name: 'users', url: 'http://localhost:4001/graphql' },
140 { name: 'posts', url: 'http://localhost:4002/graphql' },
141 ],
142 }),
143});
144
145const server = new ApolloServer({ gateway });
146```
147
148## Anti-Patterns to Avoid
149
150❌ **Exposing internal IDs**: Use opaque IDs or UUIDs
151❌ **Overly nested queries**: Limit query depth
152❌ **No pagination**: Always paginate lists
153❌ **Resolving in mutations**: Keep mutations focused
154❌ **Exposing database schema directly**: Design API-first
155❌ **No DataLoader**: Leads to N+1 queries
156❌ **Generic error messages**: Provide actionable errors
157❌ **No versioning strategy**: Plan for schema evolution
158
159## Testing
160
161```typescript
162import { ApolloServer } from '@apollo/server';
163import { describe, it, expect } from 'vitest';
164
165describe('GraphQL Server', () => {
166 it('should fetch user by id', async () => {
167 const server = new ApolloServer({ typeDefs, resolvers });
168
169 const response = await server.executeOperation({
170 query: `
171 query GetUser($id: ID!) {
172 user(id: $id) {
173 id
174 name
175 email
176 }
177 }
178 `,
179 variables: { id: '1' },
180 });
181
182 expect(response.body.kind).toBe('single');
183 expect(response.body.singleResult.data?.user).toEqual({
184 id: '1',
185 name: 'Alice',
186 email: 'alice@example.com',
187 });
188 });
189
190 it('should create post', async () => {
191 const response = await server.executeOperation({
192 query: `
193 mutation CreatePost($input: CreatePostInput!) {
194 createPost(input: $input) {
195 id
196 title
197 }
198 }
199 `,
200 variables: {
201 input: {
202 title: 'Test Post',
203 content: 'Content',
204 },
205 },
206 });
207
208 expect(response.body.singleResult.data?.createPost).toHaveProperty('id');
209 });
210});
211```
212
213## Reference Documentation
214
215Detailed material lives alongside this skill and is read on demand:
216
217- [Common Patterns](references/PATTERNS.md) — Relay Cursor Pagination, File Upload
218- [Best Practices](references/BEST_PRACTICES.md) — Schema Design, Performance Optimization, Security
219- [Modern GraphQL Development](references/MODERN_GRAPHQL_DEVELOPMENT.md) — Apollo Server 4, DataLoader for N+1 Prevention, GraphQL Codegen, Error Handling, Authentication & Authorization, Subscriptions with WebSocket, GraphQL Client (Apollo Client), Query Complexity & Depth Limiting
220
221## Resources
222
223- Apollo Server: https://www.apollographql.com/docs/apollo-server/
224- GraphQL Spec: https://spec.graphql.org/
225- DataLoader: https://github.com/graphql/dataloader
226- GraphQL Code Generator: https://the-guild.dev/graphql/codegen
227- GraphQL Tools: https://the-guild.dev/graphql/tools