-
Notifications
You must be signed in to change notification settings - Fork 0
/
getCampaigns
63 lines (54 loc) · 2.1 KB
/
getCampaigns
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// Retrieve from Klaviyo a list of all campaigns (name, date_sent and ID). Let the user configure the API_KEY:
function getCampaigns(API_KEY) {
var headers = {'Authorization': 'Klaviyo-API-Key ' + API_KEY,
'Content-Type': 'application/json',
'Revision': '2023-02-22'};
var options = {
'method' : 'get',
'headers': headers,
'muteHttpExceptions': true
};
var url = "https://a.klaviyo.com/api/campaigns";
var campaigns = [];
var retries = 0;
var delay = 1000; // initial delay of 1 second
//Fetching the data page by page until there are no more pages and builiding up "campaigns" array.
while (url) {
var response = UrlFetchApp.fetch(url, options);
if (response.getResponseCode() === 429 || response.getResponseCode() === 503) {
// Rate limit reached or Server busy
var retryAfter = response.getHeaders()["Retry-After"];
if (retryAfter) {
Utilities.sleep(retryAfter * 1000);
} else {
// Retry after a delay using exponential backoff
Utilities.sleep(delay);
delay *= 2; // double the delay for the next retry
}
retries++;
if (retries > 5) {
// Max retries reached, log an error and exit
console.log("Error fetching the data: " + response.getResponseCode());
return;
}
continue;
}
if (response.getResponseCode() === 200) {
var data = JSON.parse(response.getContentText());
campaigns = campaigns.concat(data.data); //building up campaigns array
//console.log(typeof campaigns + ' at ' + url); //dev
if (data.links && data.links.next) {
url = data.links.next;
} else {
url = null;
}
} else {
console.error(`Error: ${response.getResponseCode()} - ${response.getContentText()}`);
return null;
}
}
// Now we have an array `campaigns` that contains all the campaigns
// We loop through this array to extract the data on each campaign
var campaignData = campaigns.map(campaign => [campaign.attributes.name, campaign.id, campaign.attributes.send_time]);
return campaignData;
}