Skip to content

Instantly share code, notes, and snippets.

@koyachi
Forked from youpy/gist:34615
Created December 11, 2008 05:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save koyachi/34618 to your computer and use it in GitHub Desktop.
Save koyachi/34618 to your computer and use it in GitHub Desktop.
// wedata utility for Greasemonkey
// usage
/*
// ==UserScript==
// @name foo bar
// @namespace http://baz.com
// @require http://gist.github.com/raw/34615/ba15cad2dd736f32a6d7868ce6595ac1bd01c0a3
// ==/UserScript==
var DATABASE_URL = 'http://wedata.net/databases/XXX/items.json';
var database = new Wedata.Database();
database.get(DATABASE_URL, function(items) {
items.forEach(function(item) {
// do something
});
});
// clear cache
GM_registerMenuCommand('XXX - clear cache', function() {
Wedata.Cache.set(DATABASE_URL, null, 0);
});
*/
var Wedata = {};
Wedata.Database = function() {
this.items = [];
this.expires = 24 * 60 * 60 * 1000; // 1 day
};
Wedata.Database.prototype.get = function(url, callback) {
var self = this;
var cacheInfo;
if(cacheInfo = Wedata.Cache.get(url)) {
self.items = cacheInfo;
callback(self.items);
} else {
GM_xmlhttpRequest({
method : "GET",
url : url,
onload : function(res) {
self.items = eval('(' + res.responseText + ')');
callback(self.items);
Wedata.Cache.set(url, self.items, self.expires);
}
});
}
};
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