Home > Mobile >  convert nodejs function to AWS Lambda compatible
convert nodejs function to AWS Lambda compatible

Time:12-30

I am pretty new to both nodejs and AWS Lambda. I have created a very small nodejs function that is working fine locally. Now I need to run it on AWS Lambda, but looks like there are some handlers requirement which I am not understanding completely.

Below is my nodejs function that I need to run it on Lambda. Any idea what changes do I need to make to execute it on AWS? Thanks

(async function () {
DOMAIN = "abc.xyz.com";
KEY = "***";
const mailchimpClient = require("@mailchimp/mailchimp_transactional")(KEY);
    const run = async () => {
          const response = await mailchimpClient.senders.addDomain({
            domain: DOMAIN,
          });
          console.log(response);
        };
        
        run();
})();

CodePudding user response:

Basically you just need to export a function with a specific name: handler

exports.handler =  async function(event, context) {
  console.log("EVENT: \n"   JSON.stringify(event, null, 2))
  return "foo.bar"
}

In this handler, you just need to return something to mark as success or throw an error to mark as failure.

In your case, this should work:

var DOMAIN = "abc.xyz.com";
var KEY = "***";
const mailchimpClient = require("@mailchimp/mailchimp_transactional")(KEY);

exports.handler =  async function(event, context) {
  const response = await mailchimpClient.senders.addDomain({
    domain: DOMAIN,
  });
  console.log(response);
  return "success"
}

Here more examples and advanced configurations:

CodePudding user response:

It depends if you are using any framework to create your aws serverless code.

However, your usual code would be somthing like this.

    exports.handler = function(event, context) {
      console.log('Lambda A Received event:', JSON.stringify(event, null, 2));
      context.succeed('Hello '   event.name);
    };

If you want a easier way to work with AWS serverless code such as Lambdas look at arc.codes

Also, here is a link to the AWS docs https://docs.aws.amazon.com/lambda/latest/dg/nodejs-handler.html

  • Related