CS4521:   Mobile and Topics in Web Programming

Lambda (nodeJS) funciton code for creating route in ROUTES database table

  • //STEP 0: setup use of class DynamoDB
  • //STEP 1: make a request to insert a new Route into the ROUTES table
  • //STEP 2: return if success
  • //STEP 3:return if failure



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 DynamoDB

CODE TO create Route

//
 // Copyright 2016 Amazon.com, Inc. or its affiliates (Amazon). All Rights Reserved.
//
// Code generated by AWS Mobile Hub. Amazon gives unlimited permission to
// copy, distribute and modify it.
//
'use strict';
/*
  This code is used to create a new entry into the Database of  bikers for blindBike.  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",
   "routeId": "1",
   "name": "Starbuck_Near_Home",
   "category":"Food",
   "number_traveled" : 22,
   "start_longitude": 37.657827,
   "start_latitude": -122.056546,
   "stop_longitude": 37.427294,
   "stop_latitude": -122.149199
   }
   
 	          TODO: extend this  code to make sure that the event parameters are not null and pass default  values if they 
 	          NOTE: date is optional.   Should add processing the fields of firstName, lastName and date to complete all of the
 	          values possible in each entry of the biker database table
*/ 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
 	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;
 	          console.log("requestbody: " + JSON.stringify(requestBody));
            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 ROUTE table
 	          var userId;   //get userID from event
 	          var routeId;
 	          var name;
 	          var category;
 	          var number_traveled;
 	          var start_longitude;
 	          var start_latitude;
 	          var stop_longitude;
 	          var stop_latitude;
   
 	          //IF a PUT method get the JSON data from body and not from event
 	          if(httpMethod !== undefined && (httpMethod == "PUT" || httpMethod == "POST"))
 	          {   console.log("before parse requestBody" + requestBody);
 	              requestBody = JSON.parse(requestBody); //expect input in JSON form
 	              console.log("requestBODY: "+ requestBody);
 	              userId  = requestBody.userId;   //get userID from event
 	              routeId = requestBody.routeId;
 	              name = requestBody.name;
 	              category = requestBody.category;
 	              number_traveled = parseInt(requestBody.number_traveled);
 	              start_longitude = parseFloat(requestBody.start_longitude);
 	              start_latitude = parseFloat(requestBody.start_latitude);
 	              stop_longitude = parseFloat(requestBody.stop_longitude);
 	              stop_latitude = parseFloat(requestBody.stop_latitude);
 	          }
 	          else if(httpMethod !== undefined && httpMethod == "GET")  //if GET method type
 	          {
 	              userId  = queryStringParams.userId;   //get userID from event
 	              routeId = queryStringParams.routeId;
 	              name = queryStringParams.name;
 	              category = queryStringParams.category;
 	              number_traveled = parseInt(queryStringParams.number_traveled);
 	              start_longitude = parseFloat(queryStringParams.start_longitude);
 	              start_latitude = parseFloat(queryStringParams.start_latitude);
 	              stop_longitude = parseFloat(queryStringParams.stop_longitude);
 	              stop_latitude = parseFloat(queryStringParams.stop_latitude);
 	          }
 	          else //do nothing and let fail if not GET or POST method type in next saftey check 
 	          {
 	              userId  = event.userId;   //get userID from event
 	              routeId = event.routeId;
 	              name = event.name;
 	              category = event.category;
 	              number_traveled = parseInt(event.number_traveled);
 	              start_longitude = parseFloat(event.start_longitude);
 	              start_latitude = parseFloat(event.start_latitude);
 	              stop_longitude = parseFloat(event.stop_longitude);
 	              stop_latitude = parseFloat(event.stop_latitude);
 	          }
 
 	          //saftey check
 	          if(userId === undefined || routeId === undefined || name === undefined || category === undefined || number_traveled === undefined || start_longitude === undefined || start_latitude === undefined || stop_longitude === undefined || stop_latitude === undefined)
 	          { console.log("error some input for entry undefined -- failing");
 	            context.fail("could not add new route to ROUTES database table"); }
 	          
            //this version of code generates the date rather than reading from the event, this could be altered
 	          var datetime =  new Date().toString(); // OR can use new Date().getTime().toString();
   
 	          //simple log to see what is going on.
 	          console.log(userId  + "," + routeId + "," + name + "," + category + "," + number_traveled + "," +start_longitude + "," + start_latitude + "," + stop_longitude + "," + start_longitude);
   
 	          var tableName =  "blindbike-mobilehub-1926030853-ROUTES";  //this is the name of YOUR project's dynamoDB table
            
            //this version of the code is creating a data entry only with the required userID and additional password and date
 	          // it is left as future work to add the other fields of firstName and lastName
 	          var item = {
             "userId": userId,
             "routeId": routeId,
             "name": name,
             "category": category,
             "number_traveled" : number_traveled,
             "start_longitude": start_longitude,
             "start_latitude": start_longitude,
             "stop_longitude": stop_longitude,
             "stop_latitude": stop_latitude
 	          };
   
 	          var params = {
 	                    TableName:tableName, 
 	                    Item: item
 	          };
   
 	          console.log(params);
            console.log("About to create new entry in Database table ROUTES");
            //ADD TO database using putItem method - this code is obviously specific to the DynamoDB class that is specific to Lambda
 	          db.putItem(params,function(err,data){
 	          if (err) 
 	          {  console.log(err); context.fail("could not add new route to ROUTE database table"); 
 	             console.log("input to db.put : " + params)
 	          }
   
 	          else
 	          { console.log("No error putting to database"); console.log(data);
   
 	            //*******************************************************************************
 	            // For demonstration purposes, we'll just echo these values back to the client
 	            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,
 	              name: name
 	            };
   
 	          var response = {
 	              statusCode: responseCode,
 	              headers: {
                   "x-custom-header" : "custom header value"
 	              },
   	          body: JSON.stringify(responseBody)
 	          };

 	          console.log("response: " + JSON.stringify(response))
 	          console.log("Database new user entry into ROUTE table completed");
 	          context.succeed(response);
 	          }
         });
   
    };

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

Here is the testing data

Here is output in console window

Here is entry added properly into ROUTES table

Using AWS generated app to test Cloud logic to test /createRoute path associated with the code

 

© Lynne Grewe