Created
December 11, 2008 05:14
-
-
Save youpy/34615 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// wedata utility for Greasemonkey | |
// usage | |
/* | |
// ==UserScript== | |
// @name foo bar | |
// @namespace http://baz.com | |
// @require http://gist.github.com/raw/34615/04333b7e307eb029462680e4f4cf961f72f4324c | |
// ==/UserScript== | |
var DATABASE_URL = 'http://wedata.net/databases/XXX/items.json'; | |
var database = new Wedata.Database(DATABASE_URL); | |
database.get(function(items) { | |
items.forEach(function(item) { | |
// do something | |
}); | |
}); | |
// clear cache | |
GM_registerMenuCommand('XXX - clear cache', function() { | |
database.clearCache(); | |
}); | |
*/ | |
var Wedata = {}; | |
Wedata.Database = function(url) { | |
this.items = []; | |
this.expires = 24 * 60 * 60 * 1000; // 1 day | |
this.url = url; | |
}; | |
Wedata.Database.prototype.get = function(callback) { | |
var self = this; | |
var cacheInfo; | |
if(cacheInfo = Wedata.Cache.get(self.url)) { | |
self.items = cacheInfo; | |
callback(self.items); | |
} else { | |
GM_xmlhttpRequest({ | |
method : "GET", | |
url : self.url, | |
onload : function(res) { | |
self.items = eval('(' + res.responseText + ')'); | |
callback(self.items); | |
Wedata.Cache.set(self.url, self.items, self.expires); | |
} | |
}); | |
} | |
}; | |
Wedata.Database.prototype.clearCache = function() { | |
Wedata.Cache.set(this.url, null, 0); | |
} | |
Wedata.Cache = {}; | |
Wedata.Cache.set = function(key, value, expire) { | |
var expire = new Date().getTime() + expire; | |
GM_setValue(key, uneval({ value: value, expire: expire })); | |
}; | |
Wedata.Cache.get = function(key) { | |
var cached = eval(GM_getValue(key)); | |
if(!cached) { | |
return; | |
} | |
if(cached.expire > new Date().getTime()) { | |
return cached.value; | |
} | |
return; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment