Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

preview controller memoize response #989

Merged
merged 1 commit into from
Aug 4, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 19 additions & 4 deletions assets/controllers/preview_controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ export default class extends Controller {
static targets = ['container'];
static throttles = ['show'];

/** memoization of fetched embed response */
fetchedResponse = {};

connect() {
useThrottle(this, { wait: 1000 });

Expand Down Expand Up @@ -43,6 +46,21 @@ export default class extends Controller {
await this.show(event);
}

async fetchEmbed(url) {
if (this.fetchedResponse[url]) {
return this.fetchedResponse[url];
}

let response = await fetch(router().generate('ajax_fetch_embed', { url }), { method: 'GET' });

response = await ok(response);
response = await response.json();

this.fetchedResponse[url] = response;

return response;
}

async show(event) {
event.preventDefault();

Expand All @@ -55,10 +73,7 @@ export default class extends Controller {
try {
this.loadingValue = true;

let response = await fetch(router().generate('ajax_fetch_embed', { url: event.params.url }), { method: 'GET' });

response = await ok(response);
response = await response.json();
const response = await this.fetchEmbed(event.params.url);

this.containerTarget.innerHTML = response.html;
this.containerTarget.classList.remove('hidden');
Expand Down
Loading