Skip to content

Instantly share code, notes, and snippets.

@youpy
Created December 11, 2008 05:14
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save youpy/34615 to your computer and use it in GitHub Desktop.
Save youpy/34615 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/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