推荐答案
在 Nest.js 中,可以通过在控制器或路由处理程序上使用 @UseInterceptors() 装饰器来应用拦截器。以下是一个示例:
// www.javascriptcn.com code example
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';
}
}在这个示例中,LoggingInterceptor 拦截器被应用到了 CatsController 控制器的所有路由上。如果你只想在特定的路由处理程序上应用拦截器,可以将 @UseInterceptors() 装饰器直接放在方法上:
@Get()
@UseInterceptors(LoggingInterceptor)
findAll(): string {
return 'This action returns all cats';
}本题详细解读
拦截器的作用
拦截器是 Nest.js 中的一种强大的机制,允许你在请求处理的不同阶段插入自定义逻辑。拦截器可以用于以下场景:
- 在方法执行前后添加额外的逻辑(如日志记录、性能监控等)。
- 转换从方法返回的结果。
- 转换从方法抛出的异常。
- 扩展基本方法行为。
拦截器的实现
拦截器是一个实现了 NestInterceptor 接口的类,通常需要实现 intercept 方法。以下是一个简单的拦截器示例:
// www.javascriptcn.com code example
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`)),
);
}
}在这个示例中,LoggingInterceptor 拦截器会在请求处理前后分别打印日志。
应用拦截器的位置
拦截器可以应用在以下位置:
- 控制器级别:通过在控制器类上使用
@UseInterceptors()装饰器,拦截器将应用于该控制器的所有路由处理程序。 - 方法级别:通过在路由处理程序方法上使用
@UseInterceptors()装饰器,拦截器将仅应用于该特定方法。
全局拦截器
如果你希望在整个应用程序中应用拦截器,可以在 main.ts 文件中使用 app.useGlobalInterceptors() 方法:
// www.javascriptcn.com code example
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { LoggingInterceptor } from './logging.interceptor';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalInterceptors(new LoggingInterceptor());
await app.listen(3000);
}
bootstrap();这种方式会将拦截器应用到所有的控制器和路由处理程序上。