Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// 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
You can’t perform that action at this time.