I just started out with Node.js and AWS DynamoDB and I'm stuck with a very basic problem I believe. I'm looking for a way to return a boolean if a particular key exists in a table. So here's the code I have so far:
const AWS = require('aws-sdk')
const TOKEN_TABLE = process.env.TOKENS_TABLE
const dynamoDb = new AWS.DynamoDB.DocumentClient()
module.exports = {
isValid: function (token) {
const params = {
TableName: TOKEN_TABLE,
Key:
{
token: token
}
}
var exists = false
dynamoDb.get(params, (error, result) => {
if (result.Item)
exists = true
else
exists = false
})
return (exists)
}
}
When i call this function, the value of 'exists' never changes after it was declared even if the item I'm looking for is in the table. I've looked at similar questions and none of them could really help me out or a least explain why this occurs. Thanks
First, dynamoDb.get returns a promise. Therefore, you return 'exists' before your promise finishes and returns. What I've found to be the best way and cleanest way around this is to make your function async and await the return of the promise.
For example,
const AWS = require('aws-sdk')
const TOKEN_TABLE = process.env.TOKENS_TABLE
const dynamoDb = new AWS.DynamoDB.DocumentClient()
module.exports = {
isValid: async function (token) {
const params = {
TableName: TOKEN_TABLE,
Key:
{
token: token
},
AttributesToGet: [
'token'
]
}
var exists = false
let result = await dynamoDb.get(params).promise();
if (result.Item !== undefined && result.Item !== null) {
exists = true
}
return (exists)
}
}