Skip to content

Instantly share code, notes, and snippets.

@dambrogia
Created June 18, 2021 18:19
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dambrogia/11e8462e1d2f0e2de1c94949e1fc00ac to your computer and use it in GitHub Desktop.
Save dambrogia/11e8462e1d2f0e2de1c94949e1fc00ac to your computer and use it in GitHub Desktop.
const fs = require('fs');
const readline = require('readline');
const fetch = require('node-fetch'); // npm i node-fetch
const getApiKey = () => '<update this>';
const getBatchSize = () => 25;
/**
* Make a search request to sendgrid to get the ids of the contacts for the
* provided emails.
* @param {String[]} emails
* @return {String[]}
*/
async function getEmailIds (emails) {
var query = emails.map(email => `email LIKE '${email}'`).join(' OR ');
var args = {
method: 'POST',
body: JSON.stringify({ query: query }),
headers: {
'Content-type': 'application/json',
'Authorization': `Bearer ${getApiKey()}`
}
};
const response = await fetch('https://api.sendgrid.com/v3/marketing/contacts/search', args);
if (response.status == 200) {
var data = await response.json();
return data.result.map(contact => contact.id);
}
return [];
};
/**
* Make a request to sendgrid to delete the contacts by their IDs.
* @param {String[]} ids
* @return {String}
*/
async function deleteIds(ids) {
var args = {
method: 'DELETE',
headers: { 'Authorization': `Bearer ${getApiKey()}` }
};
var url = new URL('https://api.sendgrid.com/v3/marketing/contacts');
url.searchParams.append('ids', ids.join(','));
var urlString = url.toString();
const response = await fetch(urlString, args);
const data = await response.json();
return data;
}
/**
* This reads from a file named contacts.txt which is one email per line.
* It will batch the emails into 25 (based on the batch size declared) and
* search for them in sendgdrid. It takes the emails it finds and uses their
* contact ID to run a DELETE request on the entity in sendgrid.
*/
(async function () {
const fileStream = fs.createReadStream('contacts.txt');
var i = 0;
var emails = [];
const rl = readline.createInterface({
input: fileStream,
crlfDelay: Infinity
});
for await (const line of rl) {
emails.push(line.toLowerCase());
if (++i % getBatchSize() === 0) {
var ids = await getEmailIds(emails);
if (ids.length) {
var jsonResponse = await deleteIds(ids);
console.log(`requested to delete ${ids.length} contacts`);
if (ids.length < emails.length) {
console.log(`${emails.length - ids.length} id(s) not found in set of ${emails.length} emails`);
}
console.log(jsonResponse);
} else {
console.log(`no matches for next ${emails.length} emails`);
}
// Reset emails collection.
emails = [];
}
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment