我正在开发一个从数据库获取元素的GET端点(DynamoDB)。我使用Swagger在我的api中定义数据模型。这是我的控制器中的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
[]
当在db中找不到id时。我如何在我的代码中检测到没有找到id?我尝试检查响应的正文是否为空:
如果(!(config.body))
但这不起作用,因为主体不为空
发布于 2017-06-22 01:00:32
您可以在服务器端检查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);
}
});
}
发布于 2017-06-22 01:56:19
尝试在回调中添加长度检查,如下所示:
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(typeof config === 'array' && 0 < config.length){
res.status(200).send(config);
} else {
res.status(404).send();
}
});
}
我还建议您简单地使用getItem查询,而不是扫描:
http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB.html#getItem-property
发布于 2017-06-22 01:06:58
由于在找不到结果时config
对象键值为1,因此您可以像这样检查该对象的键值长度:
if ( Object.keys(config).length == 1 )return res.status(400).send("Error 404");
https://stackoverflow.com/questions/44681722
复制相似问题