Skip to content

Commit

Permalink
fix(client): Retry network errors even if they occur during event emi…
Browse files Browse the repository at this point in the history
…ssion

Closes #27
  • Loading branch information
enisdenjo committed Jun 9, 2022
1 parent 16f6a6c commit 489b1b0
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
5 changes: 5 additions & 0 deletions src/__tests__/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -549,4 +549,9 @@ describe('retries', () => {
);
});
});

// TODO: how to simulate network errors during emission? calling socket.destroy does nothing (see: https://github.com/enisdenjo/graphql-sse/issues/22)
it.todo(
'should retry network errors even if they occur during event emission',
);
});
14 changes: 12 additions & 2 deletions src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -368,6 +368,9 @@ export function createClient<SingleConnection extends boolean = false>(
// all non-network errors are worth reporting immediately
if (!(err instanceof NetworkError)) return onNonLazyError?.(err);

// was a network error, get rid of the current connection to ensure retries
conn = undefined;

// retries are not allowed or we tried to many times, report error
if (!retryAttempts || retries >= retryAttempts)
return onNonLazyError?.(err);
Expand Down Expand Up @@ -533,6 +536,12 @@ export function createClient<SingleConnection extends boolean = false>(
// all non-network errors are worth reporting immediately
if (!(err instanceof NetworkError)) throw err;

// was a network error, get rid of the current connection to ensure retries
// but only if the client is running in lazy mode (otherwise the non-lazy lock will get rid of the connection)
if (lazy) {
conn = undefined;
}

// retries are not allowed or we tried to many times, report error
if (!retryAttempts || retries >= retryAttempts) throw err;

Expand Down Expand Up @@ -724,8 +733,9 @@ async function connect<SingleConnection extends boolean>(
}
}
} catch (err) {
error = err;
if (waitingForThrow) waitingForThrow(err);
// non-network errors shouldn't ever have "network" in the message, right?
error = /network/i.test(err) ? new NetworkError(err) : err;
if (waitingForThrow) waitingForThrow(error);
} finally {
Object.values(waiting).forEach(({ proceed }) => proceed());
}
Expand Down

0 comments on commit 489b1b0

Please sign in to comment.