MockForge GraphQL
GraphQL protocol support for MockForge with schema-based query execution.
This crate provides comprehensive GraphQL mocking capabilities, allowing you to define GraphQL schemas and automatically generate realistic resolvers. Perfect for frontend development, API testing, and GraphQL client development.
Features
- Schema-Based Mocking: Define GraphQL schemas and auto-generate resolvers
- Query & Mutation Support: Handle queries, mutations, and subscriptions
- Full Type System: Support for scalars, objects, interfaces, unions, enums
- Introspection: Built-in GraphQL introspection for tooling integration
- GraphQL Playground: Interactive web-based query interface
- Latency Simulation: Configurable response delays for realistic testing
- Error Injection: Simulate GraphQL errors and partial responses
- Tracing Integration: Distributed tracing support with OpenTelemetry
Quick Start
Basic GraphQL Server
use start;
async
Server with Custom Schema
use ;
use LatencyProfile;
async
GraphQL Schema Definition
Define your GraphQL schema using standard GraphQL SDL (Schema Definition Language):
type Query {
user(id: ID!): User
users(limit: Int = 10, offset: Int = 0): [User!]!
posts(userId: ID): [Post!]!
}
type Mutation {
createUser(input: CreateUserInput!): User!
updateUser(id: ID!, input: UpdateUserInput!): User!
deleteUser(id: ID!): Boolean!
}
type Subscription {
userCreated: User!
postAdded(userId: ID): Post!
}
type User {
id: ID!
name: String!
email: String!
avatar: String
posts: [Post!]!
createdAt: DateTime!
updatedAt: DateTime!
}
type Post {
id: ID!
title: String!
content: String!
author: User!
tags: [String!]!
published: Boolean!
createdAt: DateTime!
updatedAt: DateTime!
}
input CreateUserInput {
name: String!
email: String!
avatar: String
}
input UpdateUserInput {
name: String
email: String
avatar: String
}
scalar DateTime
enum UserRole {
ADMIN
MODERATOR
USER
}
Automatic Resolver Generation
MockForge GraphQL automatically generates resolvers with realistic data based on field names and types:
Query Examples
# Get single user
# Get users with pagination
Mutation Examples
# Create user
# Update user
GraphQL Playground
Access the interactive GraphQL Playground at http://localhost:4000/playground
for:
- Schema Exploration: Browse types, fields, and relationships
- Query Builder: Auto-complete with syntax highlighting
- Documentation: Inline field and type documentation
- History: Save and replay previous queries
- Response Viewer: Formatted JSON responses with error highlighting
Advanced Features
Latency Simulation
Simulate realistic network conditions:
use start_with_latency;
use LatencyProfile;
async
Custom Latency Profiles
use LatencyProfile;
// Fixed delay
let fixed_latency = with_fixed_delay; // 500ms
// Normal distribution
let normal_latency = with_normal_distribution; // mean 200ms, std dev 50ms
// Custom range
let range_latency = with_range; // 100-1000ms
Error Injection
Simulate GraphQL errors:
use GraphQLExecutor;
// Configure error injection
let executor = new
.with_error_rate // 10% error rate
.with_error_types;
Tracing Integration
Enable distributed tracing:
use ;
// Create spans for monitoring
let span = create_graphql_span;
// Execute query...
// Record success
record_graphql_success; // 150ms duration
Schema Registry
Manage multiple GraphQL schemas:
use GraphQLSchemaRegistry;
// Create registry
let registry = new;
// Register schemas
registry.register_schema.await?;
registry.register_schema.await?;
// Switch between versions
registry.set_active_schema.await?;
Integration with MockForge
MockForge GraphQL integrates seamlessly with the broader MockForge ecosystem:
- MockForge Core: Shared configuration and latency profiles
- MockForge CLI: Command-line GraphQL server management
- MockForge Data: Enhanced data generation for GraphQL responses
- MockForge Observability: Metrics and tracing integration
Configuration
Server Configuration
use GraphQLExecutor;
use LatencyProfile;
// Configure executor
let executor = new
.with_latency_profile
.with_max_query_depth
.with_max_query_complexity
.with_introspection_enabled
.with_playground_enabled;
Environment Variables
# Server configuration
# Latency simulation
# Error injection
Testing GraphQL APIs
Use MockForge GraphQL for comprehensive testing:
Unit Testing
use GraphQLExecutor;
async
Integration Testing
use Client;
async
Performance Considerations
- Schema Complexity: Large schemas may impact startup time
- Query Depth: Limit maximum query depth to prevent abuse
- Caching: Enable response caching for repeated queries
- Connection Pooling: Use connection pooling for database resolvers
Examples
Complete Server Setup
use ;
use ;
use LatencyProfile;
use SocketAddr;
use CorsLayer;
async
Custom Resolvers
use *;
use GraphQLSchema;
// Define custom resolvers
;
// Register custom resolvers
let schema = build
.data
.finish;
Troubleshooting
Common Issues
Schema validation errors:
- Check GraphQL syntax in your schema files
- Ensure all referenced types are defined
- Validate field names and type references
Query execution errors:
- Verify query syntax
- Check variable types match schema
- Ensure query depth doesn't exceed limits
Performance issues:
- Profile query execution times
- Check for N+1 query problems
- Optimize resolver implementations
Related Crates
mockforge-core
: Core mocking functionalitymockforge-data
: Synthetic data generationasync-graphql
: Underlying GraphQL implementation
License
Licensed under MIT OR Apache-2.0