我正在开发一个 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/