无法在拦截器中取消请求

时间:2019-12-23 03:59:49

标签: javascript rxjs nestjs

我正试图取消超过n秒的请求的请求处理。例如,在此示例https://github.com/nestjs/nest/tree/master/sample/01-cats-app

cats.controller.ts中替换

@UseInterceptors(LoggingInterceptor, TransformInterceptor)

使用

@UseInterceptors(TimeoutInterceptor, LoggingInterceptor, TransformInterceptor)

cats.controller.ts中替换

  @Get()
  async findAll(): Promise<Cat[]> {
    return this.catsService.findAll();
  }

使用

  @Get()
  async findAll(): Promise<Cat[]> {
    for (let i = 0; i < 100000000; i++) {
      if (i === 99999999) {
        return this.catsService.findAll();
      }
    }
  }

添加拦截器源:

import {
  CallHandler,
  ExecutionContext,
  Injectable,
  NestInterceptor,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { timeout } from 'rxjs/operators';

@Injectable()
export class TimeoutInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    return next.handle().pipe(timeout(1));
  }
}

即使在1毫秒后仍请求处理并返回数据。日志:

Before...
After... 134ms

此处的拦截器代码:https://docs.nestjs.com/interceptors

我做错了什么?

1 个答案:

答案 0 :(得分:1)

好,知道发生了什么事。按原样使用for循环时,从技术上讲,您不会移至执行上下文的下一部分,因此超时管道尚未开始生效。为了启动超时运算符,必​​须调用AppService的方法以允许调用堆栈继续前进。您可以返回一个异步函数,并对其超时进行观察,以了解异步函数的工作时间,但是通常for循环是同步的,这是错误函数的所在。如果需要,请尝试添加

function asyncTimeout(time: number) {
  return new Promise((resolve, reject) => {
    setTimeout(() => resolve(), time);
  });
}

此函数连接到您的服务器,然后调用await asyncTimeout(5000)

您可以将其用于AppService

import { Injectable } from '@nestjs/common';

function asyncTimeout(time: number) {
  return new Promise((resolve, reject) => {
    setTimeout(() => resolve(), time);
  });
}

@Injectable()
export class AppService {
  async getHello(): Promise<string> {
    console.log('In service');
    await asyncTimeout(5000);
    console.log('Returning after waiting');
    return 'Hello World!';
  }
}

这是您的AppController

import { Controller, Get, UseInterceptors } from '@nestjs/common';
import { AppService } from './app.service';
import { TimeoutInterceptor } from './timeout.interceptor';

@Controller()
@UseInterceptors(TimeoutInterceptor)
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Get()
  getHello(): Promise<string> {
    console.log('In controller');
    return this.appService.getHello();
  }
}

这是您的TimeoutInterceptor

import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';
import { Observable } from 'rxjs';
import { tap, timeout } from 'rxjs/operators';

@Injectable()
export class TimeoutInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    console.log('In interceptor');
    return next.handle().pipe(tap(() => console.log('In tap of return interceptor')), timeout(1));
  }
}

如果您取消对http://localhost:3000的呼叫,则会看到超时几乎是瞬间发生的,并且您会看到日志:

[Nest] 10529   - 12/23/2019, 8:07:40 AM   [NestFactory] Starting Nest application...
[Nest] 10529   - 12/23/2019, 8:07:40 AM   [InstanceLoader] AppModule dependencies initialized +11ms
[Nest] 10529   - 12/23/2019, 8:07:40 AM   [RoutesResolver] AppController {/}: +4ms
[Nest] 10529   - 12/23/2019, 8:07:40 AM   [RouterExplorer] Mapped {/, GET} route +2ms
[Nest] 10529   - 12/23/2019, 8:07:40 AM   [NestApplication] Nest application successfully started +2ms
In interceptor
In controller
In service
[Nest] 10529   - 12/23/2019, 8:07:48 AM   [ExceptionsHandler] Timeout has occurred +7955ms
Returning after waiting

但是在HTTP响应中,您会找到

▶ curl http://localhost:3000
{"statusCode":500,"message":"Internal server error"}% 

这是因为您无法取消承诺,因此它仍必须完成其执行。但是,您可以不考虑诺言的返回,因为您已经向客户发送了回复,说请求花了太长时间。

Here's a link to the repository