NestJS - 请求超时

use*_*711 6 express nestjs

如何为所有请求设置超时,如果超时则使用自定义 json 响应?

我尝试使用:

import * as timeout from 'connect-timeout';

import { NestFactory } from '@nestjs/core';
import { ApplicationModule } from './app.module';

const port = process.env.PORT || 3020;

async function bootstrap() {
  const app = await NestFactory.create(ApplicationModule);
  app.use(timeout('5s'));
  app.use(haltOnTimedOut);

  await app.listen(port);
} 
bootstrap();


function haltOnTimedOut (req, res, next) {
  if (!req.timedout){
      next();
  } else {
      res
        .status(408)
        .json({ status: 'error', data: 'timeout'})
  }
}
Run Code Online (Sandbox Code Playgroud)

但没有运气。

小智 14

为了增加nestjs - API 应用服务器请求/响应超时,我在 main.js 中做了以下操作

const server = await app.listen(5000);
server.setTimeout(1800000); // 600,000=> 10Min, 1200,000=>20Min, 1800,000=>30Min
Run Code Online (Sandbox Code Playgroud)

  • 谢谢你!解决了我的问题!你也可以这样做: server.setTimeout(30 * 60 * 1000); (2认同)

小智 11

NestJS 有一个称为拦截器的功能。拦截器可用于强制超时,他们在这里演示了TimeoutInterceptor。

假设您的拦截器位于名为的文件中timeout.interceptor.ts:

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

@Injectable()
export class TimeoutInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    return next.handle().pipe(
      timeout(5000),
      catchError(err => {
        if (err instanceof TimeoutError) {
          return throwError(new RequestTimeoutException());
        }
        return throwError(err);
      }),
    );
  };
};
Run Code Online (Sandbox Code Playgroud)

之后,您必须注册它,可以通过多种方式完成。全局注册方式如下图:

const app = await NestFactory.create(AppModule);
app.useGlobalInterceptors(new TimeoutInterceptor());
Run Code Online (Sandbox Code Playgroud)


Dav*_*d R -1

将你的功能app.use(timeout('5s'));移出你的功能,并从功能中bootstrap移除障碍。elsehaltOnTimedOut

并尝试将您的bootstrap函数作为中间件调用,如下所示,

app.use(boostrap, timeout('5s'), bodyParser.json(), haltOnTimedout, function (req, res, next) {
if (req.timedout) return
      res
        .status(408)
        .json({ status: 'error', data: 'timeout'})
});
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!