Graphql

From williamzujkowski/standards · View interactive version

Graphql is an AI agent skill from the GitHub repository williamzujkowski/standards. Comprehensive GraphQL API design with Apollo Server, GraphQL Yoga, and Federation v2

How to use this skill

Skill file

GraphQL API Design Skill

Level 1: Quick Reference (~800 tokens)

GraphQL vs REST: When to Use GraphQL

Use GraphQL When:

Use REST When:

Schema Design Principles

Core Concepts:

  1. Type System: Strongly typed schema defines API contract
  2. Query: Read operations (like GET)
  3. Mutation: Write operations (like POST/PUT/DELETE)
  4. Subscription: Real-time data streams over WebSocket
  5. Resolver: Function that returns data for a field

Design Rules:

Essential Checklist

Schema Design
Resolvers & Performance
Authorization & Security
Federation (Microservices)
Error Handling
Testing

Quick Wins

Immediate Optimizations:

  1. DataLoader: Reduce N+1 queries by 90%+

```typescript

const userLoader = new DataLoader(async (userIds) => {

const users = await db.users.findMany({ where: { id: { in: userIds } } });

return userIds.map(id => users.find(u => u.id === id));

});

```

  1. Query Complexity: Prevent expensive queries

```typescript

const server = new ApolloServer({

schema,

plugins: [createComplexityPlugin({ maximumComplexity: 1000 })]

});

```

  1. Response Caching: Cache at resolver or HTTP level

```typescript

@cacheControl(maxAge: 3600)

type User { id: ID! name: String! }

```

  1. Subscription Filtering: Reduce unnecessary events

```typescript

subscribe: {

messageAdded: {

subscribe: withFilter(

() => pubsub.asyncIterator('MESSAGE_ADDED'),

(payload, variables) => payload.channelId === variables.channelId

)

}

}

```


Level 2:

📚 Full Examples: See REFERENCE.md for complete code samples, detailed configurations, and production-ready implementations.

Implementation Guide (~4500 tokens)

1. GraphQL Schema Design Best Practices

Type System Fundamentals

Object Types: Primary building blocks

See REFERENCE.md for complete implementation.

Input Types: For mutations and complex arguments

See REFERENCE.md for complete implementation.

Enums: For fixed sets of values

See REFERENCE.md for complete implementation.

Interfaces: For polymorphic types

See REFERENCE.md for complete implementation.

Unions: For heterogeneous result types

union SearchResult = User | Post | Comment

type Query {
  search(query: String!): [SearchResult!]!
}

Custom Scalars: For domain-specific types

scalar DateTime
scalar Email
scalar URL
scalar JSON
scalar PositiveInt
Query Design Patterns

Root Query Type

See REFERENCE.md for complete implementation.

Cursor-Based Pagination (Relay spec)

See REFERENCE.md for complete implementation.

Mutation Design Patterns

Input/Payload Pattern: Consistent structure

See REFERENCE.md for complete implementation.

Optimistic Response Support

type UpdatePostPayload {
  post: Post
  clientMutationId: String  # Client-provided ID for tracking
  errors: [ValidationError!]
}
Subscription Design

Real-Time Events

See REFERENCE.md for complete implementation.

2. Resolvers and DataLoaders

Resolver Structure

Basic Resolvers

See REFERENCE.md for complete implementation.

Resolver Best Practices

  1. Keep resolvers thin - delegate to data sources
  2. Use TypeScript for type safety
  3. Handle errors gracefully
  4. Return consistent payload structures
  5. Log resolver execution for debugging
DataLoader Implementation

Solving the N+1 Problem

Without DataLoader (N+1 queries):

// For 10 posts, this executes 11 queries!
query {
  posts {           # 1 query
    id
    title
    author {        # 10 queries (one per post)
      name
    }
  }
}

With DataLoader (2 queries):

See REFERENCE.md for complete implementation.

DataLoader in Context

