The next step is to create a lambda function that retrieves campaigns.

The function is a Node.js function and it looks like the following:

'use strict'; //1

var AWS = require('aws-sdk'); //2

var S3 = new AWS.S3(); //3

var bucket = 'mtedone-pulse-serverless'; //4

exports.handler = function (event, context, callback) { //5

    const done = function (err, res) {
        callback(null, {
            statusCode: err ? '400' : '200',
            body: err ? JSON.stringify(err) : JSON.stringify(res),
            headers: {
                'Content-Type': 'application/json',
                'Access-Control-Allow-Origin': '*' //6
            }
        });
    };

    console.log(context); //7

    S3.getObject({ //8
        Bucket: bucket,
        Key: 'data/campaignsResponse.json' //9
    }, function (err, data) { //10
        done(err, err ? null : JSON.parse(data.Body.toString()));
    });
};

Let’s see this function a bit more in detail:

  1. This instructs the Javascript engine to use strict parsing
  2. We get access to the Node.js AWS SDK and assign the whole sdk to the variable AWS
  3. Then we assign the S3 sdk (subset of the whole AWS function) to the variable S3
  4. Then we set the variable bucket with the value of our S3 bucket. Remember this is unique to you, so you should change it.
  5. Here, we are using the Lambda engine exports capability to export a function externally. The function has three arguments:
    1. event which we will not use it right now
    2. context which contains the context in which the Lambda function is running
    3. callback which is the function that the Lambda function has to invoke once done.
  6. This is a CORS (Cross Origin Resource Sharing) header
  7. This is a way to log what’s happening during execution
  8. This is the invocation of the GetObject method on S3, where we specify the bucket and, for now, a static file containing the campaigns data in JSON format.
  9. This is the name of the file on the S3 bucket that contains the static data
  10. This is the handling function that invokes the done function passing either an error object or the S3 data coming from the file

This is how the lambda function appears on AWS once it has been created. As you can see, because we have assigned the role defined in this page to the Lambda function, we can see that it has write access to the CloudWatch Logs and read access to the S3 bucket.

We need to add the data folder and the campaignsResponse.json file to the S3 bucket or the lambda function won’t be able to find it.

The campaignsResponse.json file can be downloaded here. In case you just want to copy and paste its content, you can use the text below.

{
  "_embedded": {
    "campaignResources": [
      {
        "campaign": {
          "id": 1,
          "name": "valid-campaign",
          "status": "ACTIVE",
          "validFrom": "2018-12-10",
          "validTo": "2020-12-20",
          "totalHappies": 0,
          "totalSoAndSos": 0,
          "totalUpsets": 0
        },
        "_links": {
          "/activeCampaigns": {
            "href": "http://localhost:8282/activeCampaigns"
          },
          "self": {
            "href": "http://localhost:8282/campaigns/1"
          }
        }
      },
      {
        "campaign": {
          "id": 2,
          "name": "valid-campaign",
          "status": "ACTIVE",
          "validFrom": "2018-12-10",
          "validTo": "2020-12-20",
          "totalHappies": 0,
          "totalSoAndSos": 0,
          "totalUpsets": 0
        },
        "_links": {
          "/activeCampaigns": {
            "href": "http://localhost:8282/activeCampaigns"
          },
          "self": {
            "href": "http://localhost:8282/campaigns/2"
          }
        }
      }
    ]
  },
  "_links": {
    "self": {
      "href": "http://localhost:8282/activeCampaigns"
    }
  }
}

Don’t worry too much about the content right now, we will change it as we progress.

Your S3 bucket should now have a data folder with a campaignsResponse.json file in it as shown below.

Now we can test the function. First, we will create a test event. As this function doesn’t require any inputs, we can simply pass in an empty JSON object. So we can select the “Configure test event” button and select the “Create new test event” radio button. This will show something like the following picture:

We can assign the name GetCampaignTestEvent and remove the key/value content of the JSON file resulting in the following:

And then we can press the Create button. Now we can test the function by pressing the Test button.

And we should be able to see the results.

Without entering too much into details, you can see that the status code is 200 (OK) and that the body contains the static file content that we have uploaded under the data folder. The logs also contain some information about the lambda context.

That’s it! We have created our first Lambda function that retrieves and prints to the logs the content of a static file on S3.