11

如何为所有请求设置超时,如果超时则使用自定义 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'})
  }
}

但没有运气。

4

4 回答 4

19

To increase the nestjs - API application server request/response timeout, I did the following in main.js

const server = await app.listen(5000);
server.setTimeout(1800000); // 600,000=> 10Min, 1200,000=>20Min, 1800,000=>30Min
于 2020-04-29T05:00:51.417 回答
4

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);
      }),
    );
  };
};

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

const app = await NestFactory.create(AppModule);
app.useGlobalInterceptors(new TimeoutInterceptor());
于 2021-03-29T10:43:25.243 回答
1

您可以将 express 实例传递给,NextFactory.create(module, expressInstance)以便您可以将中间件添加到该 express 实例中,例如

const expressInstance = express();
express.use(timeout('4'));
express.use((err, res, req, next) => req.jsonp(err)); // DON'T USE FOR PRODUCTION
const app = NestFactory.create(AppModule, express);

它应该工作。

于 2018-03-13T10:27:46.583 回答
-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'})
});

希望这可以帮助!

于 2018-03-09T07:55:56.933 回答