See REFERENCE.md for complete implementation.

Using DataLoader in Resolvers

See REFERENCE.md for complete implementation.

Advanced DataLoader Patterns

See REFERENCE.md for complete implementation.

3. Apollo Federation v2

Subgraph Design

Users Subgraph

See REFERENCE.md for complete implementation.

Posts Subgraph

See REFERENCE.md for complete implementation.

Reference Resolvers

See REFERENCE.md for complete implementation.

Gateway Configuration

Apollo Gateway Setup

See REFERENCE.md for complete implementation.

Managed Federation (Apollo Studio)

See REFERENCE.md for complete implementation.

4. Authentication and Authorization

Context-Based Authentication

JWT Token Verification

See REFERENCE.md for complete implementation.

Resolver-Level Authorization

See REFERENCE.md for complete implementation.

Directive-Based Authorization

Schema Directives

See REFERENCE.md for complete implementation.

Directive Implementation

See REFERENCE.md for complete implementation.

5. Subscriptions for Real-Time Data

WebSocket Transport

Apollo Server Subscriptions

See REFERENCE.md for complete implementation.

PubSub Implementation

See REFERENCE.md for complete implementation.

Subscription Resolvers

See REFERENCE.md for complete implementation.

6. Performance Optimization

Caching Strategies

Apollo Cache Control

type Query {
  user(id: ID!): User @cacheControl(maxAge: 3600)
  posts: [Post!]! @cacheControl(maxAge: 300)
}

See REFERENCE.md for complete implementation.

Redis Response Caching

See REFERENCE.md for complete implementation.

Query Complexity Analysis

Cost-Based Limiting

See REFERENCE.md for complete implementation.

Pagination Best Practices

Cursor-Based Pagination

See REFERENCE.md for complete implementation.

7. Error Handling and Validation

Structured Error Responses

Custom Error Classes

See REFERENCE.md for complete implementation.

Error Formatting

See REFERENCE.md for complete implementation.

8. Testing GraphQL APIs

Unit Testing Resolvers

Resolver Tests

See REFERENCE.md for complete implementation.

Integration Testing

GraphQL Server Tests

See REFERENCE.md for complete implementation.

9. Production Deployment

Health Checks

Readiness and Liveness

See REFERENCE.md for complete implementation.

Monitoring and Observability

Apollo Studio Integration

See REFERENCE.md for complete implementation.

Custom Metrics

See REFERENCE.md for complete implementation.

Examples

Basic Usage

See REFERENCE.md for complete implementation.

Advanced Usage

// TODO: Add advanced example for graphql
// This example shows production-ready patterns

Integration Example

// TODO: Add integration example showing how graphql
// works with other systems and services

See examples/graphql/ for complete working examples.

Integration Points

This skill integrates with:

Upstream Dependencies

Downstream Consumers

Related Skills

Common Integration Patterns

  1. Development Workflow: How this skill fits into daily development
  2. Production Deployment: Integration with production systems
  3. Monitoring & Alerting: Observability integration points

Common Pitfalls

Pitfall 1: Insufficient Testing

Problem: Not testing edge cases and error conditions leads to production bugs

Solution: Implement comprehensive test coverage including:

Prevention: Enforce minimum code coverage (80%+) in CI/CD pipeline

Pitfall 2: Hardcoded Configuration

Problem: Hardcoding values makes applications inflexible and environment-dependent

Solution: Use environment variables and configuration management:

Prevention: Use tools like dotenv, config validators, and secret scanners

Pitfall 3: Ignoring Security Best Practices

Problem: Security vulnerabilities from not following established security patterns

Solution: Follow security guidelines:

Prevention: Use security linters, SAST tools, and regular dependency updates

Best Practices:


Level 3: Deep Dive Resources

Official Documentation

Tools & Libraries

Books & Courses

Bundled Resources

See templates/ and config/ directories for production-ready implementations:

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.