Created
September 16, 2021 23:06
-
-
Save zoernert/af897a43542b4ef24bd37573234b38d7 to your computer and use it in GitHub Desktop.
Runkit implementation of Sendgrid CO2 Offset Script
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const app = async function() { | |
const sendgridAPIKey = process.env.sendgridAPIKey; | |
const rapidAPIKey = process.env.rapidAPIKey; | |
const fromDate = new Date(new Date().getTime() - (7*87600000)).toISOString().split('T')[0]; // last 7 days | |
const axios = require("axios"); | |
// Retrieve Statistics from Sendgrid | |
const sendgridStatsResponds = await axios.get("https://sendgrid.com/v3/stats?start_date="+fromDate,{ | |
headers: { | |
'content-type': 'application/json', | |
'Authorization': 'Bearer '+sendgridAPIKey | |
} | |
}); | |
const mailStats = sendgridStatsResponds.data; | |
let totalco2 = 0; | |
for(let i=0;i<mailStats.length;i++) { | |
for(let j=0;j<mailStats[i].stats.length;j++) { | |
for (const [key, value] of Object.entries(mailStats[i].stats[j].metrics)) { | |
if(key == "blocks") totalco2+=1 | |
if(key == "bounce_drops") totalco2+=2 | |
if(key == "bounces") totalco2+=2 | |
if(key == "clicks") totalco2+=2 | |
if(key == "deferred") totalco2+=2 | |
if(key == "delivered") totalco2+=20 | |
if(key == "invalid_emails") totalco2+=0 | |
if(key == "opens") totalco2+=10 | |
if(key == "processed") totalco2+=15 | |
if(key == "requests") totalco2+=0 | |
if(key == "spam_report_drops") totalco2+=1 | |
if(key == "spam_reports") totalco2+=3 | |
if(key == "unique_clicks") totalco2+=5 | |
if(key == "unique_opens") totalco2+=5 | |
if(key == "unsubscribe_drops") totalco2+=0 | |
if(key == "unsubscribes") totalco2+=2 | |
} | |
} | |
} | |
const options = { | |
method: 'GET', | |
url: 'https://co2-offset.p.rapidapi.com/rapidapi/compensate', | |
params: {gram: totalco2}, | |
headers: { | |
'x-rapidapi-host': 'co2-offset.p.rapidapi.com', | |
'x-rapidapi-key': rapidAPIKey | |
} | |
}; | |
const compensationCall = await axios.request(options); | |
return { | |
totalco2:totalco2, | |
certificate:compensationCall.data.certificate | |
}; | |
}; | |
console.log(await app()); | |
const endpoint = require("@runkit/runkit/json-endpoint/1.0.0"); | |
endpoint(exports, async function(incomingData) | |
{ | |
return await app() | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment