mblinks: use full query as key, code cleanup

This commit is contained in:
Laurent Monin 2015-06-10 23:52:36 +02:00
parent d9dbcf8dc8
commit 7c67333f92

View file

@ -130,42 +130,59 @@ var MBLinks = function (cachekey, expiration) {
insert_func(mblinks.createMusicBrainzLink(mb_url, _type));
});
} else {
// webservice query url
var query = mblinks.mb_server + '/ws/2/url?resource=' + encodeURIComponent(url) + '&inc=' + mb_type + '-rels';
// 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;
if (query in mblinks.ajax_requests) {
handlers = mblinks.ajax_requests[query].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',
function (data) {
if ('relations' in data) {
var expires = new Date().getTime() + (mblinks.expirationMinutes * 60 * 1000);
mblinks.cache[context.url] = {
timestamp: expires,
urls: []
};
$.each(data['relations'], function (idx, relation) {
if (_type in relation) {
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);
$.each(context.handlers, function(i, handler) {
handler(mblinks.createMusicBrainzLink(mb_url, _type))
})
mblinks.ajax_requests.push(
// key
query,
// handler
function () {
var ctx = this; // context from $.proxy()
var mbl = ctx.mblinks;
$.getJSON(ctx.query,
function (data) {
if ('relations' in data) {
mbl.cache[ctx.url] = {
timestamp: new Date().getTime() + (mbl.expirationMinutes * 60 * 1000),
urls: []
};
$.each(data['relations'], function (idx, relation) {
if (ctx._type in relation) {
var mb_url = mbl.mb_server + '/' + ctx.mb_type + '/' + relation[ctx._type]['id'];
if ($.inArray(mb_url, mbl.cache[ctx.url].urls) == -1) { // prevent dupes
mbl.cache[ctx.url].urls.push(mb_url);
$.each(ctx.handlers, function(i, handler) {
handler(mbl.createMusicBrainzLink(mb_url, ctx._type))
})
}
}
}
});
mblinks.saveCache();
});
mbl.saveCache();
}
}
});
}, {
'url': url,
'handlers': handlers,
'mb_type': mb_type
});
);
},
// context
{
'url': url, // discogs url
'handlers': handlers, // list of handlers
'mb_type': mb_type, // musicbrainz type ie. release-group
'_type': _type, // musicbrainz type '-' replaced, ie. release_group
'query': query, // json request url
'mblinks': mblinks // MBLinks object
}
);
}
};