Search code examples
aws-lambdaamazon-dynamodbaws-sdk-nodejs

Unable to store timestamp in Dynamo DB using Nodejs 16 version Lambda


I am unable to store timestamp in Dynamo DB using Node JS Lambda. i am new to Node JS.

while run the test case, it was stored. but while trigger this lambda function getting error.

i was try to insert below timestamp

LastUpdateTimestamp The date and time this contact was last updated, in UTC time.

Type: String (yyyy-mm-ddThh:mm:ssZ)

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0
const AWS = require('aws-sdk');
const ddb = new AWS.DynamoDB();

exports.handler = async (event) => {
    
    var surveyResults = {};
    var data = event.Details.ContactData.Attributes;    // extract the contact attributes from the Amazon Connect event
    
    Object.keys(data).forEach(element => {
       if (element.startsWith("survey_result_")) {
           surveyResults[element] = { S: data[element] };
       }
    });
    
    var params = {
        TableName: process.env.TABLE,
        Item: {
            contactId: { S: event.Details.ContactData.ContactId},
            date: { S: event.Details.ContactData.LastUpdateTimestamp},
            surveyId: { S: event.Details.ContactData.Attributes.surveyId },
            ...surveyResults
        }
    }
    
    try {
        await ddb.putItem(params).promise();    // write the object to the DynamoDB table
    } catch (err) {
        console.log(err);
    }

    const response = {
        statusCode: 200,
        body: JSON.stringify('OK'),
    };
    
    return response;
};

Test Data:

{
  "Name": "ContactFlowEvent",
  "Details": {
    "ContactData": {
      "Attributes": {
        "surveyId": "123456",
        "survey_result_1": "4",
        "survey_result_2": "5"
      },
      "Channel": "VOICE",
      "ContactId": "5ca32fbd-8f92-46af-92a5-6b0f970f0efe",
      "LastUpdateTimestamp": "2023-02-14T06:52:29Z",
      "CustomerEndpoint": {
        "Address": "+11234567890",
        "Type": "TELEPHONE_NUMBER"
      },
      "InitialContactId": "5ca32fbd-8f92-46af-92a5-6b0f970f0efe",
      "InitiationMethod": "API",
      "InstanceARN": "arn:aws:connect:us-east-1:123456789012:instance/9308c2a1-9bc6-4cea-8290-6c0b4a6d38fa",
      "MediaStreams": {
        "Customer": {
          "Audio": {
            "StartFragmentNumber": "91343852333181432392682062622220590765191907586",
            "StartTimestamp": "1565781909613",
            "StreamARN": "arn:aws:kinesisvideo:us-east-1:123456789012:stream/connect-contact-a3d73b84-ce0e-479a-a9dc-5637c9d30ac9/1565272947806"
          }
        }
      },
      "PreviousContactId": "5ca32fbd-8f92-46af-92a5-6b0f970f0efe",
      "Queue": null,
      "SystemEndpoint": {
        "Address": "+11234567890",
        "Type": "TELEPHONE_NUMBER"
      }
    },
    "Parameters": {}
  }
}

Error:

2023-02-15T14:10:26.426Z    94fad25e-bcdb-443b-95c0-47640bfaba34    INFO    ValidationException: Supplied AttributeValue is empty, must contain exactly one of the supported datatypes
    at Request.extractError (/var/runtime/node_modules/aws-sdk/lib/protocol/json.js:52:27)
    at Request.callListeners (/var/runtime/node_modules/aws-sdk/lib/sequential_executor.js:106:20)
    at Request.emit (/var/runtime/node_modules/aws-sdk/lib/sequential_executor.js:78:10)
    at Request.emit (/var/runtime/node_modules/aws-sdk/lib/request.js:686:14)
    at Request.transition (/var/runtime/node_modules/aws-sdk/lib/request.js:22:10)
    at AcceptorStateMachine.runTo (/var/runtime/node_modules/aws-sdk/lib/state_machine.js:14:12)
    at /var/runtime/node_modules/aws-sdk/lib/state_machine.js:26:10
    at Request.<anonymous> (/var/runtime/node_modules/aws-sdk/lib/request.js:38:9)
    at Request.<anonymous> (/var/runtime/node_modules/aws-sdk/lib/request.js:688:12)
    at Request.callListeners (/var/runtime/node_modules/aws-sdk/lib/sequential_executor.js:116:18) {
  code: 'ValidationException',
  time: 2023-02-15T14:10:26.328Z,
  requestId: 'F5JJOCF20D507JCFRO7FEMAH6VVV4KQNSO5AEMVJF66Q9ASUAAJG',
  statusCode: 400,
  retryable: false,
  retryDelay: 15.458319111471575
}

Solution

  • const AWS = require('aws-sdk');
    const ddb = new AWS.DynamoDB();
    
    exports.handler = async (event) => {
        
        var surveyResults = {};
        var data = event.Details.ContactData.Attributes;    // extract the contact attributes from the Amazon Connect event
        
        Object.keys(data).forEach(element => {
           if (element.startsWith("survey_result_")) {
               surveyResults[element] = { S: data[element] };
           }
        });
        var contact_params = {
      ContactId: event.Details.ContactData.InitialContactId, /* required */
      InstanceId: 'paste your instance id' /* required */
    };
    var connect = new AWS.Connect();
    console.log('describeContact');
    /*connect.describeContact(contact_params, function(err, data) {
      if (err) console.log(err, err.stack); // an error occurred
      else     console.log(data);           // successful response
    });*/
    const attributes = await connect.describeContact(contact_params).promise();
    console.log(attributes)
    console.log(typeof attributes.Contact.LastUpdateTimestamp)
    var agent_params = {
      InstanceId: 'paste your instance id', /* required */
      UserId: attributes.Contact.AgentInfo.Id /* required */
      
    };
    const agent = await connect.describeUser(agent_params).promise();
    let agent_username = "";
    if(agent_username != null){
    agent_username = agent.User.Username; 
    }
    console.log(agent)
    const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
        var params = {
            TableName: process.env.TABLE,
            Item: {
                contactId: { S: event.Details.ContactData.ContactId},
                surveyId: { S: event.Details.ContactData.Attributes.surveyId },
                date: { S: attributes.Contact.LastUpdateTimestamp.toLocaleDateString()},
                time: { S: attributes.Contact.LastUpdateTimestamp.toLocaleTimeString()},
                agentname: {S: agent_username},
                monthnumber: { S: attributes.Contact.LastUpdateTimestamp.toLocaleDateString().split("/")[0]},
                monthname: { S: months[parseInt(attributes.Contact.LastUpdateTimestamp.toLocaleDateString().split("/")[0])-1]},
                ...surveyResults
            }
        }
        
        
        
        try {
            await ddb.putItem(params).promise();    // write the object to the DynamoDB table
        } catch (err) {
            console.log(err);
        }
    
        const response = {
            statusCode: 200,
            body: JSON.stringify('OK'),
        };
        
        return response;
    };