My intention is to write a Lambda function that retrieves the specified item from the DynamoDB table using either Scan or Query (which ever works). This is invoked using a REST post request.
In my current version of my Lambda function, I am able to retrieve all the items from the DynamoDB table by using the ScanCommand and I tried to implement the different FilterExpression parameters and/or ExpressionAttributeValues (when using Query). Unfortunately, I am unsuccessful in querying/retrieving the specific item using the parameter I have defined, petID.
In the table:
sk is the sort key for where the item is retrieved by the requested petID parameter.
/**
* detail lost Pet Lambda Function
* Retrieves the singular lost pet using the pet ID / sk
*
* @param {module} DynamoDBClient
* @param {module} QueryCommand
* @param {module} ScanCommand
* @return {function} lambda invokes post/get request lost pet alert function
*
* @author
* @version 1.1
*/
const { DynamoDBClient, QueryCommand, ScanCommand } = require("@aws-sdk/client-dynamodb"); // CommonJS import
const aws = require('aws-sdk');
/**
* Exports handler Function
* Handles nodejs Lambda function using a try-catch statement
*
* @param {json} event Post/Get event parameter
* @return {json} output REST Post/Get lost pet alert data
* @throws {404} exception
* @throws {xxx} exception
*
* @author
* @version 1.1
*/
exports.handler = async (event) => {
try {
console.log(event); // log event parameter post
let body = event.body; // log event body ensure that it is string
// [object Object]
let bodyJSON2 = JSON.parse(body);
console.log("bodyJSON2: " bodyJSON2);
let bodyJSON = JSON.stringify(body); // body JSON from parsed event.body
console.log("bodyJSON: " bodyJSON);
let petID = bodyJSON.petID; // pet id param
if(!petID) {
// throw new Error("Missing petID in request body JSON")
}
/**
* detail petalert-lost parameters
* Parameters & Configuration for the table
*
* @param {Table} petalert-lost Dynamodb table identifier
* @param {String} username User profile identifier
* @param {String} sk pet id identifier
* @param {String} petname pet name identifier
* @param {String} found_desc found Pet Alert description
* @param {String} lastSeenTime Time last seen parameter
* @param {String} lastSeenLocation Location last seen parameter
* @param {String} reward reward value parameter
* @param {String} foundTime foundTime value parameter
* @param {String} phoneNumber found phone Number parameter
* @param {String} status_val status value parameter
* @param {Number} longitutde longitude location parameter
* @param {Number} latitude lattitude location parameter
* @param {String} photo1 photo1 parameter
* @param {String} photo2 photo2 parameter
* @param {String} photo3 photo3 parameter
* @param {String} photo4 photo4 parameter
* @param {String} phoneNumberAddedTime phone number added time
* @return {dynamodb params} petalert-found
*
* @author
* @version 1.1
*/
// working scan
const params = {
TableName: "petalert-lost",
Key: {
"sk": petID
}
};
// query param attempt
const paramsQUERY = {
TableName: "petalert-lost",
KeyConditionExpression: 'sk = :petID',
FilterExpression : "sk = :petID",
Key: {
"sk": petID
},
//KeyConditionExpression: "sk = :petID",
// Key: {
// "petID": {
// S: petID
// }
// },
};
const client = new DynamoDBClient({ region: "ap-southeast-1" }); // production client - singapore
let command = new ScanCommand(params);
const res = await client.send(command);
console.log(res);
console.log(res.Items);
let petList = res.Items;
let response;
/**
* 200 Status Code
* Passing Result
*
* @param {Number} res.$metadata.httpStatusCode Containing the HTTP Status Code
* @param {Struct} allPetList Containing the parameter response
* @return {json} response Json response
*
* @author
* @version 1.1
*/
if (res.$metadata.httpStatusCode == 200) {
response = {
statusCode: 200,
"isBase64Encoded": false,
"headers": { "Access-Control-Allow-Origin": "*" },
body: JSON.stringify(petList),
};
return response;
}
/**
* !200 Status Code
* Failure Result
*
* @param {Number} res.$metadata.httpStatusCode Containing the HTTP Status Code
* @return {json} response Json response
*
* @author
* @version 1.1
*/
else if (res.$metadata.httpStatusCode != 200) {
response = {
statusCode: res.$metadata.httpStatusCode,
"isBase64Encoded": false,
"headers": { "Access-Control-Allow-Origin": "*" },
body: JSON.stringify("retrieve detail lost pet alert FAIL"),
};
return response;
}
}
/**
* 456 Status Code
* Error Exception Result
* @param {Error} err Containing error value
* @return {json} errResp Error Json response
*
* @author
* @version 1.1
*/
catch (err) {
console.log("Error", err);
const errResp = {
//statusCode: err.$metadata.httpStatusCode,
statusCode: 456,
"isBase64Encoded": false,
"headers": { "Access-Control-Allow-Origin": "*" },
body: JSON.stringify(err.__type),
};
return errResp;
}
finally {
}
};
CodePudding user response:
You wish to receive a list of item where petId
is the key, to use Query petId
must be the partition key for your table, if it's not then you need to create a GSI and make petId
the partition key.
I believe petId
is your sort key by your description and for that reason a Query won't work.
Query would look like this:
const params = {
TableName: "petalert-lost",
KeyConditionExpression: 'sk = :petID',
ExpressionAttributeValues: {
":petID":{"S":petID}
}
};
let command = new QueryCommand(params);
const res = await client.send(command);
CodePudding user response:
Try with:
const paramsQUERY = {
TableName: "petalert-lost",
KeyConditionExpression: petID,
};