
NestJS 架构
控制器处理 HTTP 请求。服务处理业务逻辑。模块组织一切。
控制器 + 服务 + 依赖注入
@Controller('users')
export class UsersController {
constructor(private readonly usersService: UsersService) {}
@Get()
@UseGuards(JwtAuthGuard)
findAll() { return this.usersService.findAll() }
@Post()
@HttpCode(HttpStatus.CREATED)
create(@Body() dto: CreateUserDto) { return this.usersService.create(dto) }
@Get(':id')
findOne(@Param('id', ParseIntPipe) id: number) { return this.usersService.findOne(id) }
@Delete(':id')
@UseGuards(JwtAuthGuard)
remove(@Param('id', ParseIntPipe) id: number, @CurrentUser() user: User) {
return this.usersService.remove(id, user.id)
}
}
DTO 验证
import { IsEmail, IsString, MinLength } from 'class-validator'
import { Transform } from 'class-transformer'
export class CreateUserDto {
@IsEmail()
@Transform(({ value }) => value.toLowerCase())
email: string
@IsString()
@MinLength(8)
password: string
}
// main.ts: 全局验证
app.useGlobalPipes(new ValidationPipe({ whitelist: true, transform: true, forbidNonWhitelisted: true }))
自定义装饰器
export const CurrentUser = createParamDecorator(
(field: string, ctx: ExecutionContext) => {
const req = ctx.switchToHttp().getRequest()
return field ? req.user?.[field] : req.user
}
)
响应拦截器
@Injectable()
export class ResponseInterceptor implements NestInterceptor {
intercept(ctx: ExecutionContext, next: CallHandler) {
return next.handle().pipe(
map(data => ({ success: true, data, timestamp: new Date().toISOString() }))
)
}
}
-> 使用 JSON Viewer 格式化 API 响应。