Master GraphQL fundamentals including schemas, queries, mutations, subscriptions, and best practices for building flexible, type-safe APIs.
Master GraphQL fundamentals and best practices for building flexible, type-safe APIs with powerful query capabilities.
Guides you through implementing GraphQL APIs from scratch or improving existing ones. Covers schema design, query optimization, mutation patterns, real-time subscriptions, authorization, pagination, and performance best practices.
When the user requests help with GraphQL:
1. **Assess Context**
- Identify if this is a new GraphQL project or enhancing an existing API
- Determine the backend framework (Node.js/GraphQL.js, Apollo Server, Yoga, etc.)
- Check for existing schema files (`.graphql`, `.gql`, or schema definitions in code)
2. **Schema Design**
- Start with type definitions that model the domain clearly
- Use object types, enums, interfaces, and unions appropriately
- Define root Query, Mutation, and Subscription types
- Apply nullable vs non-nullable fields thoughtfully
- Implement the Node interface pattern for global object identification
- Example:
```graphql
type User implements Node {
id: ID!
email: String!
posts(first: Int, after: String): PostConnection
}
type Post implements Node {
id: ID!
title: String!
author: User!
publishedAt: DateTime
}
```
3. **Query Implementation**
- Structure queries to request exactly the needed data
- Use arguments for filtering and pagination
- Implement fragments for reusable field sets
- Add connection-based pagination (edges/nodes pattern)
- Example resolver:
```javascript
const resolvers = {
Query: {
user: async (_, { id }, context) => {
return context.db.users.findById(id);
}
},
User: {
posts: async (user, { first, after }, context) => {
return context.loaders.posts.loadMany(user.id, { first, after });
}
}
};
```
4. **Mutations**
- Design input types for clear mutation contracts
- Return meaningful payloads (updated object + metadata)
- Handle errors gracefully in the response
- Example:
```graphql
type Mutation {
createPost(input: CreatePostInput!): CreatePostPayload!
}
input CreatePostInput {
title: String!
content: String!
authorId: ID!
}
type CreatePostPayload {
post: Post
errors: [UserError!]!
}
```
5. **Subscriptions**
- Implement real-time updates for appropriate use cases
- Use pub/sub patterns efficiently
- Consider performance implications at scale
- Example:
```graphql
type Subscription {
postPublished: Post!
}
```
6. **Authorization**
- Apply field-level authorization in resolvers
- Use context to pass authenticated user
- Implement directive-based auth patterns where appropriate
- Never expose unauthorized data
7. **Performance Optimization**
- Implement DataLoader to prevent N+1 queries
- Add query complexity analysis
- Set depth and rate limits
- Enable response caching where appropriate
- Use persistent queries for production
- Example DataLoader:
```javascript
const userLoader = new DataLoader(async (ids) => {
const users = await db.users.findMany({ where: { id: { in: ids } } });
return ids.map(id => users.find(u => u.id === id));
});
```
8. **Validation & Error Handling**
- Leverage GraphQL's built-in validation
- Return structured errors with extensions
- Implement custom validation rules if needed
- Use error codes for client handling
9. **Introspection**
- Keep introspection enabled in development
- Add schema descriptions and deprecation notices
- Consider disabling introspection in production for security
10. **Best Practices Checklist**
- [ ] Schema uses clear, consistent naming conventions
- [ ] Pagination implemented with connections pattern
- [ ] Global IDs follow Node interface
- [ ] Authorization applied at field level
- [ ] DataLoader prevents N+1 queries
- [ ] Query complexity limits configured
- [ ] File uploads handled as mutations
- [ ] Errors return meaningful codes and messages
- [ ] Schema documented with descriptions
- [ ] Subscription scalability considered
**User Request:** "Add a GraphQL API to my Express app with user authentication"
**AI Response:**
1. Install dependencies: `npm install graphql @apollo/server @apollo/server-plugin-landing-page-local-default dataloader`
2. Create schema file `schema.graphql` with User type, Query, and Mutation roots
3. Implement resolvers with authentication context checking
4. Set up Apollo Server with Express middleware
5. Add DataLoader for efficient user queries
6. Configure authorization directive for protected fields
7. Test with Apollo Studio
**User Request:** "Optimize this slow GraphQL query that fetches posts with authors"
**AI Response:**
1. Analyze resolver chain—identify N+1 problem in `Post.author` resolver
2. Implement DataLoader for batching author queries
3. Add database indexes on foreign keys
4. Enable query complexity analysis to prevent abuse
5. Add `@cacheControl` hints for Apollo Client
6. Test performance with large datasets
Leave a review
No reviews yet. Be the first to review this skill!
# Download SKILL.md from killerskills.ai/api/skills/graphql-api-design/raw