Reputation: 25
i'm making an API in AWS Lambda with NodeJS and DynamoDB and'm trying to get details of a specific customer or customers who comes from Colorado (state = Colorado).
Here i was trying to get all customers from Colorado.
router.get("/customers", (req, res) => {
const params = {
TableName: 'Customer',
FilterExpression: "stateOrProvince = :state",
ExpressionAttributeValues: {
":state": "Colorado"
}
};
dynamoDb.query(params, (error, result) => {
if (error) {
res.status(400).json({ error: `Error fetching the ${tableName}` });
}
res.json(result.Items);
});
});
Here i was trying to get details from a specific customer
router.get("/customers/:customerId", (req, res) => {
const id = req.params.customerId
const params = {
TableName: 'Customer',
FilterExpression: "customerId = :custId",
ExpressionAttributeValues: {
":custId": id
}
};
dynamoDb.query(params, (error, result) => {
if (error) {
res.status(400).json({ error: `Error fetching the ${tableName}` });
}
res.json(result.Items);
});
});
Both cases i'm getting a 502 error in postman :|
{ "message": "Internal server error" }
Could you help me to identify what the issue is ? I've read and tried differents syntaxes but I couldn't get it to work yet Thanks
Upvotes: -1
Views: 765
Reputation: 19793
You cannot use Query
operation without using a KeyConditionExpression
which you have not defined. You must at least insert the partition key for a Query
.
Try below, which uses Scan instead:
router.get("/customers", (req, res) => {
const params = {
TableName: 'Customer',
FilterExpression: "stateOrProvince = :state",
ExpressionAttributeValues: {
":state": "Colorado"
}
};
dynamoDb.scan(params, (error, result) => {
if (error) {
res.status(400).json({ error: `Error fetching the ${tableName}` });
}
res.json(result.Items);
});
});
Or for a specific customer, set KeyConditionExpression:
router.get("/customers/:customerId", (req, res) => {
const id = req.params.customerId
const params = {
TableName: 'Customer',
KeyConditionExpression: "customerId = :custId",
ExpressionAttributeValues: {
":custId": id
}
};
dynamoDb.query(params, (error, result) => {
if (error) {
res.status(400).json({ error: `Error fetching the ${tableName}` });
}
res.json(result.Items);
});
});
More info here
Upvotes: 1