Skip to content

Commit 44f1d22

Browse files
authored
Merge pull request #1923 from codidact/0valt/user-fetch
Fix for QPixel#user race conditions
2 parents fc35aa9 + 8535dff commit 44f1d22

2 files changed

Lines changed: 20 additions & 24 deletions

File tree

app/assets/javascripts/qpixel_api.js

Lines changed: 18 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -110,28 +110,34 @@ window.QPixel = {
110110

111111
/**
112112
* Used to prevent launching multiple requests to /users/me
113-
* @type {Promise<Response>|null}
113+
* @type {Promise<QPixelUser>|null}
114114
*/
115-
_pendingUserResponse: null,
115+
_pendingUser: null,
116116

117117
/**
118118
* @type {QPixelUser|null}
119119
*/
120120
_user: null,
121121

122122
_fetchUser () {
123-
if (QPixel._pendingUserResponse) {
124-
return QPixel._pendingUserResponse;
123+
if (QPixel._pendingUser) {
124+
return QPixel._pendingUser;
125125
}
126126

127-
const myselfPromise = QPixel.fetch('/users/me', {
128-
headers: {
129-
'Accept': 'application/json',
130-
'Cache-Control': 'no-cache',
131-
}
132-
});
127+
const myselfPromise = QPixel
128+
.fetch('/users/me', {
129+
headers: {
130+
'Accept': 'application/json',
131+
'Cache-Control': 'no-cache',
132+
}
133+
})
134+
.then((resp) => resp.json())
135+
.catch(() => null)
136+
.finally(() => {
137+
QPixel._pendingUser = null;
138+
});
133139

134-
QPixel._pendingUserResponse = myselfPromise;
140+
QPixel._pendingUser = myselfPromise;
135141

136142
return myselfPromise;
137143
},
@@ -141,17 +147,7 @@ window.QPixel = {
141147
return QPixel._user;
142148
}
143149

144-
try {
145-
const resp = await QPixel._fetchUser();
146-
147-
if (!resp.bodyUsed) {
148-
QPixel._user = await resp.json();
149-
}
150-
}
151-
finally {
152-
// ensures pending user is cleared regardless of network errors
153-
QPixel._pendingUserResponse = null;
154-
}
150+
QPixel._user = await QPixel._fetchUser();
155151

156152
return QPixel._user;
157153
},

global.d.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -364,7 +364,7 @@ interface QPixel {
364364

365365
// private properties
366366
_filters?: QPixelFilter[] | null;
367-
_pendingUserResponse?: Promise<Response> | null;
367+
_pendingUser?: Promise<QPixelUser> | null;
368368
_popups?: Record<string, QPixelPopup>;
369369
_preferences?: UserPreferences | null;
370370
_user?: QPixelUser | null;
@@ -384,7 +384,7 @@ interface QPixel {
384384
/**
385385
* FIFO-style fetch wrapper for /users/me requests
386386
*/
387-
_fetchUser?: () => Promise<Response>;
387+
_fetchUser?: () => Promise<QPixelUser | null>;
388388

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

0 commit comments

Comments
 (0)