AWS Lambda Node 20 to scan DynamoDB


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

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: ""
};