-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathyqlcache.js
72 lines (51 loc) · 1.79 KB
/
yqlcache.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
function YQLCACHE() {
/* based on https://github.com/codepo8/yql-localcache */
var cacheid,cb;
var current,data;
this.get=function(transaction) {
cb = transaction.callback;
cacheid = transaction.id;
current = JSON.parse(localStorage.getItem(cacheid));
if(current !== null){
/* if the cache time is less than the cacheage return it*/
if((new Date().getTime() - current.time) < transaction.cacheage){
cb({type:"cached",data:current.data});
/* if the cache is older than the max age, prime the cache */
} else {
this.loadYQL(transaction.yql);
}
/* if the cache has no data, load from YQL again */
} else {
this.loadYQL(transaction.yql);
}
}
this.loadYQL=function(yql){
var url = "http://query.yahooapis.com/v1/public/yql?q="+encodeURIComponent(yql)+"&format=json";
Mojo.Log.info(url);
var request = new Ajax.Request(url, {
method: 'get',
asynchronous: true,
evalJSON: true,
onSuccess: this.cache,
on0: function (ajaxResponse) {
// connection failed, typically because the server is overloaded or has gone down since the page loaded
Mojo.Log.error("Connection failed");
},
onFailure: function(response) {
// Request failed (404, that sort of thing)
Mojo.Log.error("Request failed");
},
onException: function(request, ex) {
// An exception was thrown
Mojo.Log.error("Exception");
}
});
}
this.cache=function(transport) {
var data = transport.responseJSON;
var timestamp = new Date().getTime();
localStorage.setItem(cacheid,JSON.stringify({time:timestamp,data:data}));
cb({type:"freshcache",data:data});
}
}
var yqlcache = new YQLCACHE();