I am using the Github project here: https://github.com/danilop/LambdAuth/blob/master/LambdAuthCreateUser/index.js
I want to write tests so I can see if things get stored in the database correctly and to see the results of the functions.
I copied this Lambda function from the project above:
console.log('Loading function');
// dependencies
var AWS = require('aws-sdk');
var crypto = require('crypto');
var util = require('util');
var config = require('./config.json');
// Get reference to AWS clients
var dynamodb = new AWS.DynamoDB();
var ses = new AWS.SES();
function computeHash(password, salt, fn) {
// Bytesize
var len = 128;
var iterations = 4096;
if (3 == arguments.length) {
crypto.pbkdf2(password, salt, iterations, len, fn);
} else {
fn = salt;
crypto.randomBytes(len, function(err, salt) {
if (err) return fn(err);
salt = salt.toString('base64');
crypto.pbkdf2(password, salt, iterations, len, function(err, derivedKey) {
if (err) return fn(err);
fn(null, salt, derivedKey.toString('base64'));
});
});
}
}
function storeUser(email, password, salt, fn) {
// Bytesize
var len = 128;
crypto.randomBytes(len, function(err, token) {
if (err) return fn(err);
token = token.toString('hex');
dynamodb.putItem({
TableName: config.DDB_TABLE,
Item: {
email: {
S: email
},
passwordHash: {
S: password
},
passwordSalt: {
S: salt
},
verified: {
BOOL: false
},
verifyToken: {
S: token
}
},
ConditionExpression: 'attribute_not_exists (email)'
}, function(err, data) {
if (err) return fn(err);
else fn(null, token);
});
});
}
function sendVerificationEmail(email, token, fn) {
var subject = 'Verification Email for ' + config.EXTERNAL_NAME;
var verificationLink = config.VERIFICATION_PAGE + '?email=' + encodeURIComponent(email) + '&verify=' + token;
ses.sendEmail({
Source: config.EMAIL_SOURCE,
Destination: {
ToAddresses: [
email
]
},
Message: {
Subject: {
Data: subject
},
Body: {
Html: {
Data: '<html><head>'
+ '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />'
+ '<title>' + subject + '</title>'
+ '</head><body>'
+ 'Please click here to verify your email address or copy & paste the following link in a browser:'
+ '<br><br>'
+ '' + verificationLink + ''
+ '</body></html>'
}
}
}
}, fn);
}
exports.handler = function(event, context) {
var email = event.email;
var clearPassword = event.password;
computeHash(clearPassword, function(err, salt, hash) {
if (err) {
context.fail('Error in hash: ' + err);
} else {
storeUser(email, hash, salt, function(err, token) {
if (err) {
if (err.code == 'ConditionalCheckFailedException') {
// userId already found
context.succeed({
created: false
});
} else {
context.fail('Error in storeUser: ' + err);
}
} else {
sendVerificationEmail(email, token, function(err, data) {
if (err) {
context.fail('Error in sendVerificationEmail: ' + err);
} else {
context.succeed({
created: true
});
}
});
}
});
}
});
}
How do I test this?
I think you can test it with Jest.
Related
I'm having trouble accessing the access token of a Facebook user.
Here's my code
const urlToGetAccessToken =
"https://graph.facebook.com/v13.0/oauth/access_token";
const stateRootUrl = "dd";
const urlToGetOauthCode = "https://www.facebook.com/v13.0/dialog/oauth";
const urlToRedirectTo = process.env.BASE_CLIENT_URL + "/login?type=facebook";
router.get("/oauth", (req, res, next) => {
const FacebookApi = {
clientId: process.env.FACEBOOK_CLIENT_ID,
redirectUrl: urlToRedirectTo,
oauthUrl: urlToGetOauthCode,
scope: "email,public_profile",
state: `${stateRootUrl}`,
};
const {
clientId,
redirectUrl,
oauthUrl,
scope,
state
} = FacebookApi;
const url = `${oauthUrl}?response_type=code&client_id=${clientId}&scope=${scope}&state=${state}&redirect_uri=${redirectUrl}`;
return res.json({
status: "ok",
result: url,
});
});
router.get("/oauth/callback", (req, res, next) => {
if (req.query.code) {
const FacebookApi = {
clientId: process.env.FACEBOOK_CLIENT_ID,
clientSecret: process.env.FACEBOOK_CLIENT_SECRET,
redirectUrl: urlToRedirectTo
};
const {clientId, clientSecret, redirectUrl} = FacebookApi;
const url = urlToGetAccessToken +
"?client_id=" +
clientId +
"&client_secret=" +
clientSecret +
"&redirect_uri=" +
redirectUrl +
"&code=" +
req.query.code;
var op = {
method: "GET",
uri: url,
json: true, //Parse the JSON string in the response
};
request.get(op, async (error, response, body) => {
if (error) {
console.dir("Error " + error);
return res.json({
status: "error",
error,
});
}
if (response && response.body && response.body.access_token) {
const accessToken = response.body.access_token;
const userProfile = await FacebookService.getUserProfile(accessToken);
if (userProfile && userProfile.email && userProfile.email.length) {
User.findOrCreateFacebookUser(userProfile.id, userProfile.email, userProfile.first_name, userProfile.last_name)
.then((result) => {
if (result && result.length) {
const user = result[0];
if (user.status === 1) {
return res.json({
status: "error",
error: "Your user account has been flagged. This may happen if you missed too many calls.",
});
}
const payload = {
sub: user.id,
};
const token = jwt.sign(payload, process.env.JWT_SECRET, {
expiresIn: process.env.JWT_EXPIRESIN,
});
res.clearCookie("auth");
res.cookie("auth", token);
return res.json({
status: "ok",
result: {
token,
user
}
});
} else {
return res.json({
status: "error",
error: "There was an error processing your request. Please try another login method.",
});
}
})
.catch((err) => {
console.dir("Error " + err);
return res.json({
status: "error",
error: err,
});
});
} else {
console.dir("Facebook Oauth couldn't get email address");
return res.json({
status: "error",
error: "There was an error processing your request. Please try another login method.",
});
}
} else {
console.dir("Facebook Oauth couldn't get access token");
return res.json({
status: "error",
error: "There was an error processing your request. Please try another login method.",
});
}
});
}
});
I get the error An active access token must be used to query information about the current user.
when trying to make a call to the graph api
async getUserProfile(accessToken) {
var defer = Q.defer();
var op = {
method: "GET",
uri: "https://graph.facebook.com/v13.0/me",
json: true, //Parse the JSON string in the response
params: {
fields: ['id', 'email', 'first_name', 'last_name'].join(','),
access_token: accessToken,
}
};
console.dir(op);
request.get(op, async (error, response, body) => {
if (error) {
defer.reject(error);
} else if (response && response.body) {
defer.resolve(response.body);
} else {
defer.reject();
}
});
return defer.promise;
};
}
Does anyone know what I am doing wrong?
I am trying to post a file to s3 using createPresignedPost. The file is posting to my bucket but it is not respecting the file size constraint. Here is my code and the file upload is base64 encoded string.
function postObjectSignedUrl(req) {
const key = `${req + "/" + uuid.v4()}`;
return new Promise(function (resolve, reject) {
const params = {
Bucket: 'base',
Expires: 60 * 60, // in seconds,
Fields: {
key: key,
},
conditions: [
['content-length-range', 0,1000000]
]
}
s3.createPresignedPost(params, (err, data) => {
if (err) {
reject(err)
} else {
resolve(data);
}
})
})
}
My client side code is the following:
var data = new FormData();
const getUrl = await getSignedUrl();
const keys = getUrl["fields"];
$.each(keys, function(key,value){
data.append(key,value);
});
data.append("file", profilePic);
try {
const result = await fetch(getUrl["url"], {
method: "POST",
mode: "cors",
headers: {
'Access-Control-Allow-Origin': '*',
},
body: data
})
if (result.status === 204){
}
} catch (err) {
console.log(err, " error ")
}
Normally params attributes in NodeJS SDK are Upper Camel Case so you have to change "conditions" for "Conditions".
BTW you can change your url generator code as follow :)
function postObjectSignedUrl(req) {
const key = `${req + "/" + uuid.v4()}`;
const params = {
Bucket: 'base',
Expires: 60 * 60, // in seconds,
Fields: {
key: key,
},
Conditions: [
['content-length-range', 0,1000000]
]
}
return s3.createPresignedPost(params).promise();
})
Regards,
I create a ganache cli and initialize my accounts to have ethers using
ganache-cli -h "159.89.119.189" -a 3 -e "1000000000000000000000000000" --secure -u 0 -u 1 -u 2 -s 20
but after a couple of minutes, all accounts on the network are 0.
I'm not able to run any transactions or call contracts again.
A DApp i created connects to this private network
This is my app.js
App = {
web3Provider: null,
contracts: {},
account: 0x0,
coinbase: 0x0,
coinbase_amount: 0,
loading: false,
init: function () {
return App.initWeb3();
},
initWeb3: function () {
// initialize web3
if (typeof web3 !== 'undefined') {
//reuse the provider of the Web3 object injected by Metamask
App.web3Provider = web3.currentProvider;
} else {
//create a new provider and plug it directly into our local node
//App.web3Provider = new Web3.providers.HttpProvider('http://localhost:8545');
App.web3Provider = new Web3.providers.HttpProvider('http://159.89.119.189:8545');
}
web3 = new Web3(App.web3Provider);
App.getCoinbase();
return App.initContract();
},
hostname: function () {
return window.location.origin;
},
setAccount: function (address) {
App.account = address;
},
displayAccountInfo: function () {
// console.log(App);
if (App.account != 0) {
toastr.remove();
toastr.info('Getting Account Info', {timeOut: 300000});
$('#account').text(App.account);
App.getBalance();
}
},
getBalance: function() {
web3.eth.getBalance(App.account, function (err, balance) {
if (err === null) {
if(web3.fromWei(balance, "ether") == 0){
setTimeout(App.getBalance(), 60000);
} else {
console.log(web3.fromWei(balance, "ether"));
toastr.remove();
$('#accountBalance').text(web3.fromWei(balance, "ether") + " ETH");
}
}
})
},
getCoinbase: function () {
web3.eth.getCoinbase(function (err, account) {
if (err === null) {
App.coinbase = account;
// $('#account').text(account);
web3.eth.getBalance(account, function (err, balance) {
if (err === null) {
App.coinbase_amount = web3.fromWei(balance, "ether").toNumber();
console.log(App.coinbase, App.coinbase_amount)
}
})
}
});
},
transfer: function() {
web3.personal.unlockAccount(App.coinbase, "pass12345", 100000, function (err, result) {
console.log(result)
console.log(err)
web3.personal.unlockAccount(App.account, "pass#123", 100000, function (err, result) {
web3.eth.sendTransaction({
from: App.coinbase,
to: App.account,
value: web3.toWei(10, "ether")
}, function (err, result) {
if (err == null) {
console.log("sent money");
console.log(result)
console.log(err)
web3.eth.getBalance(App.account, function (err, balance) {
if (err === null) {
console.log(web3.fromWei(balance, "ether") + " ETH");
}
})
}
else {
console.log(err);
}
})
});
});
},
register: function () {
let email = $('#inputEmail');
let fname = $('#inputFname');
let lname = $('#inputLname');
let password = $('#inputPassword');
let btnRegister = $('#btnRegister');
if (email.val() == "" || fname.val() == "" || lname.val() == "" || password.val() == "") {
toastr.error('Please fill all fields');
return false;
}
btnRegister.attr("disabled", 'disabled');
web3.personal.newAccount("pass#123", function (err, data) {
let address = data;
if (err === null) {
let postData = {
email: email.val(),
fname: fname.val(),
lname: lname.val(),
password: password.val(),
address: data
}
$.ajax({
method: "POST",
url: App.hostname() + "/register",
data: postData,
success: function (data) {
console.log(data)
if (data.status == "success") {
web3.personal.unlockAccount(address, "pass#123", 1000, function (err, result) {
web3.eth.sendTransaction({
from: App.coinbase,
to: address,
value: web3.toWei(10, "ether")
}, function (err, result) {
if (err == null) {
console.log("sent money");
console.log(result)
web3.eth.getBalance(App.coinbase, function (err, balance) {
if (err === null) {
console.log("coinbase "+web3.fromWei(balance, "ether") + " ETH");
}
})
web3.eth.getBalance(address, function (err, balance) {
if (err === null) {
console.log(web3.fromWei(balance, "ether") + " ETH");
}
})
}
else {
console.log(err);
}
toastr.success("Success.");
window.location.href = App.hostname();
})
});
} else {
toastr.error(data.data);
}
btnRegister.attr("disabled", false);
},
error: function (err) {
toastr.error('Error Registering');
btnRegister.attr("disabled", false);
}
});
} else {
toastr.error('Error Registering');
btnRegister.attr("disabled", false);
return false;
}
})
},
login: function () {
let email = $('#inputEmail');
let password = $('#inputPassword');
let btnLogin = $('#btnLogin');
if (email.val() == "" || password.val() == "") {
toastr.error('Please fill all fields');
return false;
}
btnLogin.attr("disabled", 'disabled');
let postData = {
email: email.val(),
password: password.val(),
}
$.ajax({
method: "POST",
url: App.hostname() + "/login",
data: postData,
success: function (data) {
console.log(data)
if (data.status == "success") {
toastr.success("Success.");
window.location.href = App.hostname();
} else {
toastr.error(data.data);
}
btnLogin.attr("disabled", false);
},
error: function (err) {
toastr.error('Error Registering');
btnLogin.attr("disabled", false);
}
});
},
initContract: function () {
$.getJSON('Chainlist.json', function (chainListArtifact) {
// get the contract artifact file and use it to instantiate a truffle contract abstraction
App.contracts.ChainList = TruffleContract(chainListArtifact);
// set the provider for our contracts
App.contracts.ChainList.setProvider(App.web3Provider);
// listen to events
App.listenToEvents();
// retrieve the article from the contract
return App.reloadArticles();
});
},
reloadArticles: function () {
// avoid re-entry
if (App.loading) {
return
}
App.loading = true
// refresh account information because the balance might have changed
App.displayAccountInfo();
var chainListInstance;
App.contracts.ChainList.deployed().then(function (instance) {
chainListInstance = instance;
return chainListInstance.getArticlesForSale();
}).then(function (articleIds) {
$('#articlesRow').empty();
for (var i = 0; i < articleIds.length; i++) {
var articleID = articleIds[i];
chainListInstance.articles(articleID.toNumber())
.then(function (article) {
App.displayArticle(article[0], article[1], article[3], article[4], article[5], article[6])
});
}
App.loading = false;
}).catch(function (err) {
console.error(err.message);
App.loading = false;
});
},
sellArticle: function () {
// retrieve the detail of the article
var _article_name = $('#article_name').val();
var _description = $('#article_description').val();
var _price = web3.toWei(parseFloat($('#article_price').val() || 0), "ether");
const file = $('#article_image').prop('files')[0];
if ((_article_name.trim() == '') || (_price == 0)) {
// nothing to sell
return false;
}
const name = (+new Date()) + '-' + file.name;
const metadata = {
contentType: file.type
};
let ref = firebase.storage().ref();
const task = ref.child(name).put(file, metadata);
toastr.info('Processing.....', {timeOut: 30000});
task.then((snapshot) => {
const _image_url = snapshot.downloadURL;
console.log(_image_url);
web3.personal.unlockAccount(App.account, "pass#123", 1000, function (err, result) {
console.log(result);
console.log(err);
App.contracts.ChainList.deployed().then(function (instance) {
return instance.sellArticle(_article_name, _description, _price, _image_url, {
from: App.account,
gas: 500000
});
}).then(function (result) {
console.log(result);
$('#article_name').val("");
$('#article_description').val("");
$('#article_price').val("");
$('#article_image').val("");
}).catch(function (err) {
console.error(err);
});
});
}).catch((error) => {
console.error(error);
});
},
displayArticle: function (id, seller, name, description, price, image_url) {
var articlesRow = $('#articlesRow');
var etherPrice = web3.fromWei(price, "ether");
// retrieve the article template and fill it
var articleTemplate = $('#articleTemplate');
articleTemplate.find('.panel-title').text(name);
articleTemplate.find('.article-description').text(description);
articleTemplate.find('.article-price').text(etherPrice);
articleTemplate.find('.btn-image-url').attr('href', image_url);
articleTemplate.find('.btn-buy').attr('data-value', etherPrice);
articleTemplate.find('.btn-buy').attr('data-id', id);
if (seller == App.account) {
articleTemplate.find('.article-seller').text("You");
articleTemplate.find('.btn-buy').hide();
} else {
articleTemplate.find('.article-seller').text(seller);
articleTemplate.find('.btn-buy').show();
}
// buyer
// var buyer = article[1];
// if (buyer == App.account) {
// buyer = "You";
// } else if (buyer == 0x0){
// buyer = "None yet"
// }
// articleTemplate.find('.article-buyer').text(buyer);
// add this article
toastr.clear();
$('#articlesRow').append(articleTemplate.html());
},
// listen to events triggered by the contract
listenToEvents: function () {
App.contracts.ChainList.deployed().then(function (instance) {
instance.LogSellArticle({}, {}).watch(function (error, event) {
if (!error) {
$("#events").append('<li class="list-group-item">' + event.args._name + ' is now for sale</li>');
} else {
console.error(error);
}
App.reloadArticles();
});
instance.LogBuyArticle({}, {}).watch(function (error, event) {
if (!error) {
$('#sellBtn').attr("disabled", false);
$("#events").append('<li class="list-group-item">' + event.args._buyer + ' bought ' + event.args._name + '</li>');
} else {
console.error(error);
}
App.reloadArticles();
});
});
},
// retrieve article price from data-value and process buyArticle function
buyArticle: function () {
event.preventDefault();
// retrieve article Price
toastr.info('Processing.....', {timeOut: 30000});
$(event.target).attr("disabled", 'disabled');
$('#sellBtn').attr("disabled", 'disabled');
var price = parseFloat($(event.target).data('value'));
var articleID = parseFloat($(event.target).data('id'));
web3.personal.unlockAccount(App.account, "pass#123", 1000, function (err, result) {
console.log(result);
console.log(err);
App.contracts.ChainList.deployed().then(function (instance) {
return instance.buyArticle(articleID, {
from: App.account,
value: web3.toWei(price, "ether"),
gas: 500000
}).catch(function (error) {
console.error(error);
})
});
});
}
};
$(function() {
$(window).load(function() {
App.init();
// Initialize Firebase
var config = {
apiKey: "AIzaSyAQp34HzZS_3xckuxcVcsUWgCu8_p7UzxA",
authDomain: "comflo-1518513183870.firebaseapp.com",
databaseURL: "https://comflo-1518513183870.firebaseio.com",
projectId: "comflo-1518513183870",
storageBucket: "comflo-1518513183870.appspot.com",
messagingSenderId: "798445619042"
};
firebase.initializeApp(config);
});
});
Same thing happens when i run a geth private server.
I'm using a node app with express.
Im trying to create a skill that will scan or query my dynamodb table which includes a date column, filmanme, and time.
Here is the code i have so far.
console.log('Loading function');
var AWSregion = 'us-east-1'; // us-east-1
var AWS = require('aws-sdk');
var dclient = new AWS.DynamoDB.DocumentClient();
var getItems = (event, context, callback)=>{
dclient.get(event.params,(error,data)=>{
if(error){
callback(null,"error occurerd");
}
else{
callback(null,data);
}
});
};
exports.handler = getItems;
exports.handler = (event, context, callback) => {
try {
var request = event.request;
if (request.type === "LaunchRequest") {
context.succeed(buildResponse({
speechText: "Welcome to H.S.S.M.I skill, what would you like to find",
repromptText: "I repeat, Welcome to my skill, what would you like to find",
endSession: false
}));
}
else if (request.type === "IntentRequest") {
let options = {};
if (request.intent.name === "cinema") {
if (request.intent.slots.cimema !== undefined)
var sign = request.intent.slots.cinema.value;
//Check sign is valid
if (sign === undefined || sign === null) {
options.speechText = " sorry, i didn't understant your question. can you say that again?";
options.endSession = false;
context.succeed(buildResponse(options));
return;
}
if (request.intent.slots.zodiac !== undefined && !ValidateZodiacSign(sign)) {
options.speechText = ` The Zoadiac sign ${sign} is not a valid one. Please tell a valid zodiac sign .`;
options.endSession = false;
context.succeed(buildResponse(options));
return;
}
cinema(sign, function (cinema, error) {
if (error) {
context.fail(error);
options.speechText = "There has been a problem with the request.";
options.endSession = true;
context.succeed(buildResponse(options));
} else {
options.speechText = todaysFortune;
options.speechText += " . Have a nice day ahead . ";
options.sign = sign;
options.cardText = todaysFortune;
options.endSession = true;
context.succeed(buildResponse(options));
}
});
} else if (request.intent.name === "AMAZON.StopIntent" || request.intent.name === "AMAZON.CancelIntent") {
options.speechText = "ok, good bye.";
options.endSession = true;
context.succeed(buildResponse(options));
}
else if (request.intent.name === "AMAZON.HelpIntent") {
options.speechText = "My skill will read your table depending on what is asked. For example, you can ask what about a specific date. Please refer to skill description for all possible utterences.";
options.repromptText = "What is the data sign you want to know about today? If you want to exit from my skill please say stop or cancel."
options.endSession = false;
context.succeed(buildResponse(options));
}
else {
context.fail("Unknown Intent")
}
}
else if (request.type === "SessionEndedRequest") {
options.endSession = true;
context.succeed();
}
else {
context.fail("Unknown Intent type");
}
} catch (e) {
}
};
function buildResponse(options) {
var response = {
version: "1.0",
response: {
outputSpeech: {
"type": "SSML",
"ssml": `<speak><prosody rate="slow">${options.speechText}</prosody></speak>`
},
shouldEndSession: options.endSession
}
};
if (options.repromptText) {
response.response.reprompt = {
outputSpeech: {
"type": "SSML",
"ssml": `<speak><prosody rate="slow">${options.repromptText}</prosody></speak>`
}
};
}
return response;
}
function readDynamoItem(params, callback) {
var AWS = require('aws-sdk');
AWS.config.update({region: AWSregion});
var dynamodb = new AWS.DynamoDB();
console.log('reading item from DynamoDB table');
dynamodb.scan(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else{
console.log(data); // successful response
callback(JSON.stringify(data));
}
});
var docClient = new AWS.DynamoDB.DocumentClient();
//Get item by key
docClient.get(params, (err, data) => {
if (err) {
console.error("Unable to read item. Error JSON:", JSON.stringify(err, null, 2));
} else {
console.log("GetItem succeeded:", JSON.stringify(data, null, 2));
callback(data.Item.message); // this particular row has an attribute called message
}
});
}
///////////////////////////////////////////////////////////////////////////////
and here is my DBHandlder
const AWS = require('aws-sdk');
AWS.config.update({
region: "'us-east-1'"
});
var docClient = new AWS.DynamoDB.DocumentClient();
var table = "Cinema";
var getItems = (Id,callback) => {
var params = {
TableName: "cinema",
Key: {
"Id": Id
}
};
docClient.get(params, function (err, data) {
callback(err, data);
});
};
module.exports = {
getItems
};
i'm very new to this and i cant find muchsupport online for the skill i want to produce or anything similar.
I created a lambda function which works and will find the corresponding movie when i configure the test function to find a specified date, however this does not work with alexa
any input is helpful.
Is there a way to transfer the messages I get from SQS and send them over to Dynamodb? I've tried making a Lambda function using CloudWatch to trigger it every minute. I'm open to using any other services in AWS to complete this task. I'm sure there's a simple explanation to this that I'm just overlooking.
*Edit my code does not work, I'm looking for either a fix to my code or another solution to accomplish this.
**Edit got it working.
'use strict';
const AWS = require('aws-sdk');
const SQS = new AWS.SQS({ apiVersion: '2012-11-05' });
const Lambda = new AWS.Lambda({ apiVersion: '2015-03-31' });
const QUEUE_URL = 'SQS_URL';
const PROCESS_MESSAGE = 'process-message';
const DYNAMO_TABLE = 'TABLE_NAME';
function poll(functionName, callback) {
const params = {
QueueUrl: QUEUE_URL,
MaxNumberOfMessages: 10,
VisibilityTimeout: 10
};
// batch request messages
SQS.receiveMessage(params, function(err, data) {
if (err) {
return callback(err);
}
// parse each message
data.Messages.forEach(parseSQSMessage);
})
.promise()
.then(function(){
return Lambda.invokeAsync({})
.promise()
.then(function(data){
console.log('Recursion');
})
}
)
.then(function(){context.succeed()}).catch(function(err){context.fail(err, err.stack)});
}
// send each event in message to dynamoDB.
// remove message from queue
function parseSQSMessage(msg, index, array) {
// delete SQS message
var params = {
QueueUrl: QUEUE_URL,
ReceiptHandle: msg.ReceiptHandle
};
SQS.deleteMessage(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
}
// store atomic event JSON directly to dynamoDB
function storeEvent(event) {
var params = {
TableName : DYNAMO_TABLE,
Item: event
};
var docClient = new AWS.DynamoDB.DocumentClient();
docClient.put(params, function(err, data) {
if (err) console.log(err);
else console.log(data);
});
}
exports.handler = (event, context, callback) => {
try {
// invoked by schedule
poll(context.functionName, callback);
} catch (err) {
callback(err);
}
};
var aws = require( "aws-sdk" );
// get configuration defaults from config file.
var tableName = 'Table_Name';
var queueUrl = 'SQS_URL';
var dbClient = new aws.DynamoDB.DocumentClient();
var sqsClient = new aws.SQS();
// get config values from dynamodb - if the config values are found, then override existing values
// this will occur on every execution of the lambda which will allow real time configuration changes.
var updateConfig = function updateConfigValues(invokedFunction, cb) {
var params = {
TableName: "Table_NAME",
Key: {
"KEY": "KEY"
}
};
dbClient.get(params, function(err, data) {
if(err) {
console.log("ERR_DYNAMODB_GET", err, params);
}
else if(!data || !data.Item) {
console.log("INFO_DYNAMODB_NOCONFIG", params);
}
else {
queueUrl = data.Item.config.queueUrl;
tableName = data.Item.config.tableName;
}
return cb(err);
});
};
// save the email to dynamodb using conditional write to ignore addresses already in the db
var saveEmail = function saveEmail(messageBody, cb) {
var params = {
TableName:tableName,
Item:messageBody,
ConditionExpression : "attribute_not_exists(clickId)",
};
dbClient.put(params, function(err, data) {
cb(err, data);
});
};
var deleteMessage = function deleteMessage(receiptHandle, cb) {
var params = {
QueueUrl: queueUrl,
ReceiptHandle: receiptHandle
};
sqsClient.deleteMessage(params, function(err, data) {
cb(err, data);
});
}
exports.handler = function(event, context) {
updateConfig(context.invokedFunctionArn, function(err) {
if(err) {
context.done(err);
return;
}
console.log("INFO_LAMBDA_EVENT", event);
console.log("INFO_LAMBDA_CONTEXT", context);
sqsClient.receiveMessage({MaxNumberOfMessages:10 , QueueUrl: queueUrl}, function(err, data) {
if(err) {
console.log("ERR_SQS_RECEIVEMESSAGE", err);
context.done(null);
}
else {
if (data && data.Messages) {
console.log("INFO_SQS_RESULT", " message received");
var message = JSON.parse(data.Messages[0].Body);
var messageBody = message.Message;
messageBody = JSON.parse(messageBody);
// loops though the messages and replaces any empty strings with "N/A"
messageBody.forEach((item) => {
var item = item;
var custom = item.customVariables;
for (i = 0; i < custom.length; i++) {
if(custom[i] === ''){
custom[i] = 'N/A';
}
item.customVariables = custom;
}
for(variable in item) {
if(item[variable] === ""){
item[variable] = "N/A";
console.log(item);
}
}
var messageBody = item;
});
var messageBody = messageBody[0];
// Logs out the new messageBody
console.log("FIXED - ", messageBody);
// Checks for errors and delets from que after sent
saveEmail(messageBody, function(err, data) {
if (err && err.code && err.code === "ConditionalCheckFailedException") {
console.error("INFO_DYNAMODB_SAVE", messageBody + " already subscribed");
deleteMessage(message.MessageId, function(err) {
if(!err) {
console.error("INFO_SQS_MESSAGE_DELETE", "receipt handle: " + message.MessageId, "successful");
} else {
console.error("ERR_SQS_MESSAGE_DELETE", "receipt handle: " + message.MessageId, err);
}
context.done(err);
});
}
else if (err) {
console.error("ERR_DYNAMODB_SAVE", "receipt handle: " + message.MessageId, err);
context.done(err);
}
else {
console.log("INFO_DYNAMODB_SAVE", "email_saved", "receipt handle: " + message.MessageId, messageBody.Message);
deleteMessage(message.MessageId, function(err) {
if(!err) {
console.error("INFO_SQS_MESSAGE_DELETE", "receipt handle: " + message.MessageId, "successful");
} else {
console.error("ERR_SQS_MESSAGE_DELETE", "receipt handle: " + message.MessageId, err);
}
context.done(err);
});
}
});
} else {
console.log("INFO_SQS_RESULT", "0 messages received");
context.done(null);
}
}
});
});
}