-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
Copy pathfetchIssueCount.js
246 lines (211 loc) · 6.31 KB
/
fetchIssueCount.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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
/* eslint global-require: "off" */
/* eslint block-scoped-var: "off" */
/* eslint function-paren-newline: [ "off" ] */
/* eslint implicit-arrow-linebreak: [ "off" ] */
// @ts-nocheck
// required for loading into a NodeJS context
if (typeof define !== 'function') {
var define = require('amdefine')(module);
}
define(['whatwg-fetch', 'promise-polyfill'], () => {
const { localStorage, fetch } = window;
const RateLimitResetAtKey = 'Rate-Limit-Reset-At';
/**
* Read and deserialize a value from local storage.
*
* @param {string} key
*
* @returns {any | undefined}
*/
function getValue(key) {
if (typeof localStorage !== 'undefined') {
const result = localStorage.getItem(key);
if (result !== null) {
return JSON.parse(result);
}
}
return undefined;
}
/**
* Clear a value from local storage.
*
* @param {string} key
*/
function clearValue(key) {
if (typeof localStorage !== 'undefined') {
localStorage.removeItem(key);
}
}
/**
* Update a key in local storage to a new value.
*
* @param {string} key
* @param {any} value
*/
function setValue(key, value) {
try {
if (typeof localStorage !== 'undefined') {
localStorage.setItem(key, JSON.stringify(value));
}
} catch (exception) {
if (
exception != QUOTA_EXCEEDED_ERR &&
exception != NS_ERROR_DOM_QUOTA_REACHED
) {
throw exception;
}
}
}
/**
* Inspect the response from the GitHub API to see if was related to being
* rate-limited by the server.
*
* @param {Response} response
*
* @returns {Error | undefined}
*/
function inspectRateLimitError(response) {
const rateLimited = response.headers.get('X-RateLimit-Remaining') === '0';
const rateLimitReset = response.headers.get('X-RateLimit-Reset');
if (rateLimited && rateLimitReset) {
const rateLimitResetAt = new Date(1000 * rateLimitReset);
setValue(RateLimitResetAtKey, rateLimitResetAt);
return new Error(
`GitHub rate limit met. Reset at ${rateLimitResetAt.toLocaleTimeString()}`
);
}
return undefined;
}
/**
* Inspect the response from the GitHub API to return a helpful error message.
*
* @param {any} json
* @param {Response} response
*
* @returns {Error}
*/
function inspectGenericError(json, response) {
const { message } = json;
const errorMessage = message || response.statusText;
return new Error(`Could not get issue count from GitHub: ${errorMessage}`);
}
/**
* Fetch and cache the issue count for the requested repository using the
* GitHub API.
*
* This covers a whole bunch of scenarios:
*
* - cached values are used if re-requested within the next 24 hours
* - ETags are included on the request, if found in the cache
* - Rate-limiting will report an error, and no further requests will be
* made until that has period has elapsed.
*
* @param {string} ownerAndName
* @param {string} label
*
* @returns {number|string|null}
*/
function fetchIssueCount(ownerAndName, label) {
const cached = getValue(ownerAndName);
const now = new Date();
const yesterday = now - 1000 * 60 * 60 * 24;
if (cached && cached.date && new Date(cached.date) >= yesterday) {
return Promise.resolve(cached.count);
}
const rateLimitResetAt = getValue(RateLimitResetAtKey);
if (rateLimitResetAt) {
const d = new Date(rateLimitResetAt);
if (d > now) {
return Promise.reject(
new Error(`GitHub rate limit met. Reset at ${d.toLocaleTimeString()}`)
);
}
clearValue(RateLimitResetAtKey);
}
const perPage = 30;
// TODO: we're not extracting the leading or trailing slash in
// `ownerAndName` when the previous regex is passed in here. This
// would be great to cleanup at some stage
const apiURL = `https://api.github.com/repos${ownerAndName}issues?labels=${label}&per_page=${perPage}`;
const settings = {
method: 'GET',
headers: {
Accept: 'application/json',
},
};
if (cached && cached.etag) {
settings.headers = {
...settings,
'If-None-Match': cached.etag,
};
}
return new Promise((resolve, reject) => {
fetch(apiURL, settings).then(
(response) => {
if (!response.ok) {
if (response.status === 304) {
// no content is returned in the 304 Not Modified response body
const count = cached ? cached.count : 0;
resolve(count);
return;
}
clearValue(ownerAndName);
const rateLimitError = inspectRateLimitError(response);
if (rateLimitError) {
reject(rateLimitError);
return;
}
response.json().then(
(json) => {
reject(inspectGenericError(json, response));
},
(error) => {
reject(error);
}
);
return;
}
const etag = response.headers.get('ETag');
const linkHeader = response.headers.get('Link');
if (linkHeader) {
const lastPageMatch = /<([^<>]*?page=(\d*))>; rel="last"/g.exec(
linkHeader
);
if (lastPageMatch && lastPageMatch.length === 3) {
const lastPageCount = Number(lastPageMatch[2]);
const baseCount = perPage * (lastPageCount - 1);
const count = `${baseCount}+`;
setValue(ownerAndName, {
count,
etag,
date: new Date(),
});
resolve(count);
return;
}
}
response.json().then(
(json) => {
if (json && typeof json.length === 'number') {
const count = json.length;
setValue(ownerAndName, {
count,
etag,
date: new Date(),
});
resolve(count);
}
},
(error) => {
reject(error);
}
);
},
(error) => {
reject(error);
}
);
});
}
return fetchIssueCount;
});