I'm currently working on a Lambda function that is connected to an API. While most of the routes are functioning properly, I'm encountering an issue with the GET /items route which is supposed to retrieve all items from a DynamoDB table. Unfortunately, I keep getting the error message:
"Unexpected token u in JSON at position 0"
I've been following a tutorial outlined in the AWS Developer Guide:
The tutorial suggests using the scan method to fetch all items from the table. However, when I implement this, it doesn't seem to work as expected:
const AWS = require("aws-sdk");
const dynamo = new AWS.DynamoDB.DocumentClient();
exports.handler = async(event, context) => {
let body;
let statusCode = 200;
const headers = {
"Content-Type": "application/json"
};
try {
let requestJSON = JSON.parse(event.body);
switch (event.routeKey) {
case "GET /items":
body = await dynamo.scan({
TableName: "users"
})
.promise();
break;
case "PUT /signIn":
await dynamo
.update({
TableName: "users",
Key: {
UserId: requestJSON.UserId
},
UpdateExpression: "set SignedInAt = :a, IsSignedIn = :b, SignedOutAt = :c",
ExpressionAttributeValues: {
":a": new Date().toLocaleTimeString(),
":b": true,
":c": ""
}
})
.promise();
body = `User ${requestJSON.UserId} has been signed in.`;
break;
case "PUT /signOut":
await dynamo
.update({
TableName: "users",
Key: {
UserId: requestJSON.UserId
},
UpdateExpression: "set SignedOutAt = :a, IsSignedIn = :b",
ExpressionAttributeValues: {
":a": new Date().toLocaleTimeString(),
":b": false,
}
})
.promise();
body = `User ${requestJSON.UserId} has been signed out.`;
break;
default:
throw new Error(`Unsupported route: "${event.routeKey}"`);
}
}
catch (err) {
statusCode = 400;
body = err.message;
}
finally {
body = JSON.stringify(body);
}
return {
statusCode,
body,
headers
};
};
Here's a link to the logs for more information: