@nestjsvn/swagger-sse
Version:
OpenAPI documentation and interactive Swagger UI for NestJS Server-Sent Events endpoints
436 lines (333 loc) โข 12.6 kB
Markdown
# @nestjsvn/swagger-sse
> **๐ง Development Status**: This project is currently in active development. Version 1.0.0 will be released soon with full production-ready features. The core functionality is implemented and tested, but the package is still in pre-release (v0.0.1).
[](https://badge.fury.io/js/@nestjsvn/swagger-sse)
[](https://opensource.org/licenses/MIT)
[](https://github.com/dragonxsx/nestjsx-swagger-sse/actions)
[](https://coveralls.io/github/dragonxsx/nestjsx-swagger-sse?branch=main)
**OpenAPI documentation and interactive Swagger UI for NestJS Server-Sent Events endpoints.**
`@nestjsvn/swagger-sse` bridges the gap between NestJS's excellent SSE support and OpenAPI documentation by providing automatic schema generation, interactive Swagger UI integration, and comprehensive TypeScript support for real-time event streaming APIs.
## โจ Features
- ๐ **Zero-configuration setup** with CLI plugin
- ๐ **Automatic OpenAPI schema generation** for SSE endpoints
- ๐ฏ **Interactive Swagger UI** with real-time event streaming
- ๐ **Full TypeScript support** with compile-time validation
- โก **High-performance** event processing
- ๐ก๏ธ **Authentication support** (JWT, API keys, OAuth)
- ๐ง **Flexible configuration** options
## ๐ Quick Start
### Installation
```bash
npm install @nestjsvn/swagger-sse
```
### Basic Setup
1. **Update your main application file:**
```typescript
// main.ts
import { NestFactory } from '@nestjs/core';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { setupSsePlugin } from '@nestjsvn/swagger-sse';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
const config = new DocumentBuilder()
.setTitle('My API')
.setDescription('API with SSE support')
.setVersion('1.0')
.build();
const document = SwaggerModule.createDocument(app, config);
// Replace SwaggerModule.setup with setupSsePlugin
setupSsePlugin(app, document, 'api-docs');
await app.listen(3000);
}
bootstrap();
```
2. **Create your first SSE endpoint:**
```typescript
// events.controller.ts
import { Controller, Sse } from '@nestjs/common';
import { Observable, interval, map } from 'rxjs';
import { ApiSse } from '@nestjsvn/swagger-sse';
export class UserCreatedDto {
userId: string;
username: string;
email: string;
timestamp: Date;
}
@Controller('events')
export class EventsController {
@Sse('user-stream')
@ApiSse({
summary: 'User events stream',
description: 'Real-time stream of user-related events',
events: {
'user-created': UserCreatedDto,
},
})
streamUserEvents(): Observable<MessageEvent> {
return interval(2000).pipe(
map((i) => ({
data: JSON.stringify({
userId: `user-${i}`,
username: `User${i}`,
email: `user${i}@example.com`,
timestamp: new Date(),
}),
type: 'user-created',
} as MessageEvent))
);
}
}
```
3. **Visit your Swagger UI:**
Navigate to `http://localhost:3000/api-docs` and interact with your SSE endpoints using the enhanced UI!
## ๐ฏ Interactive Demo

The enhanced Swagger UI provides:
- **Real-time connection management** with connect/disconnect controls
- **Live event streaming** with formatted JSON display
- **Event filtering and search** capabilities
- **Connection status indicators** and error handling
- **Mobile-responsive design** for all devices
## ๐ง Advanced Usage
### Automatic Documentation with CLI Plugin
Enable zero-configuration documentation by adding the CLI plugin:
```json
// nest-cli.json
{
"compilerOptions": {
"plugins": [
"@nestjs/swagger",
{
"name": "@nestjsvn/swagger-sse/plugin",
"options": {
"eventNamingConvention": "kebab-case",
"introspectComments": true
}
}
]
}
}
```
Now you can create SSE endpoints without explicit decorators:
```typescript
@Controller('notifications')
export class NotificationsController {
/**
* Streams notification events
* @summary Real-time notification stream
*/
@Sse('updates')
streamNotifications(): Observable<MessageEvent<NotificationDto>> {
// Plugin automatically generates documentation!
return this.notificationService.getStream();
}
}
```
### Multiple Event Types
Handle complex event scenarios with union types:
```typescript
@ApiSse({
summary: 'Multi-type event stream',
events: {
'user-created': UserCreatedDto,
'user-updated': UserUpdatedDto,
'user-deleted': UserDeletedDto,
'system-alert': SystemAlertDto,
},
})
streamEvents(): Observable<MessageEvent> {
return merge(
this.userEvents$,
this.systemEvents$,
this.alertEvents$
);
}
```
### Authentication & Security
Secure your SSE endpoints with guards and authentication:
```typescript
@UseGuards(JwtAuthGuard)
@ApiBearerAuth()
@ApiSse({
summary: 'Authenticated event stream',
security: [{ bearer: [] }],
events: {
'private-event': PrivateEventDto,
},
})
streamPrivateEvents(@Request() req): Observable<MessageEvent> {
return this.eventService.getPrivateEvents(req.user.id);
}
```
### Error Handling
Implement robust error handling in your streams:
```typescript
@ApiSse({
events: {
'data-update': DataUpdateDto,
'error': ErrorEventDto,
},
})
streamWithErrorHandling(): Observable<MessageEvent> {
return this.dataService.watchData().pipe(
map(data => ({ type: 'data-update', data: JSON.stringify(data) })),
catchError(error => of({
type: 'error',
data: JSON.stringify({ message: error.message })
}))
);
}
```
## ๐ Documentation
- **[Getting Started Guide](./docs/getting-started.md)** - Step-by-step setup instructions
- **[API Reference](./docs/api-reference.md)** - Complete API documentation
- **[Plugin Usage](./docs/plugin-usage.md)** - CLI plugin configuration
- **[UI Plugin Usage](./docs/ui-plugin-usage.md)** - Swagger UI integration
- **[Troubleshooting](./docs/troubleshooting.md)** - Common issues and solutions
- **[Examples](./examples/)** - Real-world usage examples
## ๐งช Testing
The package includes comprehensive testing suites:
```bash
# Unit tests
npm run test
# Unit tests with watch mode
npm run test:watch
# Test coverage report
npm run test:coverage
```
## ๐ง Configuration
### Basic Configuration
```typescript
setupSsePlugin(app, document, 'api-docs', {
customSiteTitle: 'My API Documentation',
customCss: '.swagger-ui .topbar { display: none }',
swaggerOptions: {
persistAuthorization: true,
},
});
```
### Plugin Configuration
```json
{
"name": "@nestjsvn/swagger-sse/plugin",
"options": {
"eventNamingConvention": "kebab-case",
"introspectComments": true,
"autoGenerateOperationId": false,
"customEventMappings": {
"UserCreatedDto": "user.created"
}
}
}
```
## ๐ง Development & Code Quality
This project maintains high code quality standards through comprehensive ESLint and Prettier configurations. Our setup has achieved a **95.7% reduction in lint errors** while maintaining excellent developer experience.
### ๐ Code Quality Overview
The project uses a modern code quality stack:
- **ESLint** with TypeScript support, accessibility rules, and code quality enforcement
- **Prettier** for consistent code formatting across the entire codebase
- **TypeScript** strict mode with comprehensive type checking
- **Accessibility** rules via [`eslint-plugin-jsx-a11y`](https://github.com/jsx-eslint/eslint-plugin-jsx-a11y)
- **Automated workflows** with pre-commit hooks and CI integration
#### Quick Script Reference
```bash
# Linting
npm run lint # Check all files for lint errors
npm run lint:fix # Fix all auto-fixable lint errors
npm run lint:src # Check only src/ directory
npm run lint:src:fix # Fix only src/ directory
# Formatting
npm run format # Format all files with Prettier
npm run format:check # Check formatting without changes
npm run format:src # Format only src/ directory
npm run format:src:check # Check src/ formatting only
# Combined workflows
npm run quality # Run lint + format:check + type-check
npm run quality:fix # Run lint:fix + format + type-check
npm run type-check # TypeScript compilation check
```
### ๐ Setup Instructions
After cloning the repository, verify your setup:
```bash
# Install dependencies
npm install
# Verify linting works
npm run lint:src
# Verify formatting works
npm run format:src:check
# Run complete quality check
npm run quality
# Expected output: โ
All checks should pass
```
### โก Development Workflow
#### Pre-commit Workflow
**Recommended pre-commit checklist:**
- [ ] Run [`npm run quality:fix`](package.json:45) to fix all auto-fixable issues
- [ ] Run [`npm run test`](package.json:31) to ensure all tests pass
- [ ] Review ESLint warnings and address critical issues
- [ ] Verify TypeScript compilation with [`npm run type-check`](package.json:43)
**Quick pre-commit command:**
```bash
npm run quality:fix && npm run test
```
#### Code Review Process
**For reviewers:**
- Focus on logic and architecture rather than formatting
- All formatting issues are automatically handled
- ESLint warnings indicate potential code quality issues
- TypeScript errors must be resolved before merge
**For contributors:**
- Ensure [`npm run quality`](package.json:44) passes before requesting review
- Address any ESLint warnings in your changes
- Maintain test coverage for new functionality
---
## ๐ค Contributing
We welcome contributions! Please see our [Contributing Guide](./CONTRIBUTING.md) for details.
Before contributing, please review our [Development & Code Quality](#-development--code-quality) section for setup instructions and workflow guidelines.
### Development Setup
```bash
# Clone the repository
git clone https://github.com/dragonxsx/nestjsx-swagger-sse.git
cd swagger-sse
# Install dependencies
npm install
# Verify setup with quality checks
npm run quality
# Run tests
npm run test
# Build the project
npm run build
# Run E2E tests
npm run test:e2e
```
### Contribution Workflow
1. **Setup**: Follow the [Development & Code Quality](#-development--code-quality) setup instructions
2. **Development**: Use the recommended [daily workflow](#daily-development-workflow)
3. **Quality**: Run [`npm run quality:fix`](package.json:45) before committing
4. **Testing**: Ensure all tests pass with [`npm run test`](package.json:31)
5. **Documentation**: Update relevant documentation for new features
### Code Standards
All contributions must meet our code quality standards:
- โ
ESLint rules must pass (zero errors)
- โ
Prettier formatting must be consistent
- โ
TypeScript compilation must succeed
- โ
Test coverage must be maintained
- โ
Documentation must be updated for new features
See our [Configuration Details](#๏ธ-configuration-details) for specific rules and rationale.
## ๐ License
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
## ๐ Acknowledgments
- **NestJS Team** - For the excellent framework and SSE support
- **Swagger UI Team** - For the extensible documentation interface
- **Community Contributors** - For feedback, bug reports, and contributions
## ๐ Project Stats




## ๐ Related Projects
- **[@nestjs/swagger](https://github.com/nestjs/swagger)** - OpenAPI documentation for NestJS
- **[@nestjs/common](https://github.com/nestjs/nest)** - NestJS framework
---
**Made with โค๏ธ by the NestJS community**
[Report Bug](https://github.com/dragonxsx/nestjsx-swagger-sse/issues) ยท [Request Feature](https://github.com/dragonxsx/nestjsx-swagger-sse/issues) ยท [Documentation](./docs/) ยท [Examples](./examples/)