Skip to content

Commit

Permalink
(auth) - Fix willAuthError causing duplicate operations (#1849)
Browse files Browse the repository at this point in the history
  • Loading branch information
Yanko Valera authored Aug 11, 2021
1 parent 3455401 commit ef96add
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 12 deletions.
5 changes: 5 additions & 0 deletions .changeset/orange-pets-wave.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@urql/exchange-auth': patch
---

Fix willAuthError causing duplicate operations
26 changes: 14 additions & 12 deletions exchanges/auth/src/authExchange.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,28 +103,26 @@ export function authExchange<T>({

const updateAuthState = (newAuthState: T | null) => {
authState = newAuthState;
pendingPromise = undefined;
authPromise = undefined;
retryQueue.forEach(retryOperation);
retryQueue.clear();
};

let pendingPromise: Promise<any> | void = Promise.resolve()
let authPromise: Promise<any> | void = Promise.resolve()
.then(() => getAuth({ authState, mutate }))
.then(updateAuthState);

const refreshAuth = (operation: Operation): Promise<any> => {
const refreshAuth = (operation: Operation): void => {
// add to retry queue to try again later
operation = addAuthAttemptToOperation(operation, true);
retryQueue.set(operation.key, operation);

// check that another operation isn't already doing refresh
if (!pendingPromise) {
pendingPromise = getAuth({ authState, mutate })
if (!authPromise) {
authPromise = getAuth({ authState, mutate })
.then(updateAuthState)
.catch(() => updateAuthState(null));
}

return pendingPromise;
};

const sharedOps$ = pipe(operations$, share);
Expand All @@ -149,14 +147,18 @@ export function authExchange<T>({
pipe(
pendingOps$,
mergeMap(operation => {
if (retryQueue.has(operation.key)) {
return empty;
}

if (
!pendingPromise &&
!authPromise &&
willAuthError &&
willAuthError({ operation, authState })
) {
pendingPromise = refreshAuth(operation);
refreshAuth(operation);
return empty;
} else if (!pendingPromise) {
} else if (!authPromise) {
return fromValue(addAuthAttemptToOperation(operation, false));
}

Expand All @@ -168,7 +170,7 @@ export function authExchange<T>({
);

return pipe(
fromPromise(pendingPromise),
fromPromise(authPromise),
map(() => addAuthAttemptToOperation(operation, false)),
takeUntil(teardown$)
);
Expand All @@ -185,7 +187,7 @@ export function authExchange<T>({
filter(({ error, operation }) => {
if (error && didAuthError && didAuthError({ error, authState })) {
if (!operation.context.authAttempt) {
pendingPromise = refreshAuth(operation);
refreshAuth(operation);
return false;
}
}
Expand Down

0 comments on commit ef96add

Please sign in to comment.