This repository has been archived by the owner on Jan 12, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
fetch.js
207 lines (148 loc) · 3.45 KB
/
fetch.js
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
const _fetch = require('node-fetch');
const {
DateTime
} = require('luxon');
function getEnv(...names) {
const result = {};
names.forEach(name => {
const value = process.env[name];
if (!value) {
console.error(`missing ${name} environment variable`);
process.exit(1);
}
result[name] = value;
});
return result;
}
const {
DISCOURSE_USERNAME,
DISCOURSE_KEY,
DISCOURSE_BASE_URL
} = getEnv(
'DISCOURSE_USERNAME',
'DISCOURSE_KEY',
'DISCOURSE_BASE_URL'
);
function padZero(number, length) {
str = String(number);
while (str.length < length) {
str = '0' + str
}
return str;
}
function rateLimit(asyncFn, delay=300) {
return async function(...args) {
await new Promise(resolve => {
setTimeout(resolve, delay);
});
return asyncFn(...args);
};
}
const fetch = rateLimit(_fetch);
function fetchMonthlyStats(reportName, start_date, end_date) {
var params = new URLSearchParams([
[`reports[${reportName}][facets][]`, 'prev_period'],
[`reports[${reportName}][start_date]`, start_date],
[`reports[${reportName}][end_date]`, end_date],
[`reports[${reportName}][limit]`, '50'],
['api_key', DISCOURSE_KEY],
['api_username', DISCOURSE_USERNAME]
]);
const query = params.toString();
const url = `${DISCOURSE_BASE_URL}/admin/reports/bulk?${query}`;
return fetch(url, {
method: 'GET',
headers: {
accept: 'application/json'
}
})
.then(r => r.text())
.then(text => JSON.parse(text))
.then(result => {
const {
reports,
error_type
} = result;
if (error_type) {
throw new Error(`fetch error: ${error_type}`);
}
const [ report ] = reports;
return report;
});
}
async function fetchStats(name, ranges) {
let reports = [];
for (const range of ranges) {
const {
start_date,
end_date
} = range;
const report = await fetchMonthlyStats(name, start_date, end_date);
const {
data
} = report;
const [ _0, month, _1, year ] = new Date(end_date).toDateString().split(' ');
const sum = data.reduce(function(sum, entry) {
return sum + entry.y;
}, 0);
report.month = month;
report.sum = sum;
report.year = year;
reports.push(report);
}
const data = reports.map(report => {
const {
year,
month,
sum
} = report;
return {
month,
year,
sum
};
});
return {
name,
data
};
}
function toCSV(report) {
const fs = require('fs');
const {
name,
data
} = report;
const keys = Object.keys(data[0]);
const header = keys.join(',');
const entries = data.map(entry => keys.map(key => entry[key]).join(',')).join('\n');
const csv = `${header}\n${entries}`;
fs.writeFileSync(`${name}.csv`, csv, 'utf8');
console.log(`wrote ${name}.csv`);
}
function createRanges(date, look_back = 1) {
const ranges = [];
for (let i = 0; i < look_back; i++) {
var end_date = DateTime.local().minus({
month: i + 1
}).endOf('month').toISO();
var start_date = DateTime.local().minus({
month: i + 1
}).startOf('month').toISO();
ranges.push({
start_date,
end_date
});
}
return ranges;
}
const look_back = 10;
const today = new Date();
const ranges = createRanges(today, look_back);
Promise.all([
fetchStats('posts', ranges).then(toCSV),
fetchStats('signups', ranges).then(toCSV)
]).catch(err => {
console.error(err);
process.exit(1);
});