forked from ev3dev/ev3dev.github.io
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi-cache.js
More file actions
50 lines (43 loc) · 1.7 KB
/
api-cache.js
File metadata and controls
50 lines (43 loc) · 1.7 KB
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
var cacheKey = "api-cache";
function supportsHtml5Storage() {
try {
return 'localStorage' in window && window['localStorage'] !== null;
} catch (e) {
return false;
}
}
function getApiValue(endpointUrl, cacheTime, callback) {
try {
var cacheData = supportsHtml5Storage() ? JSON.parse(localStorage[cacheKey]) : null;
// This does an exact match for the URL given. Different spacing, duplicate slashes,
// alternate caps, etc. will result in the cache being bypassed.
if (cacheData && cacheData[endpointUrl] && Date.now() - cacheData[endpointUrl].dateRetrieved < cacheTime) {
callback(cacheData[endpointUrl].requestResult);
return;
}
}
catch (e) {
// Ignore the error; if the saved JSON is invalid, we'll just request it from the server.
}
console.log('No cached copy of API data for endpoint "' + endpointUrl + '" found. Downloading from remote server.');
$.ajax(endpointUrl).done(function (apiData) {
if (supportsHtml5Storage()) {
var cacheData = {};
try {
cacheData = JSON.parse(localStorage[cacheKey]);
}
catch(e) {
// Ignore error; either the cache doesn't exist or it is invalid
}
cacheData[endpointUrl] = {
dateRetrieved: Date.now(),
requestResult: apiData
};
localStorage.setItem(cacheKey, JSON.stringify(cacheData));
}
callback(apiData);
}).fail(function (xhr, error) {
console.error("Error getting API data: " + error);
callback(null, error);
});
}