-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdata-store.js
40 lines (36 loc) · 1.24 KB
/
data-store.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
const ipDataUrl = new URL('https://ip-ranges.amazonaws.com/ip-ranges.json');
async function retrieveFromAws() {
const ipDataResponse = await fetch(ipDataUrl);
const ipData = await ipDataResponse.json();
const timestamp = Date.parse(ipDataResponse.headers.get('Last-Modified'));
return {
data: ipData,
timestamp,
}
}
async function checkLastestAws() {
try {
const response = await fetch(ipDataUrl, { method: 'HEAD' });
const timestamp = Date.parse(response.headers.get('Last-Modified'));
return timestamp;
} catch (e) {
// Fallback to returning a date hopefully very far in the future
return Date.UTC(9999, 11, 31);
}
}
async function populateCache() {
const data = await retrieveFromAws();
localStorage.setItem('aws-ip-data', JSON.stringify(data.data));
localStorage.setItem('aws-ip-timestamp', data.timestamp.toString());
return data.data;
}
export async function getIpData() {
const timestamp = Number.parseInt(localStorage.getItem('aws-ip-timestamp') ?? 0);
const preData = localStorage.getItem('aws-ip-data');
const latest = await checkLastestAws();
if (!preData || timestamp < latest) {
await populateCache();
}
const data = JSON.parse(localStorage.getItem('aws-ip-data'));
return data;
}