Skip to content
Merged
Show file tree
Hide file tree
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
40 changes: 18 additions & 22 deletions app/assets/javascripts/qpixel_api.js
Original file line number Diff line number Diff line change
Expand Up @@ -110,28 +110,34 @@ window.QPixel = {

/**
* Used to prevent launching multiple requests to /users/me
* @type {Promise<Response>|null}
* @type {Promise<QPixelUser>|null}
*/
_pendingUserResponse: null,
_pendingUser: null,

/**
* @type {QPixelUser|null}
*/
_user: null,

_fetchUser () {
if (QPixel._pendingUserResponse) {
return QPixel._pendingUserResponse;
if (QPixel._pendingUser) {
return QPixel._pendingUser;
}

const myselfPromise = QPixel.fetch('/users/me', {
headers: {
'Accept': 'application/json',
'Cache-Control': 'no-cache',
}
});
const myselfPromise = QPixel
.fetch('/users/me', {
headers: {
'Accept': 'application/json',
'Cache-Control': 'no-cache',
}
})
.then((resp) => resp.json())
.catch(() => null)
.finally(() => {
QPixel._pendingUser = null;
});

QPixel._pendingUserResponse = myselfPromise;
QPixel._pendingUser = myselfPromise;

return myselfPromise;
},
Expand All @@ -141,17 +147,7 @@ window.QPixel = {
return QPixel._user;
}

try {
const resp = await QPixel._fetchUser();

if (!resp.bodyUsed) {
QPixel._user = await resp.json();
}
}
finally {
// ensures pending user is cleared regardless of network errors
QPixel._pendingUserResponse = null;
}
QPixel._user = await QPixel._fetchUser();

return QPixel._user;
},
Expand Down
4 changes: 2 additions & 2 deletions global.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -364,7 +364,7 @@ interface QPixel {

// private properties
_filters?: QPixelFilter[] | null;
_pendingUserResponse?: Promise<Response> | null;
_pendingUser?: Promise<QPixelUser> | null;
_popups?: Record<string, QPixelPopup>;
_preferences?: UserPreferences | null;
_user?: QPixelUser | null;
Expand All @@ -384,7 +384,7 @@ interface QPixel {
/**
* FIFO-style fetch wrapper for /users/me requests
*/
_fetchUser?: () => Promise<Response>;
_fetchUser?: () => Promise<QPixelUser | null>;

/**
* Get an object containing the current user's preferences. Loads, in order of precedence, from local variable,
Expand Down