Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
271 changes: 260 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,27 +8,38 @@ This project is a boilerplate for building .NET API applications with various fe

## Features

- [ ] [Vertical Slicing Architecture](https://github.com/FullstackCodingGuy/Developer-Fundamentals/wiki/Architecture-%E2%80%90-Vertical-Slicing-Architecture)
- [x] [Vertical Slicing Architecture](https://github.com/FullstackCodingGuy/Developer-Fundamentals/wiki/Architecture-%E2%80%90-Vertical-Slicing-Architecture)
- [x] Swagger
- [x] Minimal API
- [x] **GraphQL API with HotChocolate**
- [x] Professional architecture with clean separation
- [x] Complete blog management domain (Blogs, Posts, Comments)
- [x] DataLoaders for N+1 query prevention
- [x] Real-time subscriptions with Redis
- [x] Built-in GraphQL Playground and Schema explorer
- [x] Query complexity analysis and rate limiting
- [x] Field-level authorization support
- [x] Comprehensive error handling
- [x] Performance monitoring and observability
- [x] Authentication using JWT Bearer tokens
- [ ] Authorization
- [x] Authorization with role-based access control
- [x] Rate limiting to prevent API abuse
- [x] CORS policies for secure cross-origin requests
- [x] Response caching and compression
- [x] Logging with Serilog
- [x] Health check endpoint
- [x] [Middlewares](https://github.com/FullstackCodingGuy/dotnetapi-boilerplate/tree/main/src/Middlewares)
- [ ] Entity Framework
- [ ] Serilog
- [ ] FluentValidation
- [x] Entity Framework Core with SQLite
- [x] Serilog with structured logging
- [x] FluentValidation
- [ ] Vault Integration
- [ ] MQ Integration
- [ ] Application Resiliency
- [ ] Performance
- [ ] Response Compression
- [ ] Response Caching
- [ ] Metrics
- [x] Application Resiliency (GraphQL level)
- [x] Performance
- [x] Response Compression
- [x] Response Caching
- [x] GraphQL query optimization
- [x] DataLoaders for efficient data fetching
- [ ] Deployment
- [ ] Docker
- [ ] Podman
Expand Down Expand Up @@ -98,13 +109,251 @@ docker-compose down

The application includes a health check endpoint to verify that the API is running. You can access it at:


```
GET /health

This will return a simple "Healthy" message.
```

## GraphQL API

This boilerplate includes a comprehensive GraphQL implementation using HotChocolate, designed with professional architecture patterns and enterprise-grade features.

### GraphQL Features

#### 🏗️ **Professional Architecture**
- **Clean Architecture**: Vertical slicing with clear separation of concerns
- **Domain-Driven Design**: Blog management domain with Blogs, Posts, and Comments
- **Repository Pattern**: Abstracted data access with Entity Framework Core
- **Service Layer**: Business logic separation with comprehensive services

#### 🚀 **Core GraphQL Capabilities**
- **Complete CRUD Operations**: Full Create, Read, Update, Delete support
- **Advanced Querying**: Complex filtering, sorting, and pagination
- **Real-time Subscriptions**: Live updates using Redis as message broker
- **Field-level Authorization**: Granular security control
- **Input Validation**: Comprehensive data validation and sanitization

#### ⚡ **Performance Optimization**
- **DataLoaders**: Automatic N+1 query prevention with batch loading
- **Query Complexity Analysis**: Protection against expensive queries
- **Response Caching**: Intelligent caching strategies
- **Database Optimization**: Efficient EF Core queries with projections

#### 🔐 **Security & Observability**
- **JWT Authentication**: Seamless integration with existing auth
- **Role-based Authorization**: Fine-grained access control
- **Rate Limiting**: GraphQL-specific rate limiting
- **Comprehensive Logging**: Structured logging with Serilog
- **Error Handling**: Professional error responses with detailed context

#### 🛠️ **Developer Experience**
- **Built-in GraphQL Playground**: Interactive query interface at `/graphql`
- **Schema Explorer**: Full schema documentation and introspection
- **Type Safety**: Strongly typed resolvers and models
- **Extensible Design**: Easy to add new types and features

### GraphQL Endpoints

#### **Main GraphQL Endpoint**
```
POST /graphql
```
- Primary endpoint for all GraphQL operations
- Supports queries, mutations, and subscriptions
- Built-in GraphQL Playground available in development

#### **GraphQL Playground** (Development)
```
GET /graphql
```
- Interactive GraphQL IDE
- Schema exploration and documentation
- Query testing and validation
- Real-time subscription testing

### Example Queries

#### **Get All Blogs with Posts**
```graphql
query GetBlogsWithPosts {
blogs {
id
name
description
posts {
id
title
content
author {
name
email
}
comments {
id
content
author
}
}
}
}
```

#### **Create a New Blog**
```graphql
mutation CreateBlog {
createBlog(input: {
name: "Tech Blog"
description: "A blog about technology"
author: "John Doe"
tags: ["tech", "programming"]
}) {
blog {
id
name
description
author
tags
createdAt
}
errors {
message
}
}
}
```

#### **Subscribe to New Posts**
```graphql
subscription NewPosts {
onPostCreated {
id
title
content
blog {
name
}
author {
name
}
}
}
```

#### **Complex Query with Filtering**
```graphql
query SearchPosts {
posts(
where: {
and: [
{ title: { contains: "GraphQL" } }
{ isPublished: { eq: true } }
{ createdAt: { gte: "2024-01-01" } }
]
}
order: [{ createdAt: DESC }]
take: 10
) {
id
title
content
blog {
name
}
commentCount
viewCount
}
}
```

### Architecture Overview

```
Features/GraphQL/
├── Configuration/ # GraphQL server configuration
│ └── GraphQLConfiguration.cs
├── Models/ # GraphQL types and DTOs
│ ├── BlogType.cs
│ ├── PostType.cs
│ ├── CommentType.cs
│ └── AuthorType.cs
├── Services/ # Business logic services
│ ├── IBlogService.cs
│ ├── BlogService.cs
│ ├── IPostService.cs
│ └── PostService.cs
├── Resolvers/ # GraphQL resolvers
│ ├── Query.cs # Query operations
│ ├── Mutation.cs # Mutation operations
│ ├── Subscription.cs # Real-time subscriptions
│ └── FieldResolvers.cs # Field-level resolvers
└── DataLoaders/ # Performance optimization
├── BlogDataLoaders.cs
└── PostDataLoaders.cs
```

### Performance Features

#### **DataLoaders**
Automatically batches and caches database queries to prevent N+1 problems:
- `BlogByIdDataLoader`: Efficient blog loading by ID
- `PostsByBlogIdDataLoader`: Batch loading of posts by blog
- `CommentsByPostIdDataLoader`: Efficient comment loading

#### **Query Complexity Analysis**
Protects against expensive queries with configurable limits:
- Maximum query depth: 10 levels
- Maximum query complexity: 1000 points
- Field introspection limits in production

#### **Caching Strategy**
Multi-level caching for optimal performance:
- DataLoader-level caching (request scoped)
- Service-level caching for expensive operations
- Response caching for static data

### Getting Started with GraphQL

1. **Start the application**:
```bash
dotnet run
```

2. **Open GraphQL Playground**:
Navigate to `http://localhost:8000/graphql`

3. **Explore the Schema**:
Use the schema explorer to understand available types and operations

4. **Try Sample Queries**:
Copy and paste the example queries above

5. **Test Real-time Features**:
Open multiple browser tabs to test subscriptions

### Configuration

GraphQL is configured in `Features/GraphQL/Configuration/GraphQLConfiguration.cs` with:

- **HotChocolate Server**: Latest version with all features enabled
- **Entity Framework Integration**: Automatic query translation
- **Redis Subscriptions**: Real-time capabilities
- **Authentication Integration**: JWT token validation
- **Error Handling**: Professional error responses
- **Performance Monitoring**: Query execution tracking

### Best Practices Implemented

- **Single Responsibility**: Each resolver handles one concern
- **Dependency Injection**: All services properly registered
- **Async/Await**: Non-blocking operations throughout
- **Error Boundaries**: Comprehensive error handling
- **Type Safety**: Strong typing for all operations
- **Documentation**: Inline documentation for all types
- **Testing Ready**: Architecture supports unit and integration testing

This GraphQL implementation provides a solid foundation for building modern, efficient APIs with excellent developer experience and enterprise-grade performance.

### Logging with Serilog

Serilog is configured to log to the console and a file with daily rotation. You can customize the logging settings in the `serilog.json` file.
Expand Down
Loading