I am currently trying to upload a Node.js file (titled 'index.js') to AWS Lambda that I want to automatically execute every day at midnight. I understand how to upload the file and everything of that nature, but for some reason, I cannot get the code to run multiple sequential functions.
Keep in mind that this function WORKS when I manually run it from my own command line (node index.js). However, when tested on Lambda, the only function that fires is the first one, getToken. I want this code to be able to first get the API access token, then update my DynamoDB table with the fetched information. Can anyone possibly help me reconfigure this function so that it works on Lambda?
var AWS = require('aws-sdk');
AWS.config.update({region: 'us-west-2'});
async function getToken (event, context) {
artistRank = 0;
console.log("GETTING TOKEN...")
getToken = await fetch("https://api.chartmetric.com/api/token", {
body: '{"refreshtoken":"*************************************"}',
headers: {
"Content-Type": "application/json"
},
method: "POST"
})
.then( res => res.json() )
.then( data => {
token = data.token;
console.log(token)
readTable(token);
})};
async function readTable (token) {
// Create the DynamoDB service object
var ddb = new AWS.DynamoDB({apiVersion: '2012-08-10'});
for (let i = 0; i < 50; i++) {
setTimeout(() => {
var params = {
TableName: 'popularCharts',
Key: {
'rank': {N: String(i)}
},
ProjectionExpression: 'currentRank, id'
};
ddb.getItem(params, function (err, data) {
if (err) {
console.log("Error", err);
} else {
artistId = data['Item'].id
idString = JSON.stringify(artistId);
idLength = idString.length;
idFinal = idString.slice(6, idLength - 2);
pointsScored(token, idFinal, i)
}
});
}, i*2000);
}
}
async function pointsScored (accessKey, id, rank) {
fetch("https://api.chartmetric.com/api/artist/" + id + "/cpp?stat=score", {
headers: {
Authorization: "Bearer " + String(accessKey)
}
})
.then( res => res.json() )
.then( data => {
length = data['obj'].length;
change = (data['obj'][length-1].score - data['obj'][length-4].score)*1000000;
console.log(change)
var ddb2 = new AWS.DynamoDB({apiVersion: '2012-08-10'});
var params2 = {
TableName: 'pointsScored',
Item: {
'rank' : {N: String(rank)},
'id' : {N: String(id)},
'playlistPoints' : {S: String(change)},
'currentRank' : {N: String(rank)}
}
}
ddb2.putItem(params2, function(err, data) {
if (err) {
console.log("Error", err);}
});
})
}
exports.handler = getToken();
Any help is much appreciated. Thank you!