Merge pull request #49 from murdos/mblinks_optim

Mblinks optimization
This commit is contained in:
Laurent Monin 2015-06-10 18:21:12 +02:00
commit 1172d4ef54

View file

@ -24,7 +24,37 @@ var MBLinks = function (cachekey, expiration) {
}
}();
this.ajax_requests = [];
this.ajax_requests = {
// properties: "key": {handler: function, next: property, context: {}}
first: "",
last: "",
empty: function() {return this.first == "";},
push: function(key, handler, context) {
if (key in this) {
this[key].handler = handler;
this[key].context = context;
}
else {
this[key] = {handler: handler, next: "", context: context};
if (this.first == "") {
this.first = this.last = key;
}
else {
this[this.last].next = key;
this.last = key;
}
}
},
shift: function() {
if (this.empty()) { return; }
var key = this.first;
var handler = this[key].handler;
var context = this[key].context;
this.first = this[key].next;
delete this[key]; // delete this property
return $.proxy(handler, context);
}
};
this.cache = {};
this.expirationMinutes = parseInt(expiration);
this.cache_key = cachekey;
@ -39,7 +69,7 @@ var MBLinks = function (cachekey, expiration) {
this.initAjaxEngine = function () {
var ajax_requests = this.ajax_requests;
setInterval(function () {
if (ajax_requests.length > 0) {
if (!ajax_requests.empty()) {
var request = ajax_requests.shift();
if (typeof request === "function") {
request();
@ -100,7 +130,13 @@ var MBLinks = function (cachekey, expiration) {
insert_func(mblinks.createMusicBrainzLink(mb_url, _type));
});
} else {
mblinks.ajax_requests.push($.proxy(function () {
// Merge with previous context if there's already a pending ajax request
var handlers = [];
if (url in mblinks.ajax_requests) {
handlers = mblinks.ajax_requests[url].context.handlers;
}
handlers.push(insert_func);
mblinks.ajax_requests.push(url, function () {
var context = this;
$.getJSON(mblinks.mb_server + '/ws/2/url?resource=' + encodeURIComponent(context.url)
+ '&inc=' + context.mb_type + '-rels',
@ -116,7 +152,9 @@ var MBLinks = function (cachekey, expiration) {
var mb_url = mblinks.mb_server + '/' + context.mb_type + '/' + relation[_type]['id'];
if ($.inArray(mb_url, mblinks.cache[context.url].urls) == -1) { // prevent dupes
mblinks.cache[context.url].urls.push(mb_url);
context.insert_func(mblinks.createMusicBrainzLink(mb_url, _type));
$.each(context.handlers, function(i, handler) {
handler(mblinks.createMusicBrainzLink(mb_url, _type))
})
}
}
});
@ -125,9 +163,9 @@ var MBLinks = function (cachekey, expiration) {
});
}, {
'url': url,
'insert_func': insert_func,
'handlers': handlers,
'mb_type': mb_type
}));
});
}
};