node.js - NodeJS API 通过 ID 获取。如何检测未找到的项目?

标签 node.js express amazon-dynamodb swagger endpoint

我正在开发一个 GET 端点来从数据库(dynamoDB)获取元素。我正在使用 Swagger 在我的 api 中定义数据模型。这是我的 Controller 中的 operationId 方法:

 getInvoiceConfigById: function(req, res) {
   var myId = req.swagger.params.id.value;

   // InvoiceConfig is a dynamoDb model
   // providerId attribute is the unique key of the db table
   InvoiceConfig.scan('providerId')
                .eq(myId)
                .exec(function (err, config) {
                   if (err) {
                     console.log("Scan InvoiceConfig error");
                     throw err;
                   }

                   res.status(200).send(config);

                 });
 }

如果找不到 id,我想发送 404 消息。 我注意到在 swagger-ui 中响应的正文是空的

Response Body

[] 

当在数据库中找不到该 id 时。 当没有找到 id 时,如何在我的代码中检测到?我尝试检查响应正文是否为空:

if(!(config.body))

但这不起作用,因为主体不为空

最佳答案

您可以在服务器端检查config的计数,如果config计数为0,则发送期望响应代码404,否则返回200响应代码,数据如下所示

 getInvoiceConfigById: function(req, res) {
   var myId = req.swagger.params.id.value;

   // InvoiceConfig is a dynamoDb model
   // providerId attribute is the unique key of the db table
   InvoiceConfig.scan('providerId')
                .eq(myId)
                .exec(function (err, config) {
                   if (err) {
                     console.log("Scan InvoiceConfig error");
                     throw err;
                   }
                   if (config.length == 0){
                      res.status(404).end();
                   } else {
                      res.status(200).send(config);
                   }
                 });
 }

关于node.js - NodeJS API 通过 ID 获取。如何检测未找到的项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44681722/

相关文章:

javascript - 在 promise 中得到 Express 回复?

javascript - 类实例的未定义​​返回 - Javascript

mysql - 插入/删除MySQL/MariaDB,自动显示在React表中

security - ExpressJS : how does req. session 工作?

amazon-dynamodb 和按日期过滤

javascript - 高速传输的流数据可视化

node.js - "right"路由映射 REST API 的方法

java - 如何从 DynamoDB 表中的项目中删除属性?

python - 如何在 python boto 中创建 dynamodb 表

javascript - Node.js 的正确继承