AgentSkillsCN

bun-server-best-practices

收录所有可用的 Bun Server 技能与最佳实践指南。适用于寻找框架指导、发掘可用技能,或咨询 Bun Server 的各项能力与推荐模式时使用。

SKILL.md
--- frontmatter
name: bun-server-best-practices
description: Index of all available Bun Server skills and best practices guide. Use when looking for framework guidance, discovering available skills, or asking about Bun Server capabilities and recommended patterns.

Bun Server Skills Index & Best Practices

This skill provides an overview of all available skills for the Bun Server framework and guides you to the right resource.

Available Skills

Getting Started

SkillWhen to Use
quickstartNew project setup, TypeScript configuration, first application

Core Framework

SkillWhen to Use
dependency-injection@Injectable, @Inject, DI scopes, Symbol+Interface pattern
controller-routing@Controller, HTTP methods, route parameters, request/response
module-system@Module, imports/exports, forRoot pattern, modular architecture
middlewareCustom middleware, interceptors, CORS, rate limiting
validation@IsString, @IsEmail, DTOs, custom validators
error-handlingHttpException, exception filters, error responses

Official Modules

SkillWhen to Use
securityJWT, OAuth2, @UseGuards, @Roles, authentication
databaseDatabaseModule, ORM, @Entity, @Repository, @Transactional
cache@Cacheable, @CacheEvict, Redis cache
queue@Queue, @Cron, background jobs, scheduled tasks
sessionSessionModule, session storage, user state
eventsEventModule, @OnEvent, event-driven architecture
websocket@WebSocketGateway, real-time communication
swaggerSwaggerModule, OpenAPI, @ApiOperation
health-metricsHealthModule, MetricsModule, Prometheus
loggerLoggerModule, log levels, structured logging

Microservices

SkillWhen to Use
microserviceService discovery, config center, circuit breaker, tracing

Troubleshooting

SkillWhen to Use
troubleshootingDebugging, common errors, "not working" issues

Quick Reference by Task

"I want to create a new project"

→ Start with quickstart

"I need to add authentication"

→ Use security for JWT/OAuth2 and guards

"I want to validate user input"

→ Use validation for DTO validation

"I need to cache expensive operations"

→ Use cache for @Cacheable decorator

"I want to run background jobs"

→ Use queue for job queues and @Cron

"I need real-time features"

→ Use websocket for WebSocket gateways

"I want to build microservices"

→ Use microservice for service discovery and governance

"Something is not working"

→ Check troubleshooting for common issues

Best Practices Summary

Project Structure

code
src/
├── main.ts                 # Entry point
├── app.module.ts           # Root module
├── common/                 # Shared utilities
│   ├── middleware/
│   ├── filters/
│   └── guards/
├── users/                  # Feature module
│   ├── user.module.ts
│   ├── user.controller.ts
│   ├── user.service.ts
│   └── dto/
└── orders/                 # Feature module
    ├── order.module.ts
    └── ...

Module Configuration Order

typescript
// 1. Configure global modules FIRST
ConfigModule.forRoot({ defaultConfig: {} });
LoggerModule.forRoot({ level: LogLevel.INFO });
EventModule.forRoot({ wildcard: true });

// 2. THEN define modules
@Module({
  imports: [ConfigModule, LoggerModule, EventModule],
})
class AppModule {}

TypeScript Configuration (Required)

json
{
  "compilerOptions": {
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true
  }
}

Symbol + Interface Pattern

typescript
// Define interface and Symbol with same name
interface UserService {
  find(id: string): Promise<User>;
}
const UserService = Symbol("UserService");

// Register in module
@Module({
  providers: [{ provide: UserService, useClass: UserServiceImpl }],
})

// Import as value, not type
import { UserService } from "./user.service"; // ✅
import type { UserService } from "./user.service"; // ❌

Error Handling

typescript
// Use built-in exceptions
throw new NotFoundException("User not found");
throw new BadRequestException("Invalid input");

// Or custom exceptions
class UserNotFoundException extends HttpException {
  constructor(id: string) {
    super(404, `User ${id} not found`);
  }
}

Testing

bash
# Run tests in package directory
bun --cwd=packages/bun-server test

# Run specific test
bun --cwd=packages/bun-server test user.test.ts

Related Resources