Basics of a Lambda function / code in NodeJS that will write a new entry (passed as event data) to the AmazonDB database
'use strict';
/*
This code is used to make request from database table for password of entry with userId specified 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",
"date": "Mon Aug 29 2016 23:57:25 GMT+0000 (UTC)",
"password": "whateverIspassword123"
}
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');
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
//This is the MAIN function that is called by Lambda system, passing event and context
// see above for expected event data attributes that will be processed below to use as data want to enter into our bikers table
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 verify is userId specified has password specified in database var userID;
var password; //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; password = requestBody.password; } else if(httpMethod !== undefined && httpMethod == "GET") //if GET method type { userID = queryStringParams.userId; 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 }
//simple log to see what is going on.
console.log(userID + "," + password );
var tableName = "blindbike-mobilehub-1926030853-biker"; //this is the name of YOUR project's dynamoDB table
var params = {
AttributesToGet: [
"password"
],
TableName:tableName,
Key : {
"userId" : userID
}
}
//make request to get the entry from database table with the
// above key specified for user id in the params variable
db.getItem(params, function(err, data) {
if (err) {
console.log(err); // an error occurred
context.fail(new Error("failed to access databse"));
callback(new Error("Failed database retrieveal for verification"));
}
else
{
console.log("success getting item"); console.log(data); // successful response
var returned_password = data.Item.password;
console.log("returned password is: " + returned_password);
if(password != returned_password) //fail verification STEP 4
{ console.log("Verification FAILED, passwords not the same");
var error_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,
verifiedPassword: password,
verificationPassed: "FAILED"
};
var error_response = {
statusCode: responseCode,
headers: {
"x-custom-header" : "custom header value"
},
body: JSON.stringify(error_responseBody)
};
//context.fail(error_response, "Failed verification, passwords not the same");
callback(new Error("Failed verification, passwords not the same"), JSON.stringify(error_response));
}
else
{
console.log("passwords are the same");
//*******************************************************************************
// 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,
verifiedPassword: password,
verificationPassed: "true"
};
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));
}// end else passwords the same
}//end else get successfull
});
console.log(params);
|