简体   繁体   中英

Query DynamoDB to check if a particular item exists or not

I just started out with Node.js and AWS DynamoDB and I am stuck with a very basic problem. I would like to query my DynamoDB which has a "Users" table with "Username"(PKey) and "JoinedOn" columns. Now I would like to write a Lambda function to check if a particular Username exists or not and return a response on the basis of that. Currently I am using the below code:

const AWS = require('aws-sdk');
const docClient = new AWS.DynamoDB.DocumentClient();

const params = {
  TableName : 'Users',

  Key: {
    Username: 'user1'
  }
}

async function getItem(){
  try {
    const data = await docClient.get(params).promise()
    return data
  } catch (err) {
    return err
  }
}

exports.handler = async (event, context) => {
  try {
    const data = await getItem()
    return { body: JSON.stringify(data) }
  } catch (err) {
    return { error: err }
  }
}

I am currently hardcoding the key (Username: 'user1') in my code, but I want to avoid doing that as I want to use the same code to check for different users, whether the Username exists in the "Users" table or not.

I want to use SAM. My event.json should look like below, as I want to check if user1 exists in "Users" or not:

{
  "Username": "user1"
}

On running "sam local invoke TestFunction -e events/event.json", I should get a response "User exists" or "User does not exist"

I am new to AWS and development. Any help is really appreciated.

Thank you in advance!

you need to define that username in environment variable section of lambda. then inside the lambda code you can simply call process.env.username.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM