Created
September 16, 2021 22:48
-
-
Save zoernert/b8e13c05a78b9a635b38cc51af30522f to your computer and use it in GitHub Desktop.
Sendgrid CO2 Offsetting using RapidAPI service
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 sendgridAPIKey = 'YOUR_SENDGRID_API_KEY'; | |
const rapidAPIKey = 'YOUR_RAPIDAPI_KEY'; | |
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; | |
// Calculate co2 emission based on stats | |
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 | |
} | |
} | |
} | |
// Run Compensation via RapidAPI Call | |
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); | |
console.log('Your CO2 Compensation Certificate for '+totalco2+'g ',compensationCall.data.certificate); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment