Basics of a Lambda function / code in NodeJS that will write a new entry (passed as event data) to the AmazonDB database" __
EXPECT data input from POST method call
'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", "password": "whateverIspassword123",
"firstName" : "Lynne",
"lastName": "Grewe"
}
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"
date_lastAccess": "Mon Aug 29 2016 23:57:25 GMT+0000 (UTC)" //set by this server code not passed in
*/
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("request body : " + 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;
console.log("Http method = " + httpMethod);
//********************************************************************************************
//business logic --read in input and create new user entry in biker table
var userID;
var password;
var firstName;
var lastName;
//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;
firstName = requestBody.firstName;
lastName = requestBody.lastName;
password = requestBody.password; }
else if(httpMethod !== undefined && httpMethod == "GET") //if GET method type
{
userID = queryStringParams.userId;
firstName = queryStringParams.firstName;
lastName = queryStringParams.lastName;
password = queryStringParams.password;
console.log("userid INPUT" + userID + " and method type = " + httpMethod + "and queryParameters= " + JSON.stringify(queryStringParams));
}
else //if a not POST/PUT/GET
{
userID = event.userId; //get userID from event
password = event.password; //get password from event
firstName = event.firstName;
lastName = event.lastName;
console.log("userid INPUT" + userID + " and method type = " + httpMethod + " password=" +password + " firstName=" + firstName + " lastName=" + lastName + " and queryParameters= " + JSON.stringify(queryStringParams));
}
//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 + "," + password +","+ datetime);
var tableName = "blindbike-mobilehub-1926030853-biker"; //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,
"password": password,
"date_lastAccess": datetime,
"firstName": firstName,
"lastName": lastName
};
var params = {
TableName:tableName,
Item: item
};
console.log(params);
console.log("About to create new entry in Database table biker");
//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 user to biker database table"); }
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
};
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 biker table completed");
context.succeed(response);
}
});
}; |