JSON Error in Lambda Function - Setting up a SMS Registration System with AWS Pinpoint

86 views Asked by At

I'm attempting to setup an SMS Registration System with AWS Pinpoint and SNS. However, I can't get past the creation of the Lambda function following their instructions (example).

I've followed the guide here to setup the entire system, Tutorial: Setting up an SMS registration system, at https://docs.aws.amazon.com/pinpoint/latest/developerguide/tutorials-two-way-sms.html

I followed the instructions in Step 3 - create a Lambda function. I got to the point where I "created" the function, and the next step was to replace the existing code,

console.log('Loading function');

export const handler = async (event, context) => {
    //console.log('Received event:', JSON.stringify(event, null, 2));
    console.log('value1 =', event.key1);
    console.log('value2 =', event.key2);
    console.log('value3 =', event.key3);
    return event.key1;  // Echo back the first key value
    // throw new Error('Something went wrong');
};

with the sample code:


var AWS = require('aws-sdk');
var pinpoint = new AWS.Pinpoint({region: process.env.region}); 

// Make sure the SMS channel is enabled for the projectId that you specify.
// See: https://docs.aws.amazon.com/pinpoint/latest/userguide/channels-sms-setup.html
var projectId = process.env.projectId;

// You need a dedicated long code in order to use two-way SMS. 
// See: https://docs.aws.amazon.com/pinpoint/latest/userguide/channels-voice-manage.html#channels-voice-manage-request-phone-numbers
var originationNumber = process.env.originationNumber;

// This message is spread across multiple lines for improved readability.
var message = "ExampleCorp: Reply YES to confirm your subscription. 2 msgs per "
            + "month. No purchase req'd. Msg&data rates may apply. Terms: "
            + "example.com/terms-sms";
            
var messageType = "TRANSACTIONAL";

exports.handler = (event, context, callback) => {
  console.log('Received event:', event);
  validateNumber(event);
};

function validateNumber (event) {
  var destinationNumber = event.destinationNumber;
  if (destinationNumber.length == 10) {
    destinationNumber = "+1" + destinationNumber;
  }
  var params = {
    NumberValidateRequest: {
      IsoCountryCode: 'US',
      PhoneNumber: destinationNumber
    }
  };
  pinpoint.phoneNumberValidate(params, function(err, data) {
    if (err) {
      console.log(err, err.stack);
    }
    else {
      console.log(data);
      //return data;
      if (data['NumberValidateResponse']['PhoneTypeCode'] == 0) {
        createEndpoint(data, event.firstName, event.lastName, event.source);
      } else {
        console.log("Received a phone number that isn't capable of receiving "
                   +"SMS messages. No endpoint created.");
      }
    }
  });
}

function createEndpoint(data, firstName, lastName, source) {
  var destinationNumber = data['NumberValidateResponse']['CleansedPhoneNumberE164'];
  var endpointId = data['NumberValidateResponse']['CleansedPhoneNumberE164'].substring(1);
  
  var params = {
    ApplicationId: projectId,
    // The Endpoint ID is equal to the cleansed phone number minus the leading
    // plus sign. This makes it easier to easily update the endpoint later.
    EndpointId: endpointId,
    EndpointRequest: {
      ChannelType: 'SMS',
      Address: destinationNumber,
      // OptOut is set to ALL (that is, endpoint is opted out of all messages)
      // because the recipient hasn't confirmed their subscription at this
      // point. When they confirm, a different Lambda function changes this 
      // value to NONE (not opted out).
      OptOut: 'ALL',
      Location: {
        PostalCode:data['NumberValidateResponse']['ZipCode'],
        City:data['NumberValidateResponse']['City'],
        Country:data['NumberValidateResponse']['CountryCodeIso2'],
      },
      Demographic: {
        Timezone:data['NumberValidateResponse']['Timezone']
      },
      Attributes: {
        Source: [
          source
        ]
      },
      User: {
        UserAttributes: {
          FirstName: [
            firstName
          ],
          LastName: [
            lastName
          ]
        }
      }
    }
  };
  pinpoint.updateEndpoint(params, function(err,data) {
    if (err) {
      console.log(err, err.stack);
    }
    else {
      console.log(data);
      //return data;
      sendConfirmation(destinationNumber);
    }
  });
}

function sendConfirmation(destinationNumber) {
  var params = {
    ApplicationId: projectId,
    MessageRequest: {
      Addresses: {
        [destinationNumber]: {
          ChannelType: 'SMS'
        }
      },
      MessageConfiguration: {
        SMSMessage: {
          Body: message,
          MessageType: messageType,
          OriginationNumber: originationNumber
        }
      }
    }
  };

  pinpoint.sendMessages(params, function(err, data) {
    // If something goes wrong, print an error message.
    if(err) {
      console.log(err.message);
    // Otherwise, show the unique ID for the message.
    } else {
      console.log("Message sent! " 
          + data['MessageResponse']['Result'][destinationNumber]['StatusMessage']);
    }
  });
}

I added the environment variables per instructions, and then deployed. Next step was to test the function, and received the following results:

Status: Failed

Test Event Name
MyFunctionTest

Response
{
  "errorType": "ReferenceError",
  "errorMessage": "require is not defined in ES module scope, you can use import instead",
  "trace": [
    "ReferenceError: require is not defined in ES module scope, you can use import instead",
    "    at file:///var/task/index.mjs:1:11",
    "    at ModuleJob.run (node:internal/modules/esm/module_job:194:25)"
  ]
}

Function Logs
2023-10-28T23:13:35.836Z    undefined   ERROR   Uncaught Exception  {"errorType":"ReferenceError","errorMessage":"require is not defined in ES module scope, you can use import instead","stack":["ReferenceError: require is not defined in ES module scope, you can use import instead","    at file:///var/task/index.mjs:1:11","    at ModuleJob.run (node:internal/modules/esm/module_job:194:25)"]}
2023-10-28T23:13:37.506Z    undefined   ERROR   Uncaught Exception  {"errorType":"ReferenceError","errorMessage":"require is not defined in ES module scope, you can use import instead","stack":["ReferenceError: require is not defined in ES module scope, you can use import instead","    at file:///var/task/index.mjs:1:11","    at ModuleJob.run (node:internal/modules/esm/module_job:194:25)"]}
START RequestId: 6b99b840-cc0a-46da-862a-5c3c4014f1e7 Version: $LATEST
Unknown application error occurred
Runtime.Unknown
END RequestId: 6b99b840-cc0a-46da-862a-5c3c4014f1e7
REPORT RequestId: 6b99b840-cc0a-46da-862a-5c3c4014f1e7  Duration: 1932.76 ms    Billed Duration: 1933 ms    Memory Size: 128 MB Max Memory Used: 17 MB

Request ID
6b99b840-cc0a-46da-862a-5c3c4014f1e7
1

There are 1 answers

1
Thomas On BEST ANSWER

In your package.json change type to commonjs