Nestjs请求生命周期

一、请求生命周期全景图

image-20250923151309205

二、 详细执行流程图

image-20250923154406299

三、 各组件详细说明

3.1. 中间件 (Middleware)

阶段: 请求进入阶段
作用: 处理HTTP请求的预处理

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
// 日志中间件示例
@Injectable()
export class LoggingMiddleware implements NestMiddleware {
  use(req: Request, res: Response, next: NextFunction) {
    console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
    next(); // 必须调用next()继续流程
  }
}

// 注册方式
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(LoggingMiddleware)
      .forRoutes('*'); // 应用到所有路由
  }
}

3.2. 守卫 (Guards)

阶段: 请求进入阶段
作用: 权限控制和访问限制

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
// JWT守卫示例
@Injectable()
export class JwtAuthGuard implements CanActivate {
  canActivate(context: ExecutionContext): boolean {
    const request = context.switchToHttp().getRequest();
    const token = request.headers.authorization?.split(' ')[1];
    
    if (!token) throw new UnauthorizedException();
    
    // 验证token逻辑
    return this.validateToken(token);
  }
}

// 使用方式
@Controller('users')
@UseGuards(JwtAuthGuard) // 控制器级别
export class UserController {
  @Get('profile')
  @UseGuards(RolesGuard) // 路由级别 - 叠加使用
  getProfile() { ... }
}

3.3. 拦截器 (Interceptors)

特点: 贯穿请求和响应阶段

1. 请求前拦截器

1
2
3
4
5
6
7
8
9
@Injectable()
export class LoggingInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler) {
    console.log('请求前...');
    const now = Date.now();
    
    return next.handle().pipe(...); // 继续处理
  }
}

2. 响应后拦截器

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
@Injectable()
export class TransformInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler) {
    return next.handle().pipe(
      map(data => ({
        success: true,
        timestamp: new Date().toISOString(),
        data: this.transformKeys(data) // 蛇形转驼峰
      }))
    );
  }
  
  private transformKeys(obj: any) {
    // online_icon → onlineIcon 转换逻辑
    if (Array.isArray(obj)) return obj.map(item => this.transformKeys(item));
    if (obj && typeof obj === 'object') {
      return Object.keys(obj).reduce((acc, key) => {
        const camelKey = key.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase());
        acc[camelKey] = this.transformKeys(obj[key]);
        return acc;
      }, {});
    }
    return obj;
  }
}

3.4. 管道 (Pipes)

阶段: 请求进入阶段
作用: 数据验证和转换(只处理输入数据)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
// 验证管道
@Injectable()
export class ValidationPipe implements PipeTransform {
  transform(value: any, metadata: ArgumentMetadata) {
    // 只处理进入控制器的数据
    if (metadata.type === 'body') {
      return this.validate(value); // DTO验证
    }
    return value;
  }
}

// 使用方式
@Post('users')
createUser(@Body(ValidationPipe) createUserDto: CreateUserDto) {
  // createUserDto 已经过验证和转换
  return this.userService.create(createUserDto);
}

3.5. 异常过滤器 (Exception Filters)

阶段: 响应返回阶段(异常发生时) 作用: 统一异常处理

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const status = exception.getStatus();
    
    response.status(status).json({
      statusCode: status,
      timestamp: new Date().toISOString(),
      message: exception.message,
    });
  }
}

// 使用方式
@Controller('users')
@UseFilters(HttpExceptionFilter)
export class UserController {
  @Get(':id')
  @UseFilters(new HttpExceptionFilter()) // 也可以路由级别使用
  getUser(@Param('id') id: string) {
    if (!id) throw new BadRequestException('ID不能为空');
    // ...
  }
}

📋 总结表格

组件阶段主要职责
中间件请求进入请求预处理、日志、CORS
守卫请求进入认证、授权、权限控制
拦截器(前)请求进入请求日志、超时处理
管道请求进入参数验证、输入数据转换
拦截器(后)响应返回响应转换、数据包装
异常过滤器响应返回异常处理、错误响应

参考

updatedupdated2025-09-232025-09-23
加载评论