Skip to content

Instantly share code, notes, and snippets.

@LB-Digital
Created June 29, 2019 17:40
Show Gist options
  • Save LB-Digital/2bec9379df1937083819990e758e1990 to your computer and use it in GitHub Desktop.
Save LB-Digital/2bec9379df1937083819990e758e1990 to your computer and use it in GitHub Desktop.
AWS DynamoDB simple scan/put operations
// leads/read.read
'use_strict';
const uuid = require('uuid');
const AWS = require('aws-sdk');
const IsEmail = require('isemail');
const dynamoDb = new AWS.DynamoDB.DocumentClient();
module.exports.create = function(event, context, callback) {
var timestamp = new Date().getTime();
var data,
error;
if (event.body === null){
// request body does not exist
error = "missing_request_body";
} else{
// parse event body
data = JSON.parse(event.body);
// check for errors in request body
if (typeof data.name !== "string" || typeof data.email !== "string"){
// name/email missing
error = "invalid_parameter";
} else if (data.name == "" || data.email == ""){
// name/email blank
error = "blank_parameter";
}else if (!IsEmail.validate(data.email)){
// invalid email
error = "invalid_email";
}
}
if (error){
return callback(null, {
statusCode: 400,
headers: { 'Content-Type':'text/plain' },
body: error
});
}
// valid name & email, continue...
const scanParams = {
TableName: process.env.DYNAMODB_TABLE,
FilterExpression: '#email = :email',
ExpressionAttributeNames: {
'#email': 'email'
},
ExpressionAttributeValues: {
':email': data.email
}
};
dynamoDb.scan(scanParams, (error, scanData)=>{
if (error){
console.error(error);
return callback(null, {
statusCode: 500,
headers: { 'Content-Type': 'text/plain' },
body: "database_error"
});
}
if (scanData.Count > 0){
return callback(null, {
statusCode: 400,
headers: { 'Content-Type': 'text/plain' },
body: "email_exists"
});
}
// email doesn't yet exist... save lead
const putParams = {
TableName: process.env.DYNAMODB_TABLE,
Item: {
id: uuid.v1(),
name: data.name,
email: data.email,
createdAt: timestamp
}
};
// write lead to database
dynamoDb.put(putParams, (error)=>{
if (error){
console.error(error);
return callback(null, {
statusCode: error.statusCode || 501,
headers: { 'Content-Type':'text/plain' },
body: "leads service CREATE failed."
});
}
// SUCCESS!
return callback(null, {
statusCode: 200,
headers: { 'Content-Type':'text/plain' },
body: "success"
});
});
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment