关于 nestjs
面向使用 NestJS 和 TypeScript 构建 Node.js 应用的学习与参考技能,覆盖应用结构、常见后端模式,以及从 CRUD 到微服务和测试的主题。
主要功能
- 01模块、控制器与服务
- 02依赖注入模式
- 03DTO 验证与守卫
- 04数据库与身份验证模式
- 05微服务、GraphQL 与 WebSockets
- 06故障排查与测试模板
适用场景
- 01组织 NestJS 后端结构
- 02添加验证与身份验证
- 03了解微服务模式
- 04编写服务单元测试
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ pluginagentmarketplace/ custom-plugin-nodejs --skill nestjs安装后在 Claude Code 中输入/nestjs确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
assets/config.yamlschema.jsonreferences/GUIDE.mdPATTERNS.mdscripts/validate.py详细介绍
NestJS 框架技能
掌握 NestJS,使用 TypeScript、依赖注入和企业级模式构建可扩展、易维护的 Node.js 应用程序。
快速入门
分 4 步创建 NestJS 应用:
- 创建项目 -
nest new project-name - 定义模块 - 组织功能
- 添加控制器 - 处理请求
- 创建服务 - 编写业务逻辑
核心概念
模块结构
// users/users.module.ts
import { Module } from '@nestjs/common';
import { UsersController } from './users.controller';
import { UsersService } from './users.service';
import { TypeOrmModule } from '@nestjs/typeorm';
import { User } from './entities/user.entity';
@Module({
imports: [TypeOrmModule.forFeature([User])],
controllers: [UsersController],
providers: [UsersService],
exports: [UsersService] // Make available to other modules
})
export class UsersModule {}
控制器
// users/users.controller.ts
import { Controller, Get, Post, Body, Param, Query, UseGuards } from '@nestjs/common';
import { UsersService } from './users.service';
import { CreateUserDto } from './dto/create-user.dto';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { ApiTags, ApiOperation, ApiBearerAuth } from '@nestjs/swagger';
@ApiTags('users')
@Controller('users')
export class UsersController {
constructor(private readonly usersService: UsersService) {}
@Get()
@ApiOperation({ summary: 'Get all users' })
findAll(@Query('page') page = 1, @Query('limit') limit = 10) {
return this.usersService.findAll(page, limit);
}
@Get(':id')
findOne(@Param('id') id: string) {
return this.usersService.findOne(id);
}
@Post()
@UseGuards(JwtAuthGuard)
@ApiBearerAuth()
create(@Body() createUserDto: CreateUserDto) {
return this.usersService.create(createUserDto);
}
}
使用依赖注入的服务
// users/users.service.ts
import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from './entities/user.entity';
@Injectable()
export class UsersService {
constructor(
@InjectRepository(User)
private usersRepository: Repository<User>
) {}
async findAll(page: number, limit: number) {
const [users, total] = await this.usersRepository.findAndCount({
skip: (page - 1) * limit,
take: limit
});
return { data: users, total, page, limit };
}
async findOne(id: string): Promise<User> {
const user = await this.usersRepository.findOne({ where: { id } });
if (!user) {
throw new NotFoundException(`User #${id} not found`);
}
return user;
}
async create(createUserDto: CreateUserDto): Promise<User> {
const user = this.usersRepository.create(createUserDto);
return this.usersRepository.save(user);
}
}
学习路径
初学者(2-3 周)
- ✅ NestJS CLI 和项目结构
- ✅ 模块、控制器、服务
- ✅ 依赖注入基础
- ✅ 基本 CRUD 操作
中级(4-6 周)
- ✅ 守卫、管道、拦截器
- ✅ TypeORM/Prisma 集成
- ✅ JWT 身份验证
- ✅ 使用 class-validator 进行验证
高级(8-12 周)
- ✅ 使用传输机制构建微服务
- ✅ 使用 NestJS 构建 GraphQL
- ✅ WebSockets(网关)
- ✅ 测试策略
使用 DTO 验证
// dto/create-user.dto.ts
import { IsEmail, IsString, MinLength, IsOptional } from 'class-validator';
import { ApiProperty } from '@nestjs/swagger';
export class CreateUserDto {
@ApiProperty({ example: '[email protected]' })
@IsEmail()
email: string;
@ApiProperty({ example: 'John Doe' })
@IsString()
@MinLength(2)
name: string;
@ApiProperty({ example: 'password123' })
@IsString()
@MinLength(8)
password: string;
@ApiProperty({ required: false })
@IsOptional()
@IsString()
avatar?: string;
}
用于身份验证的守卫
// auth/guards/jwt-auth.guard.ts
import { Injectable, ExecutionContext } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {
canActivate(context: ExecutionContext) {
return super.canActivate(context);
}
}
// auth/guards/roles.guard.ts
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.get<string[]>('roles', context.getHandler());
if (!requiredRoles) return true;
const { user } = context.switchToHttp().getRequest();
return requiredRoles.some(role => user.roles?.includes(role));
}
}
异常筛选器
// filters/http-exception.filter.ts
import { ExceptionFilter, Catch, ArgumentsHost, HttpException } from '@nestjs/common';
import { 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 status = exception.getStatus();
response.status(status).json({
success: false,
statusCode: status,
message: exception.message,
timestamp: new Date().toISOString()
});
}
}
微服务传输机制
// main.ts for microservice
import { NestFactory } from '@nestjs/core';
import { Transport, MicroserviceOptions } from '@nestjs/microservices';
const app = await NestFactory.createMicroservice<MicroserviceOptions>(
AppModule,
{
transport: Transport.RMQ,
options: {
urls: ['amqp://localhost:5672'],
queue: 'orders_queue',
queueOptions: { durable: true }
}
}
);
await app.listen();
单元测试模板
describe('UsersService', () => {
let service: UsersService;
let repository: Repository<User>;
beforeEach(async () => {
const module = await Test.createTestingModule({
providers: [
UsersService,
{
provide: getRepositoryToken(User),
useValue: {
findOne: jest.fn(),
create: jest.fn(),
save: jest.fn()
}
}
]
}).compile();
service = module.get<UsersService>(UsersService);
repository = module.get<Repository<User>>(getRepositoryToken(User));
});
it('should find user by id', async () => {
const user = { id: '1', name: 'John' };
jest.spyOn(repository, 'findOne').mockResolvedValue(user as User);
expect(await service.findOne('1')).toEqual(user);
});
});
故障排查
| 问题 | 原因 | 解决方案 |
|---|---|---|
| 循环依赖 | 模块导入 | 使用 forwardRef() |
| 找不到注入令牌 | 缺少提供者 | 添加到模块的 providers 中 |
| 验证不起作用 | 缺少管道 | 全局添加 ValidationPipe |
| 守卫未触发 | 顺序错误 | 正确使用 @UseGuards |
适用场景
在以下情况下使用 NestJS:
- 构建企业级 Node.js 应用程序
- 需要具备强类型的 TypeScript
- 需要依赖注入
- 构建微服务
- 需要 OpenAPI 文档
相关技能
- Express REST API(底层框架)
- TypeScript(语言)
- GraphQL(REST 的替代方案)
- Microservices(分布式系统)
资源
评论
支持 Markdown