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)
}
}
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
Share Improve this question edited Dec 5, 2018 at 16:29 Goodwill Tshekela asked Dec 5, 2018 at 15:49 Goodwill TshekelaGoodwill Tshekela 231 gold badge1 silver badge6 bronze badges 2- I think your logic is wrong. You should be setting exists = true if result.Item is true. In the past, I have put logic that checks for if it exists by saying if (result.Item !== undefined && result.Item !== null). Also, something that will help you debug is if you put logging statements in your code that output to a Cloudwatch log stream. – Luke Becker Commented Dec 5, 2018 at 16:03
- Yes i noticed that logic flaw. Thanks – Goodwill Tshekela Commented Dec 5, 2018 at 16:18
1 Answer
Reset to default 3First, 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)
}
}