【发布时间】:2020-11-19 12:52:40
【问题描述】:
这是我当前的 lambda 函数,它返回表“横幅”中的所有数据。
getBanner.js
'use strict'
const AWS = require('aws-sdk');
exports.handler = async function (event, context, callback) {
const documentClient = new AWS.DynamoDB.DocumentClient();
let responseBody = "";
let statusCode = 0;
const params = {
TableName : "Banner",
};
try{
const data = await documentClient.scan(params).promise();
responseBody = JSON.stringify(data.Items);
statusCode = 200
}catch(err){
responseBody = `Unable to get products: ${err}`;
statusCode = 403
}
const response = {
statusCode: statusCode,
headers:{
"Content-Type": "application/json",
'Access-Control-Allow-Origin': '*', // Required for CORS support to work
},
body: responseBody
}
return response
}
是样本返回数据
[
{
Order: 123,
Year: 2000
...
},
{
Order: 77,
Year: 2007
...
}
]
我明白了如果我想查询属性顺序,我需要改为following。
...
var params = {
TableName : "Banner",
KeyConditionExpression: "#od = :yyyy",
ExpressionAttributeNames:{
"#od": "order"
},
ExpressionAttributeValues: {
":yyyy": 1
}
};
...
如果我想执行以下操作怎么办?
可能有一些用例让我需要查询另一个属性或多个属性。
我应该如何拥有一个可以动态处理 queryStringParameters 的函数?
根据评论更新,但又出现错误
'use strict'
const AWS = require('aws-sdk');
exports.handler = async function (event, context, callback) {
const documentClient = new AWS.DynamoDB.DocumentClient();
let responseBody = "";
let statusCode = 0;
console.log(event)
const queryStringParams = event.queryStringParameters;
console.log(queryStringParams)
let KeyConditionExpression = ''
let ExpressionAttributeNames={};
let ExpressionAttributeValues = {};
for (const property in queryStringParams) {
KeyConditionExpression += ` #${property} = :${property} ,`;
ExpressionAttributeNames['#'+property] = property ;
ExpressionAttributeValues[':'+property]=queryStringParams[property];
}
KeyConditionExpression= KeyConditionExpression.slice(0, -1);
const params = {
TableName : "Banner",
KeyConditionExpression: KeyConditionExpression,
ExpressionAttributeNames: ExpressionAttributeNames,
ExpressionAttributeValues: ExpressionAttributeValues
};
console.log(params) //Response A
try{
const data = await documentClient.scan(params).promise();
responseBody = JSON.stringify(data.Items);
statusCode = 200
}catch(err){
responseBody = `Unabel to get products: ${err}`;
statusCode = 403
}
const response = {
statusCode: statusCode,
headers:{
"Content-Type": "application/json",
'Access-Control-Allow-Origin': '*', // Required for CORS support to work
},
body: responseBody
}
return response
}
Unabel to get products: ValidationException: ExpressionAttributeNames can only be specified when using expressions
这是从 cloudwatch 获得的‘params’的值 回应A
{
TableName: 'Banner',
KeyConditionExpression: ' #order = :order , #year = :year ',
ExpressionAttributeNames: { '#order': 'order', '#year': 'year' },
ExpressionAttributeValues: { ':order': '1', ':year': '2007' }
}
【问题讨论】:
标签: node.js amazon-web-services aws-lambda amazon-dynamodb