返回 Skill 列表
extension
分类: 开发与工程无需 API Key

nestjs

NestJS模块化API架构,包括控制器、服务、守卫、中间件和依赖注入模式。使用场景:构建API端点、实现服务、创建守卫/拦截器、处理身份验证/授权或任何使用NestJS的后端业务逻辑。

person作者: jakexiaohubgithub

NestJS Skill

NestJS provides a structured, Angular-inspired architecture for Node.js backends. It enforces separation of concerns through modules, controllers, and services with built-in dependency injection. Use decorators for routing, validation, and metadata.

Quick Start

Module Structure

// src/products/products.module.ts
@Module({
  imports: [TypeOrmModule.forFeature([Product])],
  controllers: [ProductsController],
  providers: [ProductsService],
  exports: [ProductsService],
})
export class ProductsModule {}

Controller Pattern

// src/products/products.controller.ts
@Controller('products')
export class ProductsController {
  constructor(private readonly productsService: ProductsService) {}

  @Get()
  findAll(@Query() query: FindProductsDto) {
    return this.productsService.findAll(query);
  }

  @Post()
  @UseGuards(JwtAuthGuard)
  create(@Body() dto: CreateProductDto, @Request() req) {
    return this.productsService.create(dto, req.user.id);
  }
}

Service Pattern

// src/products/products.service.ts
@Injectable()
export class ProductsService {
  constructor(
    @InjectRepository(Product)
    private readonly productRepo: Repository<Product>,
  ) {}

  async findAll(query: FindProductsDto): Promise<Product[]> {
    return this.productRepo.find({ where: query });
  }
}

Key Concepts

| Concept | Usage | Example | |---------|-------|---------| | Module | Feature boundary, DI container | @Module({ providers: [...] }) | | Controller | HTTP routing, request handling | @Controller('users') | | Service | Business logic, injectable | @Injectable() | | Guard | Auth/authorization checks | @UseGuards(AuthGuard) | | Pipe | Validation, transformation | @UsePipes(ValidationPipe) | | Interceptor | Response transformation, logging | @UseInterceptors(LoggingInterceptor) |

Common Patterns

Global Validation

// main.ts
app.useGlobalPipes(new ValidationPipe({
  whitelist: true,
  forbidNonWhitelisted: true,
  transform: true,
}));

Exception Filter

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const status = exception.getStatus();
    
    response.status(status).json({
      statusCode: status,
      message: exception.message,
      timestamp: new Date().toISOString(),
    });
  }
}

See Also

  • routes - Controller routing patterns
  • services - Service layer and DI
  • database - TypeORM/Prisma integration
  • auth - Guards and authentication
  • errors - Exception handling

Related Skills

  • See the typescript skill for strict typing patterns
  • See the prisma skill for database ORM alternative to TypeORM
  • See the postgresql skill for database design
  • See the zod skill for runtime validation
  • See the jest skill for unit testing NestJS services