Skip to content

Commit

Permalink
fix: added a nice error message when graphql-ws is requested but no…
Browse files Browse the repository at this point in the history
…t installed. Moved to a dynamic import instead.

Signed-off-by: blam <[email protected]>
  • Loading branch information
benjdlambert committed May 17, 2022
1 parent 7f695b1 commit 6237d92
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 1 deletion.
5 changes: 5 additions & 0 deletions .changeset/four-mangos-warn.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@graphiql/toolkit': patch
---

Move `graphql-ws` dependency to a dynamic import, and add a nice error message when it's not installed
15 changes: 15 additions & 0 deletions packages/graphiql-toolkit/src/create-fetcher/__tests__/lib.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,3 +102,18 @@ describe('getWsFetcher', () => {
expect(SubscriptionClient.mock.calls).toHaveLength(0);
});
});

describe('missing graphql-ws dependency', () => {
it('should throw a nice error', () => {
jest.resetModules();
jest.doMock('graphql-ws', () => {
throw { code: 'MODULE_NOT_FOUND' };
});

expect(() =>
createWebsocketsFetcherFromUrl('wss://example.com'),
).toThrowError(
/You need to install the `graphql-ws` package to use websockets/,
);
});
});
17 changes: 16 additions & 1 deletion packages/graphiql-toolkit/src/create-fetcher/lib.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { DocumentNode, visit, GraphQLError } from 'graphql';
import { meros } from 'meros';
import {
createClient,
Client,
ClientOptions,
ExecutionResult,
createClient as createClientType,
} from 'graphql-ws';
import {
isAsyncIterable,
Expand All @@ -19,6 +19,10 @@ import type {
CreateFetcherOptions,
} from './types';

const errorHasCode = (err: unknown): err is { code: string } => {
return typeof err === 'object' && err !== null && 'code' in err;
};

/**
* Returns true if the name matches a subscription in the AST
*
Expand Down Expand Up @@ -76,13 +80,24 @@ export const createWebsocketsFetcherFromUrl = (
) => {
let wsClient;
try {
const { createClient } = require('graphql-ws') as {
createClient: typeof createClientType;
};

// TODO: defaults?
wsClient = createClient({
url,
connectionParams,
});
return createWebsocketsFetcherFromClient(wsClient);
} catch (err) {
if (errorHasCode(err)) {
if (err.code === 'MODULE_NOT_FOUND') {
throw Error(
'You need to install the `graphql-ws` package to use websockets',
);
}
}
console.error(`Error creating websocket client for:\n${url}\n\n${err}`);
}
};
Expand Down

0 comments on commit 6237d92

Please sign in to comment.