Reputation: 499
When I provide my Lambda function with an invalid primary key for a GetItem call, it seems to search for that key until it times out, but then it still just returns a 200 (without a response body).
Is there any way to make sure the function aborts once it has gone through the table once without finding the key and returning an error message instead? Seems like a waste of function time to have it look over and over again until it times out? Furthermore, it times out after 1000ms which is not my function timeout setting which makes me think that there is something else going on here than a regular timeout.
Code:
'use strict';
const AWS = require('aws-sdk');
const docClient = new AWS.DynamoDB.DocumentClient();
exports.handler = (event, context, callback) => {
const done = (err, res) => {
const response = {
statusCode: err ? '400' : '200',
body: err ? JSON.stringify(err) : JSON.stringify(res)
}
callback(null, response);
};
const groupId = event.pathParameters.groupId;
const eventId = event.pathParameters.eventId;
docClient.get({
TableName: 'events',
Key: {
groupId,
eventId
}
},
(err, data) => {
done(err, data.Item);
});
};
Upvotes: 2
Views: 3601
Reputation: 5003
In a perfect world, I would like for the function to stop once it has "realized" that I have supplied an incorrect primary key and then return some error that would tell the client that it could not find an item in the table with that primary key, yes!
This can only happen if we let the DB operation do it! SO we have to be dependent on the response from the DB.
Here's what we can do: Based on response return the error whether 200 or 400!
To check if the res isEmpty method of Lodash and return 400 using your done function
.
'use strict';
const AWS = require('aws-sdk');
const docClient = new AWS.DynamoDB.DocumentClient();
const { isEmpty } = require('lodash');
exports.handler = (event, context, callback) => {
const done = (err, res) => {
const response = {
statusCode: (err || isEmpty(res)) ? '400' : '200',
body: err ? JSON.stringify(err) : JSON.stringify(res)
}
callback(null, response);
};
const groupId = event.pathParameters.groupId;
const eventId = event.pathParameters.eventId;
docClient.get({
TableName: 'events',
Key: {
groupId,
eventId
}
},
(err, data) => {
done(err, data.Item);
});
};
Hope this solves your query!
Upvotes: 0