AWS Lambda Node 20 to SCAN, QUERY, GET & PUT from DynamoDB
AWS Lambda Node 20 to Query DynamoDB
DynamoDB Table
Input Parameters { "Details": { "ContactData": { "Attributes": { "customerType": "premium" }, "ContactId": "123456789", "CustomerEndpoint": { "Address": "+1234567890", "Type": "PhoneNumber" }, "InitialContactId": "init-987654321", "InitiationMethod": "INBOUND", "InstanceARN": "arn:aws:connect:us-east-1:123456789012:instance/abcdefg" }, "Parameters": { "phoneNumber": "+919382232212", "policyNumber": "POLICY55555" } } }Lambda Code 1 import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; import { DynamoDBDocumentClient, GetCommand, QueryCommand } from "@aws-sdk/lib-dynamodb"; import "./types.mjs"; const client = new DynamoDBClient(); const ddb = DynamoDBDocumentClient.from(client); const tableName = process.env["LE_TABLE"] || ""; export const handler = async (event, context, callback) => { console.log("event", JSON.stringify(event)); if (!tableName) { console.error("MISSING TABLE ENVIRONMENT VARIABLE"); return { message: "MISSING TABLE ENVIRONMENT VARIABLE", assignedAgent: "not found" }; } try { let response; if (event.Details?.Parameters?.phoneNumber) { response = await getRecord({ key: "phoneNumber", value: event.Details.Parameters.phoneNumber }); console.log("response1", response); if (response.assignedAgent === "kishore" && event.Details.Parameters.policyNumber) { response = await queryIndex({ key: "policyNumber", value: event.Details.Parameters.policyNumber, index: "policyNumber" }); console.log("response2", response); } } else if (event.Details?.Parameters?.policyNumber) { response = await queryIndex({ key: "policyNumber", value: event.Details.Parameters.policyNumber, index: "policyNumber" }); console.log("response3", response); } else { console.log("else"); return { message: "Invalid input", assignedAgent: "not found" }; } return response; } catch (err) { console.error(err); return { message: "Get record error", assignedAgent: "not found" }; } }; const queryIndex = async (event) => { console.log("Index", event.index); console.log("Key", event.key); console.log("Value", event.value); const getParams = { TableName: tableName, IndexName: event.index, KeyConditionExpression: `${event.key} = :ct`, ExpressionAttributeValues: { ":ct": event.value } }; console.log("getParams",getParams); try { let results = await ddb.send(new QueryCommand(getParams)); console.log("results", results); return results.Items?.length ? { assignedAgent: results.Items[0].agentId } : { assignedAgent: "not found" }; } catch (err) { console.error(err); return { assignedAgent: "not found" }; } }; const getRecord = async (event) => { const getParams = { TableName: tableName, Key: { [event.key]: event.value } }; try { let results = await ddb.send(new GetCommand(getParams)); return results.Item ? { assignedAgent: results.Item.agentId } : { assignedAgent: "not found" }; } catch (err) { console.error(err); return { assignedAgent: "not found" }; } };Lambda Code 2 DynamoDB Table
import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; import { DynamoDBDocumentClient, QueryCommand } from "@aws-sdk/lib-dynamodb"; const client = new DynamoDBClient({}); const ddb = DynamoDBDocumentClient.from(client); export const handler = async (event, context) => { console.log("Event+" + JSON.stringify(event)); let response; response = await queryIndex({ key: "activeCall", value: event.Details.Parameters.policyNumber, index: "ActiveCallIndex" }); console.log("response2", response); return response; // const tableName = process.env["RISK_TABLE"]; // console.log("Index", event.index); // console.log("Key", event.key); // console.log("Value", event.value); // const queryParams = { // TableName: tableName, // IndexName: "ActiveCallIndex", // KeyConditionExpression: 'activeCall = :acall', // ExpressionAttributeValues: { // ':acall': 'true' // } // }; // try { // console.log("queryParams :", queryParams); // const obj = await ddb.send(new QueryCommand(queryParams)); // console.log("query :", obj); // return obj; // } catch (err) { // console.log("error on query ", err); // return- null; // } } const queryIndex = async (event) => { const tableName = process.env["RISK_TABLE"]; console.log("Index", event.index); console.log("Key", event.key); console.log("Value", event.value); const getParams = { TableName: tableName, IndexName: event.index, KeyConditionExpression: `${event.key} = :ct`, ExpressionAttributeValues: { ':ct': "true" } }; console.log("getParams",getParams); try { let results = await ddb.send(new QueryCommand(getParams)); console.log("results", results); return results.Items?.length ? { assignedAgent: "agentId" } : { assignedAgent: "not found" }; } catch (err) { console.error(err); return { assignedAgent: "not found" }; } };Lambda Response & Logs
AWS Lambda Node 20 to scan DynamoDB
DynamoDB JSON Data:
{
"agentName": {
"S": "KISHORE@KISHOREWEB.COM"
},
"agentId": {
"S": "KISHORE@KISHOREWEB.COM"
},
"agentNumber": {
"S": "93822"
}
}
Lambda Code:
import { DynamoDBClient, ScanCommand } from "@aws-sdk/client-dynamodb";
//import warmer from 'lambda-warmer';
//import https from 'https';
export const handler = async (event, context, callback, err) => {
// Warm-up check
// if (await warmer(event)) {
// console.log("Warm-up request received.");
// return "Lambda warmed";
// }
console.log("Event:", JSON.stringify(event));
const client = new DynamoDBClient({ region: "us-east-1" });
const Name = event.Details.Parameters.agentName;
console.log("Agent Name:", Name);
const input = {
TableName: process.env.NAME_DB,
FilterExpression: 'agentName = :agentName',
ExpressionAttributeValues: {
":agentName": { S: Name },
}
};
console.log("Input:", input);
try {
const command = new ScanCommand(input);
console.log(command);
const response = await client.send(command);
console.log('Response',response);
const {Items} = response;
let result;
if(response.Count === 1){
const {agentNumber, agentId, agentName} = Items[0];
result = {
agentName: agentName.S,
agentNumber: agentNumber.S,
agentId: agentId.S
};
}
else{
result = {
agentName,
agentNumber,
agentId
};
}
console.log("Result:", result);
callback(null, result);
} catch (err) {
console.log("Error:", err);
callback(null, {
statusCode: 500,
body: JSON.stringify({
message: "An error occurred",
error: err.message,
}),
});
}
};
AWS Lambda Node 20 to Get & Query DynamoDB
{
"Details": {
"ContactData": {
"Attributes": {
"customerType": "premium"
},
"ContactId": "123456789",
"CustomerEndpoint": {
"Address": "+1234567890",
"Type": "PhoneNumber"
},
"InitialContactId": "init-987654321",
"InitiationMethod": "INBOUND",
"InstanceARN": "arn:aws:connect:us-east-1:123456789012:instance/abcdefg"
},
"Parameters": {
"phoneNumber": "+919382232212",
"policyNumber": "POLICY55555"
}
}
}
index.mjs
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import { DynamoDBDocumentClient, GetCommand, QueryCommand } from "@aws-sdk/lib-dynamodb";
import "./types.mjs";
const client = new DynamoDBClient();
const ddb = DynamoDBDocumentClient.from(client);
const tableName = process.env["LE_TABLE"] || "";
export const handler = async (event, context, callback) => {
if (!tableName) {
console.error("MISSING TABLE ENVIRONMENT VARIABLE");
return { message: "MISSING TABLE ENVIRONMENT VARIABLE", assignedAgent: "not found" };
}
try {
let response;
if (event.Details?.Parameters?.phoneNumber) {
response = await getRecord({ key: "phoneNumber", value: event.Details.Parameters.phoneNumber });
if (response.assignedAgent === "not found" && event.Details.Parameters.policyNumber) {
response = await queryIndex({ key: "policyNumber", value: event.Details.Parameters.policyNumber, index: "policyNumber" });
}
} else if (event.Details?.Parameters?.policyNumber) {
response = await queryIndex({ key: "policyNumber", value: event.Details.Parameters.policyNumber, index: "policyNumber" });
} else {
return { message: "Invalid input", assignedAgent: "not found" };
}
return response;
} catch (err) {
console.error(err);
return { message: "Get record error", assignedAgent: "not found" };
}
};
const queryIndex = async (event) => {
const getParams = {
TableName: tableName,
IndexName: event.index,
KeyConditionExpression: `${event.key} = :ct`,
ExpressionAttributeValues: { ":ct": event.value }
};
try {
let results = await ddb.send(new QueryCommand(getParams));
return results.Items?.length ? { assignedAgent: results.Items[0].agentId } : { assignedAgent: "not found" };
} catch (err) {
console.error(err);
return { assignedAgent: "not found" };
}
};
const getRecord = async (event) => {
const getParams = {
TableName: tableName,
Key: { [event.key]: event.value }
};
try {
let results = await ddb.send(new GetCommand(getParams));
return results.Item ? { assignedAgent: results.Item.agentId } : { assignedAgent: "not found" };
} catch (err) {
console.error(err);
return { assignedAgent: "not found" };
}
};
types.mjs
/**
* @typedef {Object} ConnectEvent
* @property {Object} Details
* @property {Object} Details.ContactData
* @property {Object} Details.ContactData.Attributes
* @property {string} Details.ContactData.ContactId
* @property {Object} Details.ContactData.CustomerEndpoint
* @property {string} Details.ContactData.CustomerEndpoint.Address
* @property {string} Details.ContactData.CustomerEndpoint.Type
* @property {string} Details.ContactData.InitialContactId
* @property {string} Details.ContactData.InitiationMethod
* @property {string} Details.ContactData.InstanceARN
* @property {Object} Details.Parameters
*/
/**
* @typedef {Object} EventRecord
* @property {string} phoneNumber
* @property {string} [policyNumber]
* @property {string} agentId
* @property {number} TTL
*/
/**
* @typedef {Object} Response
* @property {string} [assignedAgent]
*/
/**
* @typedef {Object} getParams
* @property {string} key
* @property {string} value
* @property {string} [index]
*/
export {};
AWS Lambda Node 20 to Put DynamoDB
handler.mjs
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import { DynamoDBDocumentClient, PutCommand } from "@aws-sdk/lib-dynamodb";
import { ConnectEvent, EventRecord, Response } from "./types.mjs";
// Initialize DynamoDB Client
const client = new DynamoDBClient({ region: process.env.REGION });
const ddb = DynamoDBDocumentClient.from(client);
const tableName = process.env.LE_TABLE || "";
// AWS Lambda Handler
export const handler = async (event, context, callback) => {
if (!tableName) {
console.error("MISSING TABLE ENVIRONMENT VARIABLE");
return { message: "MISSING TABLE ENVIRONMENT VARIABLE" };
}
if (!event.Details?.Parameters?.policyNumber) {
event.Details.Parameters.policyNumber = "not found";
}
try {
return await putItem(event.Details.Parameters);
} catch (err) {
console.error("PUT RECORD ERROR:", err);
return { message: "PUT RECORD ERROR" };
}
};
// Function to Put Item in DynamoDB
const putItem = async (event) => {
if (!event.agentId) {
return { message: "No Agent ID" };
}
const thirtyDays = 60 * 60 * 24 * 30;
event.TTL = Math.round(Date.now() / 1000) + thirtyDays;
const putParams = {
TableName: tableName,
Item: event
};
try {
await ddb.send(new PutCommand(putParams));
return { message: "Success" };
} catch (err) {
console.error("DynamoDB Put Failure:", err);
return { message: "Put failure" };
}
};
types.mjs
export const ConnectEvent = {
Details: {
ContactData: {
Attributes: {},
ContactId: "",
CustomerEndpoint: {
Address: "",
Type: ""
},
InitialContactId: "",
InitiationMethod: "",
InstanceARN: ""
},
Parameters: {}
}
};
export const EventRecord = {
phoneNumber: "",
policyNumber: "",
agentId: "",
TTL: 0
};
export const Response = {
message: ""
};


