nestjs - 使用 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
构建响应对象。
解决方案
您可以在您的服务文件中这样做 >
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();
}
推荐阅读
- android - 科尔多瓦-插件-高级-http | 上传大文件时出现内存不足错误
- java - 使用servlet JSP登录后如何防止用户返回登录页面
- python - 在两点之间更改列表中的值
- javascript - nodejs中redis客户端的异步导出
- python - C++ 在 Qt 中的行为不同,bind() 返回 EINVAL
- amazon-web-services - 更新实例后如何更新 Auto Scaling 启动配置或启动模板
- javascript - MongoDB/Mongoose $pull 一个数组中的对象,其中对象的 _id 匹配
- python - 图像序列的 LSTM - AttributeError:'bool' 对象没有属性'float'
- dart - 为什么在 Dart 中不能用“catchError”捕获异常?
- r - 将两个数据帧相乘