Skip to content

Commit

Permalink
fix(client): cant read the CloseEvent.reason after bundling so just…
Browse files Browse the repository at this point in the history
… pass the whole event to the sink error and let the user handle it
  • Loading branch information
enisdenjo committed Aug 26, 2020
1 parent 49b75ce commit 9ccb46b
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 9 deletions.
15 changes: 7 additions & 8 deletions src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ export function createClient(options: ClientOptions): Client {
// to dispatch messages to the correct destination
const subscribedSinks: Record<UUID, Sink> = {};

function errorAllSinks(err: Error) {
function errorAllSinks(err: Error | CloseEvent) {
Object.entries(subscribedSinks).forEach(([, sink]) => sink.error(err));
}
function completeAllSinks() {
Expand Down Expand Up @@ -87,25 +87,24 @@ export function createClient(options: ClientOptions): Client {
* > object (thereby invoking its onclose handler) to indicate the reason for the connection's closing.
*/

socket.onclose = ({ code, reason }) => {
const err = new Error(
`Socket closed with event ${code}` + !reason ? '' : `: ${reason}`,
);
socket.onclose = (closeEvent) => {
// NOTE: reading the `CloseEvent.reason` either trows or empties the whole error message
// (if trying to pass the reason in the `Error` message). let the user handle the close event

if (code === 1000 || code === 1001) {
if (closeEvent.code === 1000 || closeEvent.code === 1001) {
// close event `1000: Normal Closure` is ok and so is `1001: Going Away` (maybe the server is restarting)
completeAllSinks();
} else {
// all other close events are considered erroneous
errorAllSinks(err);
errorAllSinks(closeEvent);
}

if (!done) {
done = true;
connecting = false;
connected = false; // the connection is lost
socket = null;
reject(err); // we reject here bacause the close is not supposed to be called during the connect phase
reject(closeEvent); // we reject here bacause the close is not supposed to be called during the connect phase
}
};
socket.onopen = () => {
Expand Down
2 changes: 1 addition & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export interface Sink<T = unknown> {
/** Next value arriving. */
next(value: T): void;
/** An error that has occured. Calling this function "closes" the sink. */
error(error: Error | readonly GraphQLError[]): void;
error(error: Error | CloseEvent | readonly GraphQLError[]): void;
/** The sink has completed. This function "closes" the sink. */
complete(): void;
}

0 comments on commit 9ccb46b

Please sign in to comment.