使用 nodejs 和 Alexa 查询 dynamodb 以返回多个项目



我是这一切的新手,所以提前道歉。我正在尝试使用 nodejs 和 lambda 查询 Dynamodb,以便让 Alexa 返回值。dynamodb 表的设置如下所示:

date          time      filmname
2018-01-04    13:00     Titanic
2018-01-04    15:30     Titanic
2018-01-04    18:30     Paddingtion 
2018-01-05    12:00     Star Wars

我的表格设置了: 主分区键 = 日期(字符串) 主排序键 = 时间(字符串)

现在我想做的是从dynamodb查询或获取特定日期的信息,因此对于2018-01-04,应该返回3个项目。是否可以在 Lambda 中使用 nodejs 并允许 alexa 回读所有项目?

我已经在我的意图中设置了以下代码,并且工作正常:

var params = {
TableName: 'Cinema',
Key:{ "date": "2018-01-04", "time" : "13:00"  }
};
docClient.get(params, (err, data) => {
if (err) {
this.emit(':tell', 'Test Error');
} else {
this.emit(':tell', 'Test Working ' + data.Item.title);
}
});

上面的代码按预期返回泰坦尼克号。但是,我无法让它返回给定日期的所有项目,而不仅仅是该特定时间的所有项目。

我能够独立运行此 js 代码(即不在 lambda 中),并且工作正常。虽然我怀疑这不是最好的方法。

var params = {
TableName: 'Cinema',
KeyConditionExpression: "#date = :yymmdd and #time between :time1 and :time2",
ExpressionAttributeNames:{
"#date": "date",
"#time": "time"
},
ExpressionAttributeValues: {
":yymmdd":"2018-01-04",
":time1":'0',
":time2":'2'
}
};

docClient.query(params, function(err, data) {
if (err) {
console.error("Unable to query. Error:", JSON.stringify(err, null, 2));
} else {
console.log("Query succeeded.");
data.Items.forEach(function(item) {
console.log(" -", item.title + ": ");
});
}
});

现在,如果我在 Lambda 中运行此代码并尝试测试技能,我会得到"无法调用远程终端节点,或者它返回的响应无效"。此外,由于某种原因,我的 cloudwatch 日志没有针对该特定 lambda 函数进行更新,因此我目前无法获得有关它的更多信息。

如果有人感兴趣,我解决了这个问题。这就像确保发送到Alexa的响应仅触发一次一样简单。

我是新手,所以尽管代码按要求工作,但我愿意接受有关最佳实践的任何建议。

function queryDynamoDate_single() {
const startdate = this.attributes['startdate'];

var say = '';
var params = {
TableName: 'Cinema',
KeyConditionExpression: "#date = :yymmdd and #time between :time1 and :time2",
ExpressionAttributeNames:{
"#date": "date",
"#time": "time"
},
ExpressionAttributeValues: {
":yymmdd":startdate,
":time1":'0',
":time2":'2'
}
};
readDynamoItem(params, myResult=>{
say = myResult;
say = 'you asked,. The answer is: ' + myResult;
this.response.speak(say).listen('try again');
this.emit(':responseReady');
});         
}

.

function readDynamoItem(params, callback) {
var title = [];
var time = [];
var noofitems = 0;
let speechOutput = "";
docClient.query(params, (err, data) => {
if (err) {
this.emit(':tell', 'Test Error');
} else {
console.log("Query succeeded.");
data.Items.forEach(function(item) {
console.log(" -", item.title + ": ");
noofitems = noofitems + 1;
title[noofitems] = item.title;
time[noofitems] = item.time;
});
for (var l = 1; l <= noofitems ; l++){
{
speechOutput = speechOutput + title[l]; 
}
callback(speechOutput);
}
});
}

最新更新