Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Moving graphql-ws to a dynamic import and display a nice message when not found #2407

Merged
merged 1 commit into from
May 17, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 when passing a 'subscriptionUrl'/,
);
});
});
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 when passing a 'subscriptionUrl'",
);
}
}
console.error(`Error creating websocket client for:\n${url}\n\n${err}`);
}
};
Expand Down