
Nestjs
- 10 installs
- Updated July 29, 2026
- full-statck-skills/nodejs-skills
Build NestJS backends with controllers, providers, modules, dependency injection, guards, pipes, interceptors, GraphQL, and microservices.
About
Guides building NestJS applications using official docs, covering architecture, dependency injection, and cross-cutting concerns like guards and pipes. A developer uses it to build or refactor a NestJS backend.
- Controllers, providers, modules, and dependency injection from official docs
- Middleware, guards, pipes, interceptors, GraphQL, WebSockets, and microservices
Nestjs by the numbers
- 10 all-time installs (skills.sh)
- Ranked #3,590 of 4,347 Backend & APIs skills by installs in the Skillselion catalog
- Data as of Jul 30, 2026 (Skillselion catalog sync)
npx skills add https://github.com/full-statck-skills/nodejs-skills --skill nestjsAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 10 |
|---|---|
| Last updated | July 29, 2026 |
| Repository | full-statck-skills/nodejs-skills ↗ |
What it does
Build NestJS backends with controllers, providers, modules, dependency injection, guards, pipes, interceptors, GraphQL, and microservices.
Files
When to use this skill
Use this skill whenever the user wants to:
- Build or refactor a NestJS application
- Implement controllers, providers, and modules
- Apply middleware, pipes, guards, or interceptors
- Configure DI scopes, dynamic modules, or lifecycle hooks
- Add validation, serialization, caching, logging, or queues
- Integrate GraphQL, WebSockets, or microservices
- Document APIs with OpenAPI/Swagger
- Implement authentication/authorization or security hardening
- Write unit or e2e tests for NestJS
How to use this skill
1. Identify the topic from the user's request and find the corresponding example file in the mapping below
2. Load the appropriate example file from the examples/ directory
3. Follow the specific instructions in that example file for syntax, structure, and best practices
Important Notes:
- All examples follow NestJS official documentation structure
- Examples include both JavaScript and TypeScript versions where applicable
- Each example file includes key concepts, code examples, and official documentation links
- Always check the example file for best practices and common patterns
4. Use templates from the templates/ directory to speed up common scaffolding
Doc mapping (one-to-one with https://docs.nestjs.com/)
Overview (概览)
examples/overview/introduction.md→ https://docs.nestjs.com/examples/fundamentals/first-steps.md→ https://docs.nestjs.com/first-stepsexamples/fundamentals/controllers.md→ https://docs.nestjs.com/controllersexamples/fundamentals/providers.md→ https://docs.nestjs.com/providersexamples/fundamentals/modules.md→ https://docs.nestjs.com/modulesexamples/fundamentals/middleware.md→ https://docs.nestjs.com/middlewareexamples/fundamentals/exception-filters.md→ https://docs.nestjs.com/exception-filtersexamples/fundamentals/pipes.md→ https://docs.nestjs.com/pipesexamples/fundamentals/guards.md→ https://docs.nestjs.com/guardsexamples/fundamentals/interceptors.md→ https://docs.nestjs.com/interceptorsexamples/overview/custom-decorators.md→ https://docs.nestjs.com/custom-decorators
Fundamentals (基础)
examples/fundamentals/custom-providers.md→ https://docs.nestjs.com/fundamentals/custom-providersexamples/fundamentals/async-providers.md→ https://docs.nestjs.com/fundamentals/async-providersexamples/fundamentals/dynamic-modules.md→ https://docs.nestjs.com/fundamentals/dynamic-modulesexamples/fundamentals/module-ref.md→ https://docs.nestjs.com/fundamentals/module-refexamples/fundamentals/execution-context.md→ https://docs.nestjs.com/fundamentals/execution-contextexamples/fundamentals/lifecycle-events.md→ https://docs.nestjs.com/fundamentals/lifecycle-eventsexamples/fundamentals/injection-scopes.md→ https://docs.nestjs.com/fundamentals/injection-scopesexamples/fundamentals/request-scoped.md→ https://docs.nestjs.com/fundamentals/request-scopedexamples/fundamentals/circular-dependency.md→ https://docs.nestjs.com/fundamentals/circular-dependency
Techniques (技巧)
examples/techniques/configuration.md→ https://docs.nestjs.com/techniques/configurationexamples/techniques/validation.md→ https://docs.nestjs.com/techniques/validationexamples/techniques/serialization.md→ https://docs.nestjs.com/techniques/serializationexamples/techniques/caching.md→ https://docs.nestjs.com/techniques/cachingexamples/techniques/logger.md→ https://docs.nestjs.com/techniques/loggerexamples/techniques/events.md→ https://docs.nestjs.com/techniques/eventsexamples/techniques/task-scheduling.md→ https://docs.nestjs.com/techniques/task-schedulingexamples/techniques/queues.md→ https://docs.nestjs.com/techniques/queuesexamples/techniques/file-upload.md→ https://docs.nestjs.com/techniques/file-uploadexamples/techniques/streaming-files.md→ https://docs.nestjs.com/techniques/streaming-filesexamples/techniques/database.md→ https://docs.nestjs.com/techniques/databaseexamples/techniques/mongodb.md→ https://docs.nestjs.com/techniques/mongodbexamples/techniques/mongoose.md→ https://docs.nestjs.com/techniques/mongooseexamples/techniques/sequelize.md→ https://docs.nestjs.com/techniques/sequelizeexamples/techniques/prisma.md→ https://docs.nestjs.com/recipes/prisma
Security (安全)
examples/security/authentication.md→ https://docs.nestjs.com/security/authenticationexamples/security/authorization.md→ https://docs.nestjs.com/security/authorizationexamples/security/helmet.md→ https://docs.nestjs.com/security/helmetexamples/security/cors.md→ https://docs.nestjs.com/security/corsexamples/security/rate-limiting.md→ https://docs.nestjs.com/security/rate-limiting
GraphQL
examples/graphql/quick-start.md→ https://docs.nestjs.com/graphql/quick-startexamples/graphql/resolvers.md→ https://docs.nestjs.com/graphql/resolversexamples/graphql/scalars.md→ https://docs.nestjs.com/graphql/scalarsexamples/graphql/interfaces.md→ https://docs.nestjs.com/graphql/interfacesexamples/graphql/unions.md→ https://docs.nestjs.com/graphql/unionsexamples/graphql/directives.md→ https://docs.nestjs.com/graphql/directivesexamples/graphql/plugins.md→ https://docs.nestjs.com/graphql/pluginsexamples/graphql/subscriptions.md→ https://docs.nestjs.com/graphql/subscriptionsexamples/graphql/federation.md→ https://docs.nestjs.com/graphql/federationexamples/graphql/migration.md→ https://docs.nestjs.com/graphql/migration
WebSockets
examples/websockets/gateways.md→ https://docs.nestjs.com/websockets/gatewaysexamples/websockets/exception-filters.md→ https://docs.nestjs.com/websockets/exception-filtersexamples/websockets/guards.md→ https://docs.nestjs.com/websockets/guardsexamples/websockets/interceptors.md→ https://docs.nestjs.com/websockets/interceptorsexamples/websockets/adapters.md→ https://docs.nestjs.com/websockets/adapters
Microservices
examples/microservices/basics.md→ https://docs.nestjs.com/microservices/basicsexamples/microservices/redis.md→ https://docs.nestjs.com/microservices/redisexamples/microservices/mqtt.md→ https://docs.nestjs.com/microservices/mqttexamples/microservices/nats.md→ https://docs.nestjs.com/microservices/natsexamples/microservices/kafka.md→ https://docs.nestjs.com/microservices/kafkaexamples/microservices/grpc.md→ https://docs.nestjs.com/microservices/grpcexamples/microservices/rabbitmq.md→ https://docs.nestjs.com/microservices/rabbitmqexamples/microservices/custom-transport.md→ https://docs.nestjs.com/microservices/custom-transportexamples/microservices/hybrid-application.md→ https://docs.nestjs.com/microservices/hybrid-application
OpenAPI (Swagger)
examples/openapi/introduction.md→ https://docs.nestjs.com/openapi/introductionexamples/openapi/operations.md→ https://docs.nestjs.com/openapi/operationsexamples/openapi/types-and-parameters.md→ https://docs.nestjs.com/openapi/types-and-parametersexamples/openapi/security.md→ https://docs.nestjs.com/openapi/securityexamples/openapi/mapped-types.md→ https://docs.nestjs.com/openapi/mapped-types
CLI & Testing & Recipes
examples/cli/overview.md→ https://docs.nestjs.com/cli/overviewexamples/testing/unit-testing.md→ https://docs.nestjs.com/fundamentals/testingexamples/testing/e2e-testing.md→ https://docs.nestjs.com/fundamentals/testingexamples/recipes/cqrs.md→ https://docs.nestjs.com/recipes/cqrsexamples/recipes/mikroorm.md→ https://docs.nestjs.com/recipes/mikroormexamples/recipes/terminus.md→ https://docs.nestjs.com/recipes/terminusexamples/faq.md→ https://docs.nestjs.com/faq
Examples and Templates
This skill includes detailed examples organized to match the NestJS official documentation structure (https://docs.nestjs.com/). All examples are in the examples/ directory, organized by topic (see mapping above).
To use examples:
- Identify the topic from the user's request
- Load the appropriate example file from the mapping above
- Follow the instructions, syntax, and best practices in that file
- Adapt the code examples to your specific use case
To use templates:
- Reference templates in
templates/directory for common scaffolding - Templates include: controller, provider, module, middleware, guard, pipe, interceptor, exception filter, DTO, and project structure
- Adapt templates to your specific needs and coding style
Best Practices
1. Use dependency injection: Leverage NestJS DI container for better testability and maintainability 2. Organize by modules: Group related functionality into feature modules 3. Use decorators consistently: Follow NestJS decorator patterns for controllers, providers, and routes 4. Validate input data: Use ValidationPipe and DTOs for request validation 5. Handle errors gracefully: Implement global exception filters for consistent error handling 6. Use guards for authorization: Protect routes with guards rather than inline checks 7. Leverage interceptors: Use interceptors for cross-cutting concerns like logging and transformation 8. Type safety: Use TypeScript for better type safety and developer experience 9. Test thoroughly: Write unit tests for services and E2E tests for API endpoints 10. Follow official patterns: Refer to official documentation for recommended patterns and practices
Resources
- Official Documentation: https://docs.nestjs.com/
- GitHub Repository: https://github.com/nestjs/nest
Keywords
NestJS, Node.js, framework, controller, provider, module, middleware, exception filter, pipe, guard, interceptor, dependency injection, GraphQL, WebSocket, microservice, OpenAPI, Swagger, testing, validation, caching, logging, TypeScript, decorator, DI, IoC, 控制器, 提供者, 模块, 中间件, 守卫, 管道, 拦截器, 依赖注入
能力边界
✅ 适用场景
- 当你需要使用此技能对应的技术栈时
- 当项目需要遵循最佳实践时
- 当需要快速上手或深入理解核心概念时
⚠️ 需要注意
- 复杂业务逻辑需要结合具体场景调整
- 性能优化需要根据实际数据量评估
❌ 不适用场景
- 不相关的技术栈或框架
- 需要完全自定义的特殊场景
常见陷阱 (Gotchas)
1. 版本兼容性:注意框架版本与依赖库的兼容性,不同版本 API 可能有差异 2. 配置文件格式:配置文件格式错误是最常见的问题,建议使用编辑器的语法检查 3. 环境变量:确保所有必要的环境变量已正确设置,敏感信息不要硬编码 4. 依赖冲突:多版本共存时注意依赖冲突,使用 lock 文件锁定版本 5. 性能陷阱:大数据量场景下注意性能优化,避免 N+1 查询等常见问题
使用流程
Step 1: 环境准备
确保开发环境已安装必要的依赖和工具。
Step 2: 配置初始化
根据项目需求进行基础配置。
Step 3: 核心功能使用
按照示例代码实现核心功能。
Step 4: 测试验证
运行测试确保功能正常。
Step 5: 部署上线
完成开发后进行部署和监控。
Decorators API | 装饰器 API
API Reference
All NestJS decorators and their usage.
Module Decorators
@Module()
Defines a module.
Properties:
imports: Array of modules to importcontrollers: Array of controllersproviders: Array of providersexports: Array of providers to export
Example:
@Module({
imports: [OtherModule],
controllers: [CatsController],
providers: [CatsService],
exports: [CatsService],
})
export class CatsModule {}Controller Decorators
@Controller()
Defines a controller with optional route prefix.
Parameters:
prefix: Route prefix (optional)
Example:
@Controller('cats')
export class CatsController {}@Get(), @Post(), @Put(), @Delete(), @Patch()
HTTP method decorators.
Parameters:
path: Route path (optional)
Example:
@Get()
@Get('profile')
@Post('create')Parameter Decorators
@Param()
Extract route parameter.
Parameters:
property: Parameter name (optional)
Example:
@Get(':id')
findOne(@Param('id') id: string) {}@Query()
Extract query parameter.
Parameters:
property: Query parameter name (optional)
Example:
@Get()
findAll(@Query('limit') limit: number) {}@Body()
Extract request body.
Parameters:
property: Body property name (optional)
Example:
@Post()
create(@Body() createDto: CreateDto) {}@Headers()
Extract request header.
Parameters:
property: Header name (optional)
Example:
@Get()
findAll(@Headers('authorization') auth: string) {}@Req(), @Request()
Extract request object.
Example:
@Get()
findAll(@Req() request: Request) {}@Res(), @Response()
Extract response object.
Example:
@Get()
findAll(@Res() response: Response) {}Provider Decorators
@Injectable()
Marks a class as a provider.
Example:
@Injectable()
export class CatsService {}@Inject()
Injects a custom provider.
Parameters:
token: Injection token
Example:
constructor(@Inject('CONFIG') private config: any) {}@Optional()
Marks a dependency as optional.
Example:
constructor(@Optional() @Inject('CONFIG') private config: any) {}Guard Decorators
@UseGuards()
Applies guards to controller or route.
Parameters:
...guards: Guard classes or instances
Example:
@UseGuards(AuthGuard)
@Controller('cats')
export class CatsController {}Interceptor Decorators
@UseInterceptors()
Applies interceptors to controller or route.
Parameters:
...interceptors: Interceptor classes or instances
Example:
@UseInterceptors(LoggingInterceptor)
@Controller('cats')
export class CatsController {}Pipe Decorators
@UsePipes()
Applies pipes to controller or route.
Parameters:
...pipes: Pipe classes or instances
Example:
@UsePipes(ValidationPipe)
@Post()
create(@Body() createDto: CreateDto) {}Exception Filter Decorators
@UseFilters()
Applies exception filters to controller or route.
Parameters:
...filters: Exception filter classes or instances
Example:
@UseFilters(HttpExceptionFilter)
@Controller('cats')
export class CatsController {}HTTP Code Decorators
@HttpCode()
Sets HTTP status code.
Parameters:
statusCode: HTTP status code
Example:
@Post()
@HttpCode(201)
create() {}@Header()
Sets response header.
Parameters:
name: Header namevalue: Header value
Example:
@Get()
@Header('Cache-Control', 'no-cache')
findAll() {}@Redirect()
Redirects to a URL.
Parameters:
url: Redirect URLstatusCode: HTTP status code (default: 302)
Example:
@Get()
@Redirect('https://nestjs.com', 301)
redirect() {}Key Points
- Decorators provide metadata for NestJS
- Use decorators to configure controllers, providers, and routes
- Parameter decorators extract values from requests
- Method decorators define HTTP methods and routes
- Class decorators define modules, controllers, and providers
CLI Overview | CLI 概览
官方文档: https://docs.nestjs.com/cli/overview
Instructions
Use the Nest CLI to generate and manage projects.
Key Concepts
- Use the Nest CLI to generate and manage projects.
- Use decorators to declare behavior
- Keep providers and controllers focused
Example
// example(): 示例函数,演示核心用法
function example() {
return 'overview'
}FAQ | 常见问题
官方文档: https://docs.nestjs.com/faq
Instructions
Common questions and troubleshooting.
Key Concepts
- Common questions and troubleshooting.
- Use decorators to declare behavior
- Keep providers and controllers focused
Example
// example(): 示例函数,演示核心用法
function example() {
return 'faq'
}Async Providers | 异步提供者
官方文档: https://docs.nestjs.com/fundamentals/async-providers
Instructions
Configure providers with async factory functions.
Key Concepts
- Configure providers with async factory functions.
- Use decorators to declare behavior
- Keep providers and controllers focused
Example
// example(): 示例函数,演示核心用法
function example() {
return 'async-providers'
}Circular Dependency | 循环依赖
官方文档: https://docs.nestjs.com/fundamentals/circular-dependency
Instructions
Resolve circular dependencies with forwardRef.
Key Concepts
- Resolve circular dependencies with forwardRef.
- Use decorators to declare behavior
- Keep providers and controllers focused
Example
// example(): 示例函数,演示核心用法
function example() {
return 'circular-dependency'
}Controllers | 控制器
官方文档: https://docs.nestjs.com/controllers
Instructions
This example demonstrates how to create controllers and handle HTTP requests in NestJS.
Key Concepts
- Creating controllers with
@Controller() - Route handlers with
@Get(),@Post(),@Put(),@Delete(),@Patch() - Route parameters with
@Param() - Query parameters with
@Query() - Request body with
@Body() - Request and response objects
Example: Basic Controller
import { Controller, Get } from '@nestjs/common';
@Controller('cats')
export class CatsController {
@Get()
findAll(): string {
return 'This action returns all cats';
}
}Example: Route Parameters
import { Controller, Get, Param } from '@nestjs/common';
@Controller('cats')
export class CatsController {
@Get(':id')
findOne(@Param('id') id: string): string {
return `This action returns a #${id} cat`;
}
@Get(':id/owner/:ownerId')
findOneWithOwner(
@Param('id') id: string,
@Param('ownerId') ownerId: string,
): string {
return `Cat #${id} owned by #${ownerId}`;
}
}Example: Query Parameters
import { Controller, Get, Query } from '@nestjs/common';
@Controller('cats')
export class CatsController {
@Get()
findAll(@Query('limit') limit: number): string {
return `This action returns all cats (limit: ${limit})`;
}
}Example: Request Body
import { Controller, Post, Body } from '@nestjs/common';
@Controller('cats')
export class CatsController {
@Post()
create(@Body() createCatDto: CreateCatDto): string {
return 'This action adds a new cat';
}
}Example: All HTTP Methods
import { Controller, Get, Post, Put, Delete, Patch, Body, Param } from '@nestjs/common';
@Controller('cats')
export class CatsController {
@Get()
findAll(): string {
return 'This action returns all cats';
}
@Get(':id')
findOne(@Param('id') id: string): string {
return `This action returns a #${id} cat`;
}
@Post()
create(@Body() createCatDto: CreateCatDto): string {
return 'This action adds a new cat';
}
@Put(':id')
update(@Param('id') id: string, @Body() updateCatDto: UpdateCatDto): string {
return `This action updates a #${id} cat`;
}
@Patch(':id')
partialUpdate(@Param('id') id: string, @Body() updateCatDto: UpdateCatDto): string {
return `This action partially updates a #${id} cat`;
}
@Delete(':id')
remove(@Param('id') id: string): string {
return `This action removes a #${id} cat`;
}
}Example: Status Codes
import { Controller, Get, HttpCode, HttpStatus, Post } from '@nestjs/common';
@Controller('cats')
export class CatsController {
@Post()
@HttpCode(HttpStatus.CREATED)
create(): string {
return 'This action adds a new cat';
}
@Get()
@HttpCode(200)
findAll(): string {
return 'This action returns all cats';
}
}Example: Headers
import { Controller, Get, Header } from '@nestjs/common';
@Controller('cats')
export class CatsController {
@Get()
@Header('Cache-Control', 'no-cache')
findAll(): string {
return 'This action returns all cats';
}
}Example: Redirects
import { Controller, Get, Redirect } from '@nestjs/common';
@Controller('cats')
export class CatsController {
@Get()
@Redirect('https://nestjs.com', 301)
redirect() {
return { url: 'https://nestjs.com' };
}
}Key Points
- Controllers handle incoming requests and return responses
- Use
@Controller()decorator with optional route prefix - Route handlers use HTTP method decorators (
@Get(),@Post(), etc.) - Use
@Param()to extract route parameters - Use
@Query()to extract query parameters - Use
@Body()to extract request body - Use
@HttpCode()to set status codes - Use
@Header()to set response headers - Use
@Redirect()for redirects
Custom Decorators | 自定义装饰器
官方文档: https://docs.nestjs.com/custom-decorators
Instructions
Create custom decorators to improve readability and reuse.
Key Concepts
- Create custom decorators to improve readability and reuse.
- Use decorators to declare behavior
- Keep providers and controllers focused
Example
// example(): 示例函数,演示核心用法
function example() {
return 'custom-decorators'
}Custom Providers | 自定义提供者
官方文档: https://docs.nestjs.com/fundamentals/custom-providers
Instructions
Create custom provider definitions and tokens.
Key Concepts
- Create custom provider definitions and tokens.
- Use decorators to declare behavior
- Keep providers and controllers focused
Example
// example(): 示例函数,演示核心用法
function example() {
return 'custom-providers'
}Dynamic Modules | 动态模块
官方文档: https://docs.nestjs.com/fundamentals/dynamic-modules
Instructions
Create modules that accept configuration at runtime.
Key Concepts
- Create modules that accept configuration at runtime.
- Use decorators to declare behavior
- Keep providers and controllers focused
Example
// example(): 示例函数,演示核心用法
function example() {
return 'dynamic-modules'
}Exception Filters | 异常过滤器
官方文档: https://docs.nestjs.com/exception-filters
Instructions
This example demonstrates how to create and use exception filters for error handling in NestJS.
Key Concepts
- Creating exception filters with
@Catch()andExceptionFilter - Using exception filters with
@UseFilters() - Global exception filters
- Built-in exceptions
- Custom exceptions
Example: Basic Exception Filter
import { ExceptionFilter, Catch, ArgumentsHost, HttpException, HttpStatus } from '@nestjs/common';
import { Request, Response } from 'express';
@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
catch(exception: unknown, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
const request = ctx.getRequest<Request>();
const status =
exception instanceof HttpException
? exception.getStatus()
: HttpStatus.INTERNAL_SERVER_ERROR;
response.status(status).json({
statusCode: status,
timestamp: new Date().toISOString(),
path: request.url,
});
}
}Example: Specific Exception Filter
import { ExceptionFilter, Catch, ArgumentsHost, HttpException } from '@nestjs/common';
import { Request, Response } from 'express';
@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
catch(exception: HttpException, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
const request = ctx.getRequest<Request>();
const status = exception.getStatus();
response.status(status).json({
statusCode: status,
timestamp: new Date().toISOString(),
path: request.url,
message: exception.message,
});
}
}Example: Using Exception Filter in Controller
import { Controller, Get, UseFilters, HttpException, HttpStatus } from '@nestjs/common';
import { HttpExceptionFilter } from './http-exception.filter';
@Controller('cats')
@UseFilters(HttpExceptionFilter)
export class CatsController {
@Get()
findAll() {
throw new HttpException('Forbidden', HttpStatus.FORBIDDEN);
}
}Example: Global Exception Filter
// main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { HttpExceptionFilter } from './common/filters/http-exception.filter';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalFilters(new HttpExceptionFilter());
await app.listen(3000);
}
bootstrap();Example: Built-in Exceptions
import {
BadRequestException,
UnauthorizedException,
NotFoundException,
ForbiddenException,
NotAcceptableException,
RequestTimeoutException,
ConflictException,
GoneException,
HttpVersionNotSupportedException,
PayloadTooLargeException,
UnsupportedMediaTypeException,
UnprocessableEntityException,
InternalServerErrorException,
NotImplementedException,
BadGatewayException,
ServiceUnavailableException,
GatewayTimeoutException,
} from '@nestjs/common';
// Usage
throw new BadRequestException('Invalid input');
throw new NotFoundException('Resource not found');
throw new UnauthorizedException('Unauthorized');Example: Custom Exception
import { HttpException, HttpStatus } from '@nestjs/common';
export class CustomException extends HttpException {
constructor() {
super('Custom error message', HttpStatus.BAD_REQUEST);
}
}
// Usage
throw new CustomException();Key Points
- Exception filters catch and handle exceptions
- Use
@Catch()to specify exception types - Use
@UseFilters()to apply filters - Filters can be applied globally or per route
- Built-in exceptions provide standard HTTP errors
- Custom exceptions extend HttpException
- Filters have access to ArgumentsHost for request/response
Execution Context | 执行上下文
官方文档: https://docs.nestjs.com/fundamentals/execution-context
Instructions
Use ExecutionContext to access request details in guards/interceptors.
Key Concepts
- Use ExecutionContext to access request details in guards/interceptors.
- Use decorators to declare behavior
- Keep providers and controllers focused
Example
// example(): 示例函数,演示核心用法
function example() {
return 'execution-context'
}First Steps | 快速开始
官方文档: https://docs.nestjs.com/first-steps
Instructions
This example demonstrates how to create a new NestJS application and understand the basic project structure.
Key Concepts
- Installing NestJS CLI
- Creating a new project
- Project structure
- Running the application
- Basic application setup
Example: Installation
# Install NestJS CLI globally
npm i -g @nestjs/cli
# Or using yarn
yarn global add @nestjs/cliExample: Creating a New Project
# Create a new project
nest new project-name
# Or using npm
npm i -g @nestjs/cli
nest new project-nameExample: Project Structure
project-name/
├── src/
│ ├── app.controller.ts # Basic controller
│ ├── app.controller.spec.ts # Controller tests
│ ├── app.service.ts # Basic service
│ ├── app.module.ts # Root module
│ └── main.ts # Application entry point
├── test/ # E2E tests
├── node_modules/
├── package.json
├── tsconfig.json # TypeScript configuration
└── nest-cli.json # NestJS CLI configurationExample: Basic Application
// src/main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(3000);
}
bootstrap();// src/app.module.ts
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
@Module({
imports: [],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}// src/app.controller.ts
import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get()
getHello(): string {
return this.appService.getHello();
}
}// src/app.service.ts
import { Injectable } from '@nestjs/common';
@Injectable()
export class AppService {
getHello(): string {
return 'Hello World!';
}
}Example: Running the Application
# Development mode
npm run start
# Watch mode
npm run start:dev
# Production mode
npm run start:prod
# Debug mode
npm run start:debugExample: Generating Files
# Generate a controller
nest generate controller cats
# or
nest g controller cats
# Generate a service
nest generate service cats
# or
nest g service cats
# Generate a module
nest generate module cats
# or
nest g module catsKey Points
- Use NestJS CLI for project generation and file scaffolding
- Application entry point is
main.ts - Root module is
AppModule - Controllers handle HTTP requests
- Services contain business logic
- Use
@Injectable()decorator for services - Use
@Controller()decorator for controllers - Use
@Module()decorator for modules
Guards | 守卫
官方文档: https://docs.nestjs.com/guards
Instructions
This example demonstrates how to create and use guards for authentication and authorization in NestJS.
Key Concepts
- Creating guards with
@Injectable()andCanActivate - Using guards with
@UseGuards() - Global guards
- Execution context
- Role-based access control
Example: Basic Guard
import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
import { Observable } from 'rxjs';
@Injectable()
export class AuthGuard implements CanActivate {
canActivate(
context: ExecutionContext,
): boolean | Promise<boolean> | Observable<boolean> {
const request = context.switchToHttp().getRequest();
return this.validateRequest(request);
}
private validateRequest(request: any): boolean {
// Validate request logic
return true;
}
}Example: Using Guard in Controller
import { Controller, Get, UseGuards } from '@nestjs/common';
import { AuthGuard } from './auth.guard';
@Controller('cats')
@UseGuards(AuthGuard)
export class CatsController {
@Get()
findAll(): string {
return 'This action returns all cats';
}
}Example: Route-Specific Guard
import { Controller, Get, Post, UseGuards } from '@nestjs/common';
import { AuthGuard } from './auth.guard';
@Controller('cats')
export class CatsController {
@Get()
findAll(): string {
return 'This action returns all cats';
}
@Post()
@UseGuards(AuthGuard)
create(): string {
return 'This action adds a new cat';
}
}Example: Authentication Guard
import { Injectable, CanActivate, ExecutionContext, UnauthorizedException } from '@nestjs/common';
@Injectable()
export class JwtAuthGuard implements CanActivate {
canActivate(context: ExecutionContext): boolean {
const request = context.switchToHttp().getRequest();
const token = this.extractTokenFromHeader(request);
if (!token) {
throw new UnauthorizedException();
}
try {
// Verify token
const payload = this.verifyToken(token);
request.user = payload;
return true;
} catch {
throw new UnauthorizedException();
}
}
private extractTokenFromHeader(request: any): string | undefined {
const [type, token] = request.headers.authorization?.split(' ') ?? [];
return type === 'Bearer' ? token : undefined;
}
private verifyToken(token: string): any {
// Token verification logic
return {};
}
}Example: Role-Based Guard
import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
@Injectable()
export class RolesGuard implements CanActivate {
constructor(private reflector: Reflector) {}
canActivate(context: ExecutionContext): boolean {
const requiredRoles = this.reflector.getAllAndOverride<string[]>('roles', [
context.getHandler(),
context.getClass(),
]);
if (!requiredRoles) {
return true;
}
const { user } = context.switchToHttp().getRequest();
return requiredRoles.some((role) => user.roles?.includes(role));
}
}Example: Global Guard
// main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { AuthGuard } from './auth.guard';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalGuards(new AuthGuard());
await app.listen(3000);
}
bootstrap();Example: Using Multiple Guards
import { Controller, Get, UseGuards } from '@nestjs/common';
import { AuthGuard } from './auth.guard';
import { RolesGuard } from './roles.guard';
@Controller('cats')
@UseGuards(AuthGuard, RolesGuard)
export class CatsController {
@Get()
findAll(): string {
return 'This action returns all cats';
}
}Key Points
- Guards determine if a request should be handled by the route handler
- Guards execute after middleware but before interceptors
- Use
CanActivateinterface to create guards - Use
@UseGuards()to apply guards to controllers or routes - Guards can be applied globally, controller-wide, or route-specific
- Use
ExecutionContextto access request/response objects - Guards return boolean, Promise<boolean>, or Observable<boolean>
Injection Scopes | 注入作用域
官方文档: https://docs.nestjs.com/fundamentals/injection-scopes
Instructions
Configure provider lifetimes (singleton, request, transient).
Key Concepts
- Configure provider lifetimes (singleton, request, transient).
- Use decorators to declare behavior
- Keep providers and controllers focused
Example
// example(): 示例函数,演示核心用法
function example() {
return 'injection-scopes'
}Interceptors | 拦截器
官方文档: https://docs.nestjs.com/interceptors
Instructions
This example demonstrates how to create and use interceptors for cross-cutting concerns in NestJS.
Key Concepts
- Creating interceptors with
@Injectable()andNestInterceptor - Using interceptors with
@UseInterceptors() - Global interceptors
- Execution context
- Response transformation
- Logging interceptors
Example: Basic Interceptor
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
@Injectable()
export class LoggingInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
console.log('Before...');
const now = Date.now();
return next
.handle()
.pipe(
tap(() => console.log(`After... ${Date.now() - now}ms`)),
);
}
}Example: Using Interceptor in Controller
import { Controller, Get, UseInterceptors } from '@nestjs/common';
import { LoggingInterceptor } from './logging.interceptor';
@Controller('cats')
@UseInterceptors(LoggingInterceptor)
export class CatsController {
@Get()
findAll(): string {
return 'This action returns all cats';
}
}Example: Response Transformation Interceptor
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
@Injectable()
export class TransformInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
return next.handle().pipe(
map(data => ({
statusCode: 200,
data,
timestamp: new Date().toISOString(),
})),
);
}
}Example: Timeout Interceptor
import { Injectable, NestInterceptor, ExecutionContext, CallHandler, RequestTimeoutException } from '@nestjs/common';
import { Observable, throwError, TimeoutError } from 'rxjs';
import { catchError, timeout } from 'rxjs/operators';
@Injectable()
export class TimeoutInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
return next.handle().pipe(
timeout(5000),
catchError(err => {
if (err instanceof TimeoutError) {
return throwError(() => new RequestTimeoutException());
}
return throwError(() => err);
}),
);
}
}Example: Global Interceptor
// main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { LoggingInterceptor } from './common/interceptors/logging.interceptor';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalInterceptors(new LoggingInterceptor());
await app.listen(3000);
}
bootstrap();Example: Cache Interceptor
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable, of } from 'rxjs';
import { tap } from 'rxjs/operators';
@Injectable()
export class CacheInterceptor implements NestInterceptor {
private cache = new Map();
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
const request = context.switchToHttp().getRequest();
const key = request.url;
if (this.cache.has(key)) {
return of(this.cache.get(key));
}
return next.handle().pipe(
tap(response => {
this.cache.set(key, response);
}),
);
}
}Key Points
- Interceptors execute before and after route handlers
- Use
NestInterceptorinterface to create interceptors - Use
@UseInterceptors()to apply interceptors - Interceptors can transform responses
- Interceptors can handle errors and timeouts
- Interceptors have access to ExecutionContext
- Can be applied globally, controller-wide, or route-specific
Lifecycle Events | 生命周期事件
官方文档: https://docs.nestjs.com/fundamentals/lifecycle-events
Instructions
Hook into application lifecycle events.
Key Concepts
- Hook into application lifecycle events.
- Use decorators to declare behavior
- Keep providers and controllers focused
Example
// example(): 示例函数,演示核心用法
function example() {
return 'lifecycle-events'
}Middleware | 中间件
官方文档: https://docs.nestjs.com/middleware
Instructions
This example demonstrates how to create and use middleware in NestJS.
Key Concepts
- Creating middleware classes
- Functional middleware
- Applying middleware
- Global middleware
- Route-specific middleware
Example: Class-Based Middleware
import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';
@Injectable()
export class LoggerMiddleware implements NestMiddleware {
use(req: Request, res: Response, next: NextFunction) {
console.log(`Request... ${req.method} ${req.url}`);
next();
}
}Example: Functional Middleware
import { Request, Response, NextFunction } from 'express';
export function logger(req: Request, res: Response, next: NextFunction) {
console.log(`Request... ${req.method} ${req.url}`);
next();
}Example: Applying Middleware in Module
import { Module, NestModule, MiddlewareConsumer } from '@nestjs/common';
import { LoggerMiddleware } from './common/middleware/logger.middleware';
import { CatsModule } from './cats/cats.module';
@Module({
imports: [CatsModule],
})
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer
.apply(LoggerMiddleware)
.forRoutes('cats');
}
}Example: Multiple Routes
configure(consumer: MiddlewareConsumer) {
consumer
.apply(LoggerMiddleware)
.forRoutes({ path: 'cats', method: RequestMethod.GET });
}Example: Route Exclusions
configure(consumer: MiddlewareConsumer) {
consumer
.apply(LoggerMiddleware)
.exclude(
{ path: 'cats', method: RequestMethod.GET },
{ path: 'cats', method: RequestMethod.POST },
'cats/(.*)',
)
.forRoutes(CatsController);
}Example: Global Middleware
// main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { logger } from './common/middleware/logger.middleware';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.use(logger);
await app.listen(3000);
}
bootstrap();Key Points
- Middleware executes before route handlers
- Can be class-based or functional
- Use
MiddlewareConsumerto apply middleware - Can apply to specific routes or exclude routes
- Global middleware applies to all routes
- Middleware has access to request, response, and next function
Module Reference | 模块引用
官方文档: https://docs.nestjs.com/fundamentals/module-ref
Instructions
Access providers dynamically with ModuleRef.
Key Concepts
- Access providers dynamically with ModuleRef.
- Use decorators to declare behavior
- Keep providers and controllers focused
Example
// example(): 示例函数,演示核心用法
function example() {
return 'module-ref'
}Modules | 模块
官方文档: https://docs.nestjs.com/modules
Instructions
This example demonstrates how to create and organize modules in NestJS.
Key Concepts
- Creating modules with
@Module() - Module imports, exports, and providers
- Feature modules
- Shared modules
- Global modules
- Dynamic modules
Example: Basic Module
import { Module } from '@nestjs/common';
import { CatsController } from './cats.controller';
import { CatsService } from './cats.service';
@Module({
controllers: [CatsController],
providers: [CatsService],
})
export class CatsModule {}Example: Feature Module
import { Module } from '@nestjs/common';
import { CatsController } from './cats.controller';
import { CatsService } from './cats.service';
@Module({
controllers: [CatsController],
providers: [CatsService],
exports: [CatsService], // Export to make it available to other modules
})
export class CatsModule {}Example: Importing Modules
import { Module } from '@nestjs/common';
import { CatsModule } from './cats/cats.module';
import { DogsModule } from './dogs/dogs.module';
@Module({
imports: [CatsModule, DogsModule],
})
export class AppModule {}Example: Shared Module
import { Module, Global } from '@nestjs/common';
import { CommonService } from './common.service';
@Global()
@Module({
providers: [CommonService],
exports: [CommonService],
})
export class CommonModule {}Example: Dynamic Module
import { Module, DynamicModule } from '@nestjs/common';
import { ConfigModule } from './config.module';
@Module({})
export class DatabaseModule {
static forRoot(options: DatabaseOptions): DynamicModule {
return {
module: DatabaseModule,
providers: [
{
provide: 'DATABASE_OPTIONS',
useValue: options,
},
DatabaseService,
],
exports: [DatabaseService],
};
}
}
// Usage
@Module({
imports: [DatabaseModule.forRoot({ host: 'localhost', port: 5432 })],
})
export class AppModule {}Example: Module Re-exporting
import { Module } from '@nestjs/common';
import { CatsModule } from './cats/cats.module';
import { DogsModule } from './dogs/dogs.module';
@Module({
imports: [CatsModule, DogsModule],
exports: [CatsModule, DogsModule], // Re-export modules
})
export class AnimalModule {}Key Points
- Modules organize application structure
- Use
@Module()decorator with imports, controllers, providers, exports - Feature modules encapsulate related functionality
- Shared modules export providers for reuse
- Global modules are available everywhere
- Dynamic modules accept configuration
- Export providers to make them available to other modules
- Import modules to use their exported providers
Pipes | 管道
官方文档: https://docs.nestjs.com/pipes
Instructions
This example demonstrates how to create and use pipes for validation and transformation in NestJS.
Key Concepts
- Built-in pipes
- Custom pipes
- Validation pipes
- Transformation pipes
- Using pipes globally
Example: Built-in Pipes
import { Controller, Get, Param, Query, UsePipes, ParseIntPipe, ParseBoolPipe } from '@nestjs/common';
@Controller('cats')
export class CatsController {
@Get(':id')
findOne(@Param('id', ParseIntPipe) id: number) {
return `This action returns a #${id} cat`;
}
@Get()
findAll(@Query('active', ParseBoolPipe) active: boolean) {
return `This action returns all cats (active: ${active})`;
}
}Example: Custom Validation Pipe
import { PipeTransform, Injectable, ArgumentMetadata, BadRequestException } from '@nestjs/common';
@Injectable()
export class ValidationPipe implements PipeTransform {
transform(value: any, metadata: ArgumentMetadata) {
if (!value) {
throw new BadRequestException('Value is required');
}
return value;
}
}Example: Using ValidationPipe
import { Controller, Post, Body, UsePipes, ValidationPipe } from '@nestjs/common';
import { CreateCatDto } from './dto/create-cat.dto';
@Controller('cats')
export class CatsController {
@Post()
@UsePipes(ValidationPipe)
create(@Body() createCatDto: CreateCatDto) {
return this.catsService.create(createCatDto);
}
}Example: Global Validation Pipe
// main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ValidationPipe } from '@nestjs/common';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalPipes(new ValidationPipe());
await app.listen(3000);
}
bootstrap();Example: Transformation Pipe
import { PipeTransform, Injectable, ArgumentMetadata } from '@nestjs/common';
@Injectable()
export class ParseIntPipe implements PipeTransform<string, number> {
transform(value: string, metadata: ArgumentMetadata): number {
const val = parseInt(value, 10);
if (isNaN(val)) {
throw new BadRequestException('Validation failed');
}
return val;
}
}Example: Custom Pipe with DTO
import { PipeTransform, Injectable, ArgumentMetadata, BadRequestException } from '@nestjs/common';
import { validate } from 'class-validator';
import { plainToClass } from 'class-transformer';
@Injectable()
export class ValidationPipe implements PipeTransform<any> {
async transform(value: any, { metatype }: ArgumentMetadata) {
if (!metatype || !this.toValidate(metatype)) {
return value;
}
const object = plainToClass(metatype, value);
const errors = await validate(object);
if (errors.length > 0) {
throw new BadRequestException('Validation failed');
}
return value;
}
private toValidate(metatype: Function): boolean {
const types: Function[] = [String, Boolean, Number, Array, Object];
return !types.includes(metatype);
}
}Key Points
- Pipes transform or validate input data
- Built-in pipes: ParseIntPipe, ParseBoolPipe, ParseUUIDPipe, etc.
- Use ValidationPipe for DTO validation
- Pipes can be applied globally or per route
- Custom pipes implement PipeTransform interface
- Pipes execute before route handlers
Providers | 提供者
官方文档: https://docs.nestjs.com/providers
Instructions
This example demonstrates how to create providers (services) and use dependency injection in NestJS.
Key Concepts
- Creating providers with
@Injectable() - Dependency injection
- Using providers in controllers
- Provider scopes
- Custom providers
Example: Basic Service
import { Injectable } from '@nestjs/common';
@Injectable()
export class CatsService {
private readonly cats: Cat[] = [];
findAll(): Cat[] {
return this.cats;
}
create(cat: Cat): Cat {
this.cats.push(cat);
return cat;
}
findOne(id: number): Cat {
return this.cats.find(cat => cat.id === id);
}
}Example: Using Service in Controller
import { Controller, Get, Post, Body } from '@nestjs/common';
import { CatsService } from './cats.service';
import { CreateCatDto } from './dto/create-cat.dto';
@Controller('cats')
export class CatsController {
constructor(private readonly catsService: CatsService) {}
@Get()
findAll() {
return this.catsService.findAll();
}
@Post()
create(@Body() createCatDto: CreateCatDto) {
return this.catsService.create(createCatDto);
}
}Example: Registering Provider in Module
import { Module } from '@nestjs/common';
import { CatsController } from './cats.controller';
import { CatsService } from './cats.service';
@Module({
controllers: [CatsController],
providers: [CatsService],
})
export class CatsModule {}Example: Optional Providers
import { Injectable, Optional, Inject } from '@nestjs/common';
@Injectable()
export class HttpService {
constructor(
@Optional() @Inject('HTTP_OPTIONS') private httpClient: any,
) {}
}Example: Custom Providers (useValue)
import { Module } from '@nestjs/common';
const config = {
apiKey: 'my-api-key',
timeout: 5000,
};
@Module({
providers: [
{
provide: 'CONFIG',
useValue: config,
},
],
})
export class AppModule {}Example: Custom Providers (useFactory)
import { Module } from '@nestjs/common';
@Module({
providers: [
{
provide: 'CONNECTION',
useFactory: (optionsProvider: OptionsProvider) => {
const options = optionsProvider.create();
return new DatabaseConnection(options);
},
inject: [OptionsProvider],
},
],
})
export class AppModule {}Example: Custom Providers (useClass)
import { Module } from '@nestjs/common';
@Module({
providers: [
{
provide: 'CONFIG_SERVICE',
useClass: ConfigService,
},
],
})
export class AppModule {}Example: Provider Scopes
import { Injectable, Scope } from '@nestjs/common';
@Injectable({ scope: Scope.REQUEST })
export class CatsService {
// Service instance is created for each request
}Key Points
- Use
@Injectable()decorator for providers - Providers are injected via constructor
- Register providers in module's
providersarray - Use custom providers for advanced scenarios
- Provider scopes: DEFAULT, REQUEST, TRANSIENT
- Use
@Inject()for custom tokens - Use
@Optional()for optional dependencies
Request Scoped | 请求作用域
官方文档: https://docs.nestjs.com/fundamentals/request-scoped
Instructions
Use request-scoped providers for per-request state.
Key Concepts
- Use request-scoped providers for per-request state.
- Use decorators to declare behavior
- Keep providers and controllers focused
Example
// example(): 示例函数,演示核心用法
function example() {
return 'request-scoped'
}Directives | 指令
官方文档: https://docs.nestjs.com/graphql/directives
Instructions
Use directives for schema enhancements.
Key Concepts
- Use directives for schema enhancements.
- Use decorators to declare behavior
- Keep providers and controllers focused
Example
// example(): 示例函数,演示核心用法
function example() {
return 'directives'
}Federation | 联邦
官方文档: https://docs.nestjs.com/graphql/federation
Instructions
Build federated GraphQL services.
Key Concepts
- Build federated GraphQL services.
- Use decorators to declare behavior
- Keep providers and controllers focused
Example
// example(): 示例函数,演示核心用法
function example() {
return 'federation'
}Interfaces | 接口
官方文档: https://docs.nestjs.com/graphql/interfaces
Instructions
Use GraphQL interfaces in schema.
Key Concepts
- Use GraphQL interfaces in schema.
- Use decorators to declare behavior
- Keep providers and controllers focused
Example
// example(): 示例函数,演示核心用法
function example() {
return 'interfaces'
}Migration | 迁移
官方文档: https://docs.nestjs.com/graphql/migration
Instructions
Migrate GraphQL setup between versions.
Key Concepts
- Migrate GraphQL setup between versions.
- Use decorators to declare behavior
- Keep providers and controllers focused
Example
// example(): 示例函数,演示核心用法
function example() {
return 'migration'
}Plugins | 插件
官方文档: https://docs.nestjs.com/graphql/plugins
Instructions
Configure Apollo or GraphQL plugins.
Key Concepts
- Configure Apollo or GraphQL plugins.
- Use decorators to declare behavior
- Keep providers and controllers focused
Example
// example(): 示例函数,演示核心用法
function example() {
return 'plugins'
}Quick Start | 快速开始
官方文档: https://docs.nestjs.com/graphql/quick-start
Instructions
Set up GraphQL module and basic schema.
Key Concepts
- Set up GraphQL module and basic schema.
- Use decorators to declare behavior
- Keep providers and controllers focused
Example
// example(): 示例函数,演示核心用法
function example() {
return 'quick-start'
}Resolvers | 解析器
官方文档: https://docs.nestjs.com/graphql/resolvers
Instructions
Implement resolvers for queries and mutations.
Key Concepts
- Implement resolvers for queries and mutations.
- Use decorators to declare behavior
- Keep providers and controllers focused
Example
// example(): 示例函数,演示核心用法
function example() {
return 'resolvers'
}Scalars | 标量
官方文档: https://docs.nestjs.com/graphql/scalars
Instructions
Define custom scalar types.
Key Concepts
- Define custom scalar types.
- Use decorators to declare behavior
- Keep providers and controllers focused
Example
// example(): 示例函数,演示核心用法
function example() {
return 'scalars'
}Subscriptions | 订阅
官方文档: https://docs.nestjs.com/graphql/subscriptions
Instructions
Enable real-time GraphQL subscriptions.
Key Concepts
- Enable real-time GraphQL subscriptions.
- Use decorators to declare behavior
- Keep providers and controllers focused
Example
// example(): 示例函数,演示核心用法
function example() {
return 'subscriptions'
}Unions | 联合类型
官方文档: https://docs.nestjs.com/graphql/unions
Instructions
Use union types for flexible results.
Key Concepts
- Use union types for flexible results.
- Use decorators to declare behavior
- Keep providers and controllers focused
Example
// example(): 示例函数,演示核心用法
function example() {
return 'unions'
}Basics | 基础
官方文档: https://docs.nestjs.com/microservices/basics
Instructions
Create microservice applications and message patterns.
Key Concepts
- Create microservice applications and message patterns.
- Use decorators to declare behavior
- Keep providers and controllers focused
Example
// example(): 示例函数,演示核心用法
function example() {
return 'basics'
}Custom Transport | 自定义传输层
官方文档: https://docs.nestjs.com/microservices/custom-transport
Instructions
Implement a custom transporter.
Key Concepts
- Implement a custom transporter.
- Use decorators to declare behavior
- Keep providers and controllers focused
Example
// example(): 示例函数,演示核心用法
function example() {
return 'custom-transport'
}gRPC | gRPC
官方文档: https://docs.nestjs.com/microservices/grpc
Instructions
Configure gRPC transporter.
Key Concepts
- Configure gRPC transporter.
- Use decorators to declare behavior
- Keep providers and controllers focused
Example
// example(): 示例函数,演示核心用法
function example() {
return 'grpc'
}Hybrid Application | 混合应用
官方文档: https://docs.nestjs.com/microservices/hybrid-application
Instructions
Combine HTTP and microservice apps.
Key Concepts
- Combine HTTP and microservice apps.
- Use decorators to declare behavior
- Keep providers and controllers focused
Example
// example(): 示例函数,演示核心用法
function example() {
return 'hybrid-application'
}Kafka | Kafka
官方文档: https://docs.nestjs.com/microservices/kafka
Instructions
Configure Kafka transporter.
Key Concepts
- Configure Kafka transporter.
- Use decorators to declare behavior
- Keep providers and controllers focused
Example
// example(): 示例函数,演示核心用法
function example() {
return 'kafka'
}MQTT | MQTT
官方文档: https://docs.nestjs.com/microservices/mqtt
Instructions
Configure MQTT transporter.
Key Concepts
- Configure MQTT transporter.
- Use decorators to declare behavior
- Keep providers and controllers focused
Example
// example(): 示例函数,演示核心用法
function example() {
return 'mqtt'
}NATS | NATS
官方文档: https://docs.nestjs.com/microservices/nats
Instructions
Configure NATS transporter.
Key Concepts
- Configure NATS transporter.
- Use decorators to declare behavior
- Keep providers and controllers focused
Example
// example(): 示例函数,演示核心用法
function example() {
return 'nats'
}RabbitMQ | RabbitMQ
官方文档: https://docs.nestjs.com/microservices/rabbitmq
Instructions
Configure RabbitMQ transporter.
Key Concepts
- Configure RabbitMQ transporter.
- Use decorators to declare behavior
- Keep providers and controllers focused
Example
// example(): 示例函数,演示核心用法
function example() {
return 'rabbitmq'
}Redis | Redis
官方文档: https://docs.nestjs.com/microservices/redis
Instructions
Configure Redis transporter.
Key Concepts
- Configure Redis transporter.
- Use decorators to declare behavior
- Keep providers and controllers focused
Example
// example(): 示例函数,演示核心用法
function example() {
return 'redis'
}Introduction | 简介
官方文档: https://docs.nestjs.com/openapi/introduction
Instructions
Enable Swagger/OpenAPI for NestJS.
Key Concepts
- Enable Swagger/OpenAPI for NestJS.
- Use decorators to declare behavior
- Keep providers and controllers focused
Example
// example(): 示例函数,演示核心用法
function example() {
return 'introduction'
}Mapped Types | 映射类型
官方文档: https://docs.nestjs.com/openapi/mapped-types
Instructions
Use mapped types for DTO reuse.
Key Concepts
- Use mapped types for DTO reuse.
- Use decorators to declare behavior
- Keep providers and controllers focused
Example
// example(): 示例函数,演示核心用法
function example() {
return 'mapped-types'
}Operations | 操作
官方文档: https://docs.nestjs.com/openapi/operations
Instructions
Document endpoints with decorators.
Key Concepts
- Document endpoints with decorators.
- Use decorators to declare behavior
- Keep providers and controllers focused
Example
// example(): 示例函数,演示核心用法
function example() {
return 'operations'
}Security | 安全
官方文档: https://docs.nestjs.com/openapi/security
Instructions
Add auth schemes to API docs.
Key Concepts
- Add auth schemes to API docs.
- Use decorators to declare behavior
- Keep providers and controllers focused
Example
// example(): 示例函数,演示核心用法
function example() {
return 'security'
}Types and Parameters | 类型与参数
官方文档: https://docs.nestjs.com/openapi/types-and-parameters
Instructions
Describe DTOs and parameters.
Key Concepts
- Describe DTOs and parameters.
- Use decorators to declare behavior
- Keep providers and controllers focused
Example
// example(): 示例函数,演示核心用法
function example() {
return 'types-and-parameters'
}Controllers | 控制器
官方文档: https://docs.nestjs.com/controllers
Instructions
Define request handlers and route mappings with decorators.
Key Concepts
- Define request handlers and route mappings with decorators.
- Use decorators to declare behavior
- Keep providers and controllers focused
Example
// example(): 示例函数,演示核心用法
function example() {
return 'controllers'
}Custom Decorators | 自定义装饰器
官方文档: https://docs.nestjs.com/custom-decorators
Instructions
This example demonstrates how to create custom decorators in NestJS to improve code readability and reusability.
Key Concepts
- Creating parameter decorators with
createParamDecorator() - Creating method decorators
- Creating class decorators
- Combining decorators
- Using decorators with metadata
Example: Parameter Decorator
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
// User(): 自定义参数装饰器,从请求中提取用户信息
export const User = createParamDecorator(
(data: unknown, ctx: ExecutionContext) => {
const request = ctx.switchToHttp().getRequest();
return request.user;
},
);
// Usage in controller
@Controller('profile')
export class ProfileController {
@Get()
getProfile(@User() user: any) {
return user;
}
}Example: Method Decorator
import { SetMetadata } from '@nestjs/common';
// Roles(): 自定义方法装饰器,设置角色元数据
export const Roles = (...roles: string[]) => SetMetadata('roles', roles);
// Usage in controller
@Controller('admin')
export class AdminController {
@Get('users')
@Roles('admin', 'moderator')
getUsers() {
return [];
}
}Example: Combining Decorators
import { applyDecorators, UseGuards, SetMetadata } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
// Auth(): 组合装饰器,同时应用守卫和元数据
export function Auth(...roles: string[]) {
return applyDecorators(
SetMetadata('roles', roles),
UseGuards(AuthGuard('jwt')),
);
}
// Usage
@Controller('protected')
export class ProtectedController {
@Get('data')
@Auth('admin')
getData() {
return { data: 'protected' };
}
}Example: Class Decorator
import { SetMetadata } from '@nestjs/common';
// ApiVersion(): 自定义类装饰器,设置 API 版本
export const ApiVersion = (version: string) => SetMetadata('apiVersion', version);
// Usage
@ApiVersion('V1')
@Controller('users')
export class UsersController {
@Get()
findAll() {
return [];
}
}Key Points
- Use
createParamDecorator()for parameter decorators - Use
SetMetadata()to attach metadata to handlers - Use
applyDecorators()to combine multiple decorators - Custom decorators improve code readability and reusability
- Decorators can access execution context and request/response objects
Exception Filters | 异常过滤器
官方文档: https://docs.nestjs.com/exception-filters
Instructions
Handle and transform exceptions globally or per-route.
Key Concepts
- Handle and transform exceptions globally or per-route.
- Use decorators to declare behavior
- Keep providers and controllers focused
Example
// example(): 示例函数,演示核心用法
function example() {
return 'exception-filters'
}Guards | 守卫
官方文档: https://docs.nestjs.com/guards
Instructions
Control route access using guards and metadata.
Key Concepts
- Control route access using guards and metadata.
- Use decorators to declare behavior
- Keep providers and controllers focused
Example
// example(): 示例函数,演示核心用法
function example() {
return 'guards'
}Interceptors | 拦截器
官方文档: https://docs.nestjs.com/interceptors
Instructions
Wrap request/response lifecycle for logging, caching, and transforms.
Key Concepts
- Wrap request/response lifecycle for logging, caching, and transforms.
- Use decorators to declare behavior
- Keep providers and controllers focused
Example
// example(): 示例函数,演示核心用法
function example() {
return 'interceptors'
}Introduction | 介绍
官方文档: https://docs.nestjs.com/
Instructions
NestJS is a progressive Node.js framework for building efficient, reliable and scalable server-side applications.
Key Concepts
- NestJS is a progressive Node.js framework for building efficient, reliable and scalable server-side applications.
- Use decorators to declare behavior
- Keep providers and controllers focused
Example
// example(): 示例函数,演示核心用法
function example() {
return 'introduction'
}Middleware | 中间件
官方文档: https://docs.nestjs.com/middleware
Instructions
Apply middleware for request/response processing.
Key Concepts
- Apply middleware for request/response processing.
- Use decorators to declare behavior
- Keep providers and controllers focused
Example
// example(): 示例函数,演示核心用法
function example() {
return 'middleware'
}Modules | 模块
官方文档: https://docs.nestjs.com/modules
Instructions
Organize application structure using modules.
Key Concepts
- Organize application structure using modules.
- Use decorators to declare behavior
- Keep providers and controllers focused
Example
// example(): 示例函数,演示核心用法
function example() {
return 'modules'
}Pipes | 管道
官方文档: https://docs.nestjs.com/pipes
Instructions
Transform and validate data at the route handler boundary.
Key Concepts
- Transform and validate data at the route handler boundary.
- Use decorators to declare behavior
- Keep providers and controllers focused
Example
// example(): 示例函数,演示核心用法
function example() {
return 'pipes'
}Providers | 提供者
官方文档: https://docs.nestjs.com/providers
Instructions
Use providers for business logic and dependency injection.
Key Concepts
- Use providers for business logic and dependency injection.
- Use decorators to declare behavior
- Keep providers and controllers focused
Example
// example(): 示例函数,演示核心用法
function example() {
return 'providers'
}CQRS | CQRS
官方文档: https://docs.nestjs.com/recipes/cqrs
Instructions
Implement CQRS patterns with NestJS.
Key Concepts
- Implement CQRS patterns with NestJS.
- Use decorators to declare behavior
- Keep providers and controllers focused
Example
// example(): 示例函数,演示核心用法
function example() {
return 'cqrs'
}MikroORM | MikroORM
官方文档: https://docs.nestjs.com/recipes/mikroorm
Instructions
Use MikroORM in NestJS.
Key Concepts
- Use MikroORM in NestJS.
- Use decorators to declare behavior
- Keep providers and controllers focused
Example
// example(): 示例函数,演示核心用法
function example() {
return 'mikroorm'
}Terminus | Terminus
官方文档: https://docs.nestjs.com/recipes/terminus
Instructions
Add health checks with Terminus.
Key Concepts
- Add health checks with Terminus.
- Use decorators to declare behavior
- Keep providers and controllers focused
Example
// example(): 示例函数,演示核心用法
function example() {
return 'terminus'
}Authentication | 认证
官方文档: https://docs.nestjs.com/security/authentication
Instructions
Implement authentication strategies and guards.
Key Concepts
- Implement authentication strategies and guards.
- Use decorators to declare behavior
- Keep providers and controllers focused
Example
// example(): 示例函数,演示核心用法
function example() {
return 'authentication'
}Authorization | 授权
官方文档: https://docs.nestjs.com/security/authorization
Instructions
Enforce permissions and roles.
Key Concepts
- Enforce permissions and roles.
- Use decorators to declare behavior
- Keep providers and controllers focused
Example
// example(): 示例函数,演示核心用法
function example() {
return 'authorization'
}CORS | 跨域
官方文档: https://docs.nestjs.com/security/cors
Instructions
Configure CORS for HTTP servers.
Key Concepts
- Configure CORS for HTTP servers.
- Use decorators to declare behavior
- Keep providers and controllers focused
Example
// example(): 示例函数,演示核心用法
function example() {
return 'cors'
}Helmet | 安全头
官方文档: https://docs.nestjs.com/security/helmet
Instructions
Harden HTTP headers with Helmet.
Key Concepts
- Harden HTTP headers with Helmet.
- Use decorators to declare behavior
- Keep providers and controllers focused
Example
// example(): 示例函数,演示核心用法
function example() {
return 'helmet'
}Rate Limiting | 限流
官方文档: https://docs.nestjs.com/security/rate-limiting
Instructions
Protect APIs with throttling.
Key Concepts
- Protect APIs with throttling.
- Use decorators to declare behavior
- Keep providers and controllers focused
Example
// example(): 示例函数,演示核心用法
function example() {
return 'rate-limiting'
}Caching | 缓存
官方文档: https://docs.nestjs.com/techniques/caching
Instructions
Add cache manager to improve response performance.
Key Concepts
- Add cache manager to improve response performance.
- Use decorators to declare behavior
- Keep providers and controllers focused
Example
// example(): 示例函数,演示核心用法
function example() {
return 'caching'
}Configuration | 配置管理
官方文档: https://docs.nestjs.com/techniques/configuration
Instructions
Manage environment configuration with ConfigModule.
Key Concepts
- Manage environment configuration with ConfigModule.
- Use decorators to declare behavior
- Keep providers and controllers focused
Example
// example(): 示例函数,演示核心用法
function example() {
return 'configuration'
}Database | 数据库
官方文档: https://docs.nestjs.com/techniques/database
Instructions
Integrate relational databases with NestJS.
Key Concepts
- Integrate relational databases with NestJS.
- Use decorators to declare behavior
- Keep providers and controllers focused
Example
// example(): 示例函数,演示核心用法
function example() {
return 'database'
}Events | 事件
官方文档: https://docs.nestjs.com/techniques/events
Instructions
Implement event-driven patterns with EventEmitterModule.
Key Concepts
- Implement event-driven patterns with EventEmitterModule.
- Use decorators to declare behavior
- Keep providers and controllers focused
Example
// example(): 示例函数,演示核心用法
function example() {
return 'events'
}File Upload | 文件上传
官方文档: https://docs.nestjs.com/techniques/file-upload
Instructions
Handle file uploads with Multer interceptors.
Key Concepts
- Handle file uploads with Multer interceptors.
- Use decorators to declare behavior
- Keep providers and controllers focused
Example
// example(): 示例函数,演示核心用法
function example() {
return 'file-upload'
}Logging | 日志
官方文档: https://docs.nestjs.com/techniques/logger
Instructions
Customize logging with Logger or custom logger.
Key Concepts
- Customize logging with Logger or custom logger.
- Use decorators to declare behavior
- Keep providers and controllers focused
Example
// example(): 示例函数,演示核心用法
function example() {
return 'logger'
}MongoDB | MongoDB
官方文档: https://docs.nestjs.com/techniques/mongodb
Instructions
Use MongoDB integration in NestJS.
Key Concepts
- Use MongoDB integration in NestJS.
- Use decorators to declare behavior
- Keep providers and controllers focused
Example
// example(): 示例函数,演示核心用法
function example() {
return 'mongodb'
}Mongoose | Mongoose
官方文档: https://docs.nestjs.com/techniques/mongoose
Instructions
Integrate Mongoose models and schemas.
Key Concepts
- Integrate Mongoose models and schemas.
- Use decorators to declare behavior
- Keep providers and controllers focused
Example
// example(): 示例函数,演示核心用法
function example() {
return 'mongoose'
}Prisma | Prisma
官方文档: https://docs.nestjs.com/recipes/prisma
Instructions
Use Prisma in NestJS applications.
Key Concepts
- Use Prisma in NestJS applications.
- Use decorators to declare behavior
- Keep providers and controllers focused
Example
// example(): 示例函数,演示核心用法
function example() {
return 'prisma'
}Queues | 队列
官方文档: https://docs.nestjs.com/techniques/queues
Instructions
Process background jobs with queues (Bull/BullMQ).
Key Concepts
- Process background jobs with queues (Bull/BullMQ).
- Use decorators to declare behavior
- Keep providers and controllers focused
Example
// example(): 示例函数,演示核心用法
function example() {
return 'queues'
}Sequelize | Sequelize
官方文档: https://docs.nestjs.com/techniques/sequelize
Instructions
Use Sequelize ORM with NestJS.
Key Concepts
- Use Sequelize ORM with NestJS.
- Use decorators to declare behavior
- Keep providers and controllers focused
Example
// example(): 示例函数,演示核心用法
function example() {
return 'sequelize'
}Serialization | 序列化
官方文档: https://docs.nestjs.com/techniques/serialization
Instructions
Control response serialization with ClassSerializerInterceptor.
Key Concepts
- Control response serialization with ClassSerializerInterceptor.
- Use decorators to declare behavior
- Keep providers and controllers focused
Example
// example(): 示例函数,演示核心用法
function example() {
return 'serialization'
}Streaming Files | 文件流
官方文档: https://docs.nestjs.com/techniques/streaming-files
Instructions
Stream files using StreamableFile.
Key Concepts
- Stream files using StreamableFile.
- Use decorators to declare behavior
- Keep providers and controllers focused
Example
// example(): 示例函数,演示核心用法
function example() {
return 'streaming-files'
}Task Scheduling | 定时任务
官方文档: https://docs.nestjs.com/techniques/task-scheduling
Instructions
Schedule jobs with ScheduleModule and cron decorators.
Key Concepts
- Schedule jobs with ScheduleModule and cron decorators.
- Use decorators to declare behavior
- Keep providers and controllers focused
Example
// example(): 示例函数,演示核心用法
function example() {
return 'task-scheduling'
}Validation | 数据校验
官方文档: https://docs.nestjs.com/techniques/validation
Instructions
Validate DTOs using ValidationPipe and class-validator.
Key Concepts
- Validate DTOs using ValidationPipe and class-validator.
- Use decorators to declare behavior
- Keep providers and controllers focused
Example
// example(): 示例函数,演示核心用法
function example() {
return 'validation'
}E2E Testing | 端到端测试
官方文档: https://docs.nestjs.com/fundamentals/testing
Instructions
Write end-to-end tests with Supertest.
Key Concepts
- Write end-to-end tests with Supertest.
- Use decorators to declare behavior
- Keep providers and controllers focused
Example
// example(): 示例函数,演示核心用法
function example() {
return 'e2e-testing'
}Unit Testing | 单元测试
官方文档: https://docs.nestjs.com/fundamentals/testing
Instructions
Write unit tests using TestingModule.
Key Concepts
- Write unit tests using TestingModule.
- Use decorators to declare behavior
- Keep providers and controllers focused
Example
// example(): 示例函数,演示核心用法
function example() {
return 'unit-testing'
}Adapters | 适配器
官方文档: https://docs.nestjs.com/websockets/adapters
Instructions
Customize WebSocket adapters.
Key Concepts
- Customize WebSocket adapters.
- Use decorators to declare behavior
- Keep providers and controllers focused
Example
// example(): 示例函数,演示核心用法
function example() {
return 'adapters'
}Exception Filters | 异常过滤器
官方文档: https://docs.nestjs.com/websockets/exception-filters
Instructions
Handle WebSocket exceptions.
Key Concepts
- Handle WebSocket exceptions.
- Use decorators to declare behavior
- Keep providers and controllers focused
Example
// example(): 示例函数,演示核心用法
function example() {
return 'exception-filters'
}Gateways | 网关
官方文档: https://docs.nestjs.com/websockets/gateways
Instructions
Create WebSocket gateways and handlers.
Key Concepts
- Create WebSocket gateways and handlers.
- Use decorators to declare behavior
- Keep providers and controllers focused
Example
// example(): 示例函数,演示核心用法
function example() {
return 'gateways'
}Guards | 守卫
官方文档: https://docs.nestjs.com/websockets/guards
Instructions
Protect WebSocket handlers with guards.
Key Concepts
- Protect WebSocket handlers with guards.
- Use decorators to declare behavior
- Keep providers and controllers focused
Example
// example(): 示例函数,演示核心用法
function example() {
return 'guards'
}Interceptors | 拦截器
官方文档: https://docs.nestjs.com/websockets/interceptors
Instructions
Use interceptors around WebSocket events.
Key Concepts
- Use interceptors around WebSocket events.
- Use decorators to declare behavior
- Keep providers and controllers focused
Example
// example(): 示例函数,演示核心用法
function example() {
return 'interceptors'
}
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Controller Template | 控制器模板
Basic Controller Template
import { Controller, Get, Post, Put, Delete, Body, Param, Query, UseGuards } from '@nestjs/common';
import { ServiceName } from './service-name.service';
import { CreateDto } from './dto/create-dto.dto';
import { UpdateDto } from './dto/update-dto.dto';
import { AuthGuard } from '../auth/guards/auth.guard';
@Controller('resource-name')
@UseGuards(AuthGuard)
export class ResourceNameController {
constructor(private readonly serviceName: ServiceName) {}
@Get()
findAll(@Query('limit') limit?: number) {
return this.serviceName.findAll(limit);
}
@Get(':id')
findOne(@Param('id') id: string) {
return this.serviceName.findOne(id);
}
@Post()
create(@Body() createDto: CreateDto) {
return this.serviceName.create(createDto);
}
@Put(':id')
update(@Param('id') id: string, @Body() updateDto: UpdateDto) {
return this.serviceName.update(id, updateDto);
}
@Delete(':id')
remove(@Param('id') id: string) {
return this.serviceName.remove(id);
}
}Controller with Pagination
import { Controller, Get, Query } from '@nestjs/common';
import { ServiceName } from './service-name.service';
@Controller('resource-name')
export class ResourceNameController {
constructor(private readonly serviceName: ServiceName) {}
@Get()
findAll(
@Query('page') page: number = 1,
@Query('limit') limit: number = 10,
) {
return this.serviceName.findAll(page, limit);
}
}Controller Template | 控制器模板
import { Controller, Get } from '@nestjs/common'
// AppController: 示例控制器
@Controller('health')
export class AppController {
// getHealth(): 返回健康状态
@Get()
getHealth() {
return { status: 'ok' }
}
}DTO Template | DTO 模板
Basic DTO Template
import { IsString, IsInt, Min, Max, IsOptional, IsEmail, IsBoolean } from 'class-validator';
export class CreateResourceDto {
@IsString()
name: string;
@IsInt()
@Min(0)
@Max(100)
age: number;
@IsEmail()
@IsOptional()
email?: string;
@IsBoolean()
@IsOptional()
isActive?: boolean;
}Update DTO Template
import { IsString, IsInt, Min, Max, IsOptional } from 'class-validator';
export class UpdateResourceDto {
@IsString()
@IsOptional()
name?: string;
@IsInt()
@Min(0)
@Max(100)
@IsOptional()
age?: number;
}DTO with Nested Objects
import { IsString, ValidateNested, IsObject } from 'class-validator';
import { Type } from 'class-transformer';
class AddressDto {
@IsString()
street: string;
@IsString()
city: string;
}
export class CreateUserDto {
@IsString()
name: string;
@ValidateNested()
@Type(() => AddressDto)
@IsObject()
address: AddressDto;
}DTO with Arrays
import { IsArray, IsString, ArrayMinSize } from 'class-validator';
export class CreateResourceDto {
@IsString()
name: string;
@IsArray()
@IsString({ each: true })
@ArrayMinSize(1)
tags: string[];
}Exception Filter Template | 异常过滤器模板
import { ExceptionFilter, Catch, ArgumentsHost, HttpException } from '@nestjs/common'
// HttpExceptionFilter: 处理 HTTP 异常
@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
// catch(): 捕获异常并返回响应
catch(exception: HttpException, host: ArgumentsHost) {
const ctx = host.switchToHttp()
const response = ctx.getResponse()
response.status(exception.getStatus()).json({
message: exception.message
})
}
}Guard Template | 守卫模板
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common'
// AuthGuard: 示例权限守卫
@Injectable()
export class AuthGuard implements CanActivate {
// canActivate(): 访问控制逻辑
canActivate(context: ExecutionContext) {
const request = context.switchToHttp().getRequest()
return Boolean(request.user)
}
}Interceptor Template | 拦截器模板
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common'
import { Observable } from 'rxjs'
import { map } from 'rxjs/operators'
// TransformInterceptor: 统一响应结构
@Injectable()
export class TransformInterceptor implements NestInterceptor {
// intercept(): 拦截并转换响应
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
return next.handle().pipe(map(data => ({ data })))
}
}Middleware Template | 中间件模板
import { Injectable, NestMiddleware } from '@nestjs/common'
import { Request, Response, NextFunction } from 'express'
// LoggerMiddleware: 记录请求日志
@Injectable()
export class LoggerMiddleware implements NestMiddleware {
// use(): 中间件执行逻辑
use(req: Request, res: Response, next: NextFunction) {
console.log(req.method, req.originalUrl)
next()
}
}Module Template | 模块模板
import { Module } from '@nestjs/common'
import { AppController } from './app.controller'
import { AppService } from './app.service'
// AppModule: 应用模块
@Module({
controllers: [AppController],
providers: [AppService]
})
export class AppModule {}Pipe Template | 管道模板
import { PipeTransform, Injectable, BadRequestException } from '@nestjs/common'
// ParseIdPipe: 将字符串 id 转为数字
@Injectable()
export class ParseIdPipe implements PipeTransform {
// transform(): 管道转换逻辑
transform(value: string) {
const parsed = Number(value)
if (Number.isNaN(parsed)) {
throw new BadRequestException('Invalid id')
}
return parsed
}
}Project Structure Template | 项目结构模板
Standard NestJS Project Structure
project-name/
├── src/
│ ├── main.ts # Application entry point
│ ├── app.module.ts # Root module
│ ├── app.controller.ts # Root controller
│ ├── app.service.ts # Root service
│ ├── common/ # Shared utilities
│ │ ├── decorators/
│ │ ├── filters/
│ │ ├── guards/
│ │ ├── interceptors/
│ │ └── pipes/
│ ├── config/ # Configuration
│ │ └── configuration.ts
│ ├── database/ # Database configuration
│ │ └── database.module.ts
│ └── modules/ # Feature modules
│ ├── auth/
│ │ ├── auth.module.ts
│ │ ├── auth.controller.ts
│ │ ├── auth.service.ts
│ │ ├── strategies/
│ │ └── guards/
│ ├── users/
│ │ ├── users.module.ts
│ │ ├── users.controller.ts
│ │ ├── users.service.ts
│ │ ├── entities/
│ │ ├── dto/
│ │ └── users.controller.spec.ts
│ └── cats/
│ ├── cats.module.ts
│ ├── cats.controller.ts
│ ├── cats.service.ts
│ ├── entities/
│ ├── dto/
│ └── cats.controller.spec.ts
├── test/ # E2E tests
│ ├── app.e2e-spec.ts
│ └── jest-e2e.json
├── .env # Environment variables
├── .gitignore
├── nest-cli.json # NestJS CLI configuration
├── package.json
├── tsconfig.json # TypeScript configuration
└── README.mdModule Structure
module-name/
├── module-name.module.ts # Module definition
├── module-name.controller.ts # Controller
├── module-name.service.ts # Service
├── entities/ # Database entities
│ └── entity-name.entity.ts
├── dto/ # Data Transfer Objects
│ ├── create-dto.dto.ts
│ └── update-dto.dto.ts
├── interfaces/ # TypeScript interfaces
│ └── interface-name.interface.ts
└── module-name.controller.spec.ts # Unit testsProvider Template | 提供者模板
import { Injectable } from '@nestjs/common'
// AppService: 示例服务
@Injectable()
export class AppService {
// getMessage(): 返回示例消息
getMessage() {
return 'hello'
}
}Service Template | 服务模板
Basic Service Template
import { Injectable } from '@nestjs/common';
import { CreateDto } from './dto/create-dto.dto';
import { UpdateDto } from './dto/update-dto.dto';
@Injectable()
export class ResourceNameService {
private items: any[] = [];
findAll(): any[] {
return this.items;
}
findOne(id: string): any {
return this.items.find(item => item.id === id);
}
create(createDto: CreateDto): any {
const item = {
id: Date.now().toString(),
...createDto,
};
this.items.push(item);
return item;
}
update(id: string, updateDto: UpdateDto): any {
const item = this.findOne(id);
if (item) {
Object.assign(item, updateDto);
}
return item;
}
remove(id: string): void {
const index = this.items.findIndex(item => item.id === id);
if (index > -1) {
this.items.splice(index, 1);
}
}
}Service with Repository
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { EntityName } from './entities/entity-name.entity';
import { CreateDto } from './dto/create-dto.dto';
import { UpdateDto } from './dto/update-dto.dto';
@Injectable()
export class ResourceNameService {
constructor(
@InjectRepository(EntityName)
private repository: Repository<EntityName>,
) {}
async findAll(): Promise<EntityName[]> {
return this.repository.find();
}
async findOne(id: string): Promise<EntityName> {
return this.repository.findOne({ where: { id } });
}
async create(createDto: CreateDto): Promise<EntityName> {
const entity = this.repository.create(createDto);
return this.repository.save(entity);
}
async update(id: string, updateDto: UpdateDto): Promise<EntityName> {
await this.repository.update(id, updateDto);
return this.findOne(id);
}
async remove(id: string): Promise<void> {
await this.repository.delete(id);
}
}