CS4521:   Mobile and Topics in Web Programming

Lambda (nodeJS) funciton code for retrieve of multiple routes entries in ROUTES database table-- this code will

  • //STEP 0: setup use of AWS DocumentClient class
  • //STEP 1: make a request from database table ROUTES, to get all entries associated with input userId specified
  • //STEP 2: cycle through each returned entry/item in the ROUTES table building out a JSON response
  • //STEP 3:return JSON wrapped results



First: Have a database table called ROUTES that contain routes

  • primary key - userId , routeId

  • other columns - name, category, number_traveled, start_longitude, start_latitude, stop_longitude, stop_latitude

Code

special note: uses the AWS class DocumentClient

'use strict';
/*
 	          This code is used to grab the 10 most popolar entries into the Database of  ROUTES for blindBike.
 	          To make this request the input to this program must contain the userId so can grab only ROUTES associated
 	          with that user. 
 	          Notice that the
 	          format is JSON (java script object notation) which is commonly used for data exchange with web services
 	          
    input event example
   "Item"  : {
                "userId": "lynne123"  
 	        }
 */
 	          
console.log('Loading function');
 	          
var doc =  require('dynamodb-doc');  //require javascript package for DynamoDB access
var db = new  doc.DynamoDB();   //create instance of DynamoDB access object
var AWS = require("aws-sdk");
var docClient = new AWS.DynamoDB.DocumentClient();//NEW using this for multiple item requests
   
console.log('Loaded Database Object');
   
exports.handler = function(event, context, callback) {
 	          var responseCode = 200;
 	          var requestBody, pathParams, queryStringParams, headerParams, stage,
 	          stageVariables, cognitoIdentityId, httpMethod, sourceIp, userAgent,
 	          requestId, resourcePath;
 	          console.log("request: " + JSON.stringify(event));
            // Request Body
 	          requestBody = event.body;
            if (requestBody !== undefined && requestBody !== null) {
                 // Set 'test-status' field in the request to test sending a specific response status code (e.g., 503)
 	               responseCode = JSON.parse(requestBody)['test-status'];
 	          }
            // Path Parameters
 	          pathParams = event.path;
            // Query String Parameters
 	          queryStringParams = event.queryStringParameters;
            // Header Parameters
 	          headerParams = event.headers;
            if (event.requestContext !== null && event.requestContext !== undefined) {
               var requestContext = event.requestContext;
               // API Gateway Stage
 	             stage = requestContext.stage;
               // Unique Request ID
 	             requestId = requestContext.requestId;
               // Resource Path
 	             resourcePath = requestContext.resourcePath;
               var identity = requestContext.identity;
               // Amazon Cognito User Identity
 	             cognitoIdentityId = identity.cognitoIdentityId;
               // Source IP
 	             sourceIp = identity.sourceIp;
               // User-Agent
 	             userAgent = identity.userAgent;
 	          }
             // API Gateway Stage Variables
 	           stageVariables = event.stageVariables;
             // HTTP Method (e.g., POST, GET, HEAD)
 	           httpMethod = event.httpMethod;
             //********************************************************************************************
 	          //business logic --read in input and create new user entry in biker table
   
 	          var userId ;   //get userID from event
 	          //IF a PUT method get the JSON data from body and not from event
 	          if(httpMethod !== undefined && (httpMethod == "PUT" || httpMethod =="POST"))
 	          {   requestBody = JSON.parse(requestBody); //expect input in JSON form
 	              userId = requestBody.userId;
 	              console.log("POST request with userid=" + userId + " and method type = " + httpMethod + "and requestBody= " + JSON.stringify(requestBody));
 	          }
 	          else if(httpMethod !== undefined && httpMethod == "GET")  //if GET method type
 	          {
 	             console.log("Get parameter data: " + JSON.stringify(queryStringParams));
  	         userId = queryStringParams.userId;
 	             console.log("userid INPUT" + userId + " and method type = " + httpMethod + "and queryParameters= " + JSON.stringify(queryStringParams));
 	          }
 	          else  //if not post
 	          {
   
 	            userId = event.userId;   //get userID from event
 	            console.log("INSIDE non POST request with userId= " + userId + " and method type = " + httpMethod + "and event= " + JSON.stringify(event));
 	          }
 
 	          //simple log to see what is going on.
 	          console.log(userId);
   
 	          var tableName =  "blindbike-mobilehub-1926030853-ROUTES";  //this is the name of YOUR project's dynamoDB table
 	          
  
             //make request to get the entry from database table with the
 	          // above key specified for user id in the params variable
   
 	          //*******Using query method of DocumentClient in AWS api
 	          var params2 = {
   
 	              TableName:tableName, 
 	              KeyConditionExpression: "#uid = :value", 
 	              ExpressionAttributeNames:{
                   "#uid": "userId"
 	              },
 	              ExpressionAttributeValues: {
                   ":value":userId
   	          } 
 	          };
 	          
console.log("params" + params2);
 	          
 docClient.query(params2, function(err, data) {
 	          if (err) {
 	            console.error("Unable to query. Error:", JSON.stringify(err, null, 2));
 	          } else {
 	            console.log("Query succeeded.");
 	            console.log("data" + data);
 	            //*******************************************************************************
 	            // For demonstration purposes, we'll just echo these values back to the client
 	            var routes = "{";
 	            var print_Routes = routes;
 	            // Cylce through each item retrieved from the Table using params2 query
 	            data.Items.forEach(function(item) {
 	               console.log(" -", item.name + ": " + item.userId);
   
 	               routes += "{ Item : " + JSON.stringify(item) + " }  ";
 	               print_Routes  += "{ Item :\n" + JSON.stringify(item) + "\n}\n";
 	             });
   
 	             routes += "   }"
 	             console.log(routes); // successful response
 	             console.log(print_Routes);
   
 	             var responseBody = {
 	               requestBody : requestBody,
 	               pathParams : pathParams,
 	               queryStringParams : queryStringParams,
 	               headerParams : headerParams,
 	               stage : stage,
 	               stageVariables : stageVariables,
 	               cognitoIdentityId : cognitoIdentityId,
 	               httpMethod : httpMethod,
 	               sourceIp : sourceIp,
 	               userAgent : userAgent,
 	               requestId : requestId,
 	               resourcePath : resourcePath,
 	               userId: userId,
 	               routes: JSON.stringify(routes)
 	             };
   
 	          var response = {
 	             statusCode: responseCode,
 	             headers: {
                  "x-custom-header" : "custom header value"
 	             },
 	             body: JSON.stringify(responseBody)
 	           };
   
 	          console.log("response: " + JSON.stringify(response))
 	          context.succeed(response);
 	          callback(JSON.stringify(response)); 
 	        }
 	    });
   
   console.log(params);
  
  };

Results

we see output as JSON response and LOG shows print out of the multiple routes for user "lynne123" presented as Item JSON formated objects

 

 

 

© Lynne Grewe