NestJS中的Middleware, Interceptors, Guards, Pipes使用场景区分

NestJS 是一个用于构建高效、可扩展的 Node.js 服务器端应用程序的框架。它提供了多种中间件、拦截器、守卫和管道,用于处理请求和响应。

NestJS的中间件、拦截器、守卫和管道是处理请求和响应的不同方式,它们在应用程序中扮演着不同的角色。

管道(Pipes)

用途

  • 数据转换和验证。
  • 在请求到达控制器之前处理请求数据。

应用场景

  • 验证请求中的数据是否符合预期格式。
  • 将请求数据转换为其他格式或类型。

示例

1
2
3
4
5
6
7
8
9
10
11
12
import { PipeTransform, Injectable, BadRequestException } from '@nestjs/common';

@Injectable()
export class ValidationPipe implements PipeTransform {
transform(value: any) {
// 进行数据验证逻辑
if (!value.isValid()) {
throw new BadRequestException('Invalid data');
}
return value;
}
}

拦截器(Interceptors)

用途

  • 在请求到达控制器之前和之后执行操作。
  • 可用于日志记录、修改响应等。

应用场景

  • 记录请求和响应的日志。
  • 对响应数据进行统一处理,如添加额外的信息。

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } 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(
map((data) => {
console.log(`After... Request took ${Date.now() - now}ms`);
return data;
}),
);
}
}

守卫(Guards)

用途

  • 控制进入控制器或方法的访问权限。
  • 通常用于认证和授权。

应用场景

  • 用户认证,确保只有已登录用户才能访问某些资源。
  • 角色授权,只有特定角色的用户才能访问某些资源。

示例

1
2
3
4
5
6
7
8
9
import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';

@Injectable()
export class AuthGuard implements CanActivate {
canActivate(context: ExecutionContext): boolean {
const request = context.switchToHttp().getRequest();
return request.isAuthenticated(); // 假设这是一个自定义的方法,用于验证用户是否已登录
}
}

中间件(Middleware)

用途

  • 执行跨请求的初始化逻辑。
  • 通常用于日志记录、身份验证、错误处理等。

应用场景

  • 日志记录,记录所有请求的基本信息。
  • 错误处理,统一处理未捕获的异常。

示例

1
2
3
4
5
6
7
8
9
10
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(`${req.method} ${req.url}`);
next();
}
}

使用场景总结

  • 管道(Pipes):主要用于请求数据的验证和转换。
  • 拦截器(Interceptors):用于在请求到达控制器之前和之后执行某些操作,如日志记录、修改响应等。
  • 守卫(Guards):用于控制对控制器或方法的访问权限,常见于认证和授权场景。
  • 中间件(Middleware):用于执行跨请求的初始化逻辑,如日志记录、身份验证等。

本文永久链接: https://www.mulianju.com/nestjs-pipes-interceptors-guards-middleware/