NodeJS API通过ID获取。 如何检测项目未find?
我正在开发一个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 []
当在数据库中找不到id时。 如何在我的代码中检测到ID未find时? 我试图检查响应的主体是否为空:
如果(!(config.body))
但是这不起作用,因为身体不是空的
您可以在服务器端检查configuration的计数,如果configuration计数为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); } }); }
尝试在callback中添加长度检查,如下所示:
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(); } }); }
我也build议你应该简单地使用getItem查询来代替扫描:
http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB.html#getItem-property
由于config
对象的键值是一个没有find结果时,所以你可以做的是检查该对象的键的长度是这样的:
if ( Object.keys(config).length == 1 )return res.status(400).send("Error 404");