Andy Pohl
Andy Pohl

Reputation: 253

passing query params for aws lambda function

I am trying to set up a Lambda function that will pull query params that are passed into the API Gateway URL that is created. (Sidebar: I am still pretty green when it comes to programming, so please forgive any unintentional confusion regarding how to name things on my part). I've wrapped a few REST calls within a fiber using Synchronize.JS, and it works great when I hard code the variables that I want to pass into the various REST urls, but our goal is to be able to pass different parameters that will act as global variables for the different REST calls being made. This is what I currently have...

// Dependendies
var request = require('superagent');
var sync = require('synchronize');


exports.handler = function(event, context) {

    sync.fiber(function() {
        var followingArray = [];
        var followersArray = [];
        var postsCountArray = [];
        var allSqorCountArray = [];
        var trendingPostAuthorArray = [];
        var hashtagCountArray = [];
        var notificationCountArray = [];

        var getParam = function(query){
                var SearchString = window.location.search.substring(1);
                var VariableArray = SearchString.split('&');
                for(var i = 0; i < VariableArray.length; i++){
                var KeyValuePair = VariableArray[i].split('=');
                if(KeyValuePair[0] == query){
                    return KeyValuePair[1];
                }
                };
        };

        var userId = getParam('userId');
        var limit = getParam('limit');
        var offset = getParam('offset');

        var restCallOne = function() {
            request('https://someurl.com/etc/' + userId + '/follows?limit=' + limit + '&offset=' + offset)
            .end(function(err, res) {
                if (err) {
                    console.log('Request 1');
                    context.fail("Danger Will Robinson!!! Follows Count Does Not Like You!!");
                } else {
                    var followsCount = res.body.total_count;
                    followingArray.push(followsCount);
                }
            });
        };

        var restCallTwo = function() {
            request
            .get('https://someurl.com/etc/etc/etc?limit=' + limit + '&offset=' + offset)
            .set({'access-token': 'someAccessToken'})
            .end(function(err, res) {
                if(err) {
                    console.log('Request 4');
                    context.fail("Danger Will Robinson!!  The All Sqor Feed is moody");
                } else {
                    var allSqorCount = res.body.total_count;
                    allSqorCountArray.push(allSqorCount);
                }
            });
        };

        var restCallThree = function() {
            request
            .get('https://someUrl.com/etc/' + userId + '/followers?limit=' + limit + '&offset=' + offset)
            .end(function(err, res) {
                if (err) {
                    console.log('Request 3');
                    context.fail("Danger Will Robinson!!! Following Count Done Smacked You Upside The Head!!");
                } else {
                    var count = res.body.total_count;
                    followersArray.push(count);
                    context.done(null, 'The total number of people that follow Andy is ' + followersArray[0] +
                                       ', and the number of people that Andy follows is ' + followingArray[0] + 
                                       ', and the number of posts in his feed is ' + allSqorCountArray[0]);
                }
            });
        };

        try {
            restCallOne(userId, limit, offset);
        } catch(errOne) {
            console.log("Error on call 1!!");
        }

        try {
            restCallTwo(limit, offset);
        } catch(errTwo) {
            console.log("Error on call 2!!");
        }

        try {
            restCallThree(userId, limit, offset);
        } catch(errThree) {
            console.log("Error on call 3!!");
        }
    });
};

The API Gateway URL that was generated when I linked it with this function is as such: https://someID.execute-api.us-east-1.amazonaws.com/syncFunctionalParams

but I'd like to be able to pass something like this in, and use the params within my Lambda function to return the correct information from the rest calls: https://someID.execute-api.us-east-1.amazonaws.com/syncFunctionalParams?userId=212733&limit=25&offset=0

Is this possible?? Am I way off track with this?

Upvotes: 5

Views: 3811

Answers (1)

Ryan
Ryan

Reputation: 5973

You need to setup a mapping template in API Gateway. If you know the name of your parameters ahead of time your template could look like this:

{
  "userId": "$input.params('userId')",
  "limit": "$input.params('limit')",
  "offset": "$input.params('offset')"
}

Where each $input.params('...') will get evaluated and the value in your query string will be put in its place when the event is passed to Lambda.

If you don't know the parameter names ahead of time you will have to do some parsing in Lambda. Your mapping template would look like this:

{
  "querystring": "$input.params().querystring"
}

Which will end up looking like this in the event that is passed to Lambda:

{
  "querystring": "{limit=25, offset=0, userId=212733}"
}

And then you would parse event.querystring instead of window.location.search in your getParam(). Obviously you would need to change some of the logic since you'll be splitting on commas instead of ampersands and you'd need to get rid of the curly brackets. Which by the way, since you are on the server at this point you don't have a window object.

Upvotes: 3

Related Questions