首页 > 解决方案 > 使用 NestJS 向响应添加状态

问题描述

我正在使用 NestJS,想知道如何向响应对象添加状态。假设我有这个控制器方法:

  @Get()
  ping(): string {
    return this.appService.ping();
  }

这会返回一个类似“2020 年 3 月 24 日 16:56:07”的字符串。我想要的是将状态代码添加到响应中,以便我的响应和错误消息使响应看起来像这样:

{
  result: "24 March 2020 16:56:07"
  status: "OK"
  errorMessage: ""
}

无论如何使用一些内置功能的nestjs来实现这一点?

更新:@Hitech-Hitesh 提出的解决方案不是我想要的,我想自动构建响应对象,所以我只是从控制器方法返回结果return this.appService.ping();,然后something else taking place构建响应对象。

标签: nestjs

解决方案


您可以在您的服务文件中这样做 >

  getData(): Message {
    // return { message: 'Welcome to api!' };
    return { message: '' };
  }
  ping() {
    if (this.getData().message !== '') {
      return { status: 'OK', errorMessage: '', result: this.getData().message };
    }
    else {
      return { status: 'FAIL', errorMessage: 'Not able to fetch the result. Please try again later', result: '' };
    }
  }

当从控制器调用 ping 文件时,它将直接给出结果

  @Get()
  ping(): any {
    return this.appService.ping();
  }

您也可以直接在控制器中执行此操作,但要检查服务响应。

  @Get()
  ping(): any {
    const pingServiceResponse = this.appService.ping();
    if (pingServiceResponse !== '')
      return { status: 'OK', errorMessage: '', result: pingServiceResponse };
    else
      return { status: 'FAIL', errorMessage: 'Not able to fetch the result. Please try again later', result: pingServiceResponse };

    // return this.appService.ping();
  }

推荐阅读