discourse/app/assets/javascripts/pretty-text/addon/inline-oneboxer.js
Bianca Nenciu ecc3c404a0
FIX: Cache missing inline oneboxes (#12953)
* FIX: Cache missing inline oneboxes

Some inline oneboxes were not cached when the server did not return an
answer for an URL and the queried URL and the absolute URL were
different.

For example, if user typed www.example.com, the client asked the server
for http://www.example.com and if the server returned an empty response,
then the client would keep requesting an inline onebox everytime the
composer changed.

In other words, the key used for reading (the absolute URL) and the one
used for writing (the URL as typed by the user) were not the same when
the server returned an empty response.

* DEV: Check cache before making request

There is another cache check in PrettyText, but that is not enough if
multiple requests are pending. This problem was made obvious in tests,
but can happen for users with slow connections.
2021-05-06 19:08:04 +03:00

50 lines
1.1 KiB
JavaScript

const _cache = {};
export function applyInlineOneboxes(inline, ajax, opts) {
opts = opts || {};
const urls = Object.keys(inline).filter((url) => !_cache[url]);
urls.forEach((url) => {
// cache a blank locally, so we never trigger a lookup
_cache[url] = {};
});
if (urls.length === 0) {
return;
}
ajax("/inline-onebox", {
data: {
urls,
category_id: opts.categoryId,
topic_id: opts.topicId,
},
}).then((result) => {
result["inline-oneboxes"].forEach((onebox) => {
if (onebox.title) {
_cache[onebox.url] = onebox;
let links = inline[onebox.url] || [];
links.forEach((link) => {
$(link)
.text(onebox.title)
.addClass("inline-onebox")
.removeClass("inline-onebox-loading");
});
}
});
});
}
export function cachedInlineOnebox(url) {
return _cache[url];
}
export function applyCachedInlineOnebox(url, onebox) {
return (_cache[url] = onebox);
}
export function deleteCachedInlineOnebox(url) {
return delete _cache[url];
}