关于NestJS拦截器执行顺序的澄清

关于NestJS拦截器执行顺序的澄清,nestjs,Nestjs,我有一个返回字符串的控制器处理程序 // Controller.ts import { Controller, Get, UseInterceptors } from '@nestjs/common'; import { UpperInterceptor } from './upper.interceptor'; import { LowerInterceptor } from './lower.interceptor'; @Controller() export class AppCont

我有一个返回字符串的控制器处理程序

// Controller.ts

import { Controller, Get, UseInterceptors } from '@nestjs/common';
import { UpperInterceptor } from './upper.interceptor';
import { LowerInterceptor } from './lower.interceptor';

@Controller()
export class AppController {

  @Get()
  @UseInterceptors(LowerInterceptor, UpperInterceptor)
  getHello(): string {
    return 'Hello'
  }
}
我已经附加了2个拦截器,上下两个拦截器会根据名称相应地更改字符串大小写

// lower.interceptor.ts
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators'

@Injectable()
export class LowerInterceptor implements NestInterceptor {

  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    console.log('lower')
    return next
      .handle()
      .pipe(
        map((e) => {
          console.log('calling lowercase')
          return e.toLowerCase()
        }),
      );
  }
}
//lower.interceptor.ts
从'@nestjs/common'导入{CallHandler,ExecutionContext,Injectable,NestInterceptor};
从“rxjs”导入{Observable};
从“rxjs/operators”导入{map}
@可注射()
导出类LowerInterceptor实现NestInterceptor{
拦截(上下文:ExecutionContext,下一步:CallHandler):可观察{
console.log('lower')
下一个返回
.handle()
.烟斗(
地图((e)=>{
console.log('调用小写字母')
返回e.toLowerCase()
}),
);
}
}
//upper.interceptor.ts
从'@nestjs/common'导入{CallHandler,ExecutionContext,Injectable,NestInterceptor};
从“rxjs”导入{Observable};
从“rxjs/operators”导入{map}
@可注射()
导出类UpperInterceptor实现了NestInterceptor{
拦截(上下文:ExecutionContext,下一步:CallHandler):可观察{
console.log('upper')
下一个返回
.handle()
.烟斗(
地图((e)=>{
console.log('调用大写字母')
返回e.toUpperCase()
}),
);
}
}
我希望返回值是
HELLO
,但它是
HELLO

据我所知,下拦截器是首先执行的,但它传递到可观察对象的映射是在上拦截器的映射之后执行的,因此返回字符串是
hello

您知道为什么拦截器按预期的顺序执行,但它们通过管道映射的回调却按相反的顺序执行吗

这与nest有关还是仅仅与rxjs有关?对不起,我对这两个都不熟悉。

这是RxJS的东西。本质上显示了正在发生的事情,即使没有显式地写在服务器中。每个拦截器都被链接到下一个拦截器中。拦截器遵循先入后出的堆栈帧,因此您可以看到先记录lower,再记录upper,但随后您会看到输出为小写,而不是您最初期望的大写。我还添加了一些
tap
方法,以说明在调用链中,使用Observbales发生的一切

// upper.interceptor.ts
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators'

@Injectable()
export class UpperInterceptor implements NestInterceptor {

  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    console.log('upper')
    return next
      .handle()
      .pipe(
        map((e) => {
          console.log('calling uppercase')
          return e.toUpperCase()
        }),
      );
  }
}