-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjson-fetcher.js
executable file
·70 lines (62 loc) · 1.72 KB
/
json-fetcher.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
ns.jsonFetcher = (function($, window, document) {
var fetchers = {};
function execute(fetcher) {
var i = fetcher.callbacks.length;
while (i--) {
if (fetcher.response && fetcher.ttl && fetcher.ttl > 0) {
ns.storage.set(fetcher.name, fetcher.response, fetcher.ttl);
}
if (typeof fetcher.callbacks[i] === 'function') {
var callback = fetcher.callbacks[i];
callback(fetcher.response);
fetcher.callbacks.splice(i, 1);
}
}
return;
};
function register(url, callback) {
if (fetchers[url]) {
fetchers[url].callbacks.push(callback);
return true;
} else {
fetchers[url] = {
callbacks: []
};
fetchers[url].callbacks.push(callback);
return false;
}
};
function get(url, ttl, callback) {
var fetcher = fetchers[url],
storage = ns.storage.get(url);
// VERIFY EXISTS IN STORAGE AND EXECUTE CALLBACK!
if (storage) {
if (typeof callback === 'function') {
return callback(storage);
}
};
// OH! NOT SEARCHED IN STORAGE, LETS TRY FETCHING IN SERVER!
if (!register(url, callback)) {
ns.http.request({
url: url,
type: 'json',
method: 'get',
error: function (error) {
console.log('[ERROR]: ', error);
return;
},
success: function (response) {
fetchers[url].response = response;
fetchers[url].ttl = ttl;
fetchers[url].name = url;
return execute(fetchers[url]);
}
});
} else if (fetcher && fetcher.response) { // OR EXECUTE ON FETCHERS!
return execute(fetchers[url]);
}
};
return {
get: get
};
})(undefined, window, window.document);