Add subscription link for graphql client

This commit is contained in:
Matthew Russell 2022-03-16 12:38:04 -07:00 committed by GitHub
parent c2e4f1d007
commit d9e57f6694
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 39 additions and 2 deletions

View File

@ -1,6 +1,15 @@
import { ApolloClient, from, HttpLink, InMemoryCache } from '@apollo/client';
import {
ApolloClient,
split,
from,
HttpLink,
InMemoryCache,
} from '@apollo/client';
import { GraphQLWsLink } from '@apollo/client/link/subscriptions';
import { getMainDefinition } from '@apollo/client/utilities';
import { onError } from '@apollo/client/link/error';
import { RetryLink } from '@apollo/client/link/retry';
import { createClient as createWSClient } from 'graphql-ws';
export function createClient(base?: string) {
if (!base) {
@ -40,6 +49,28 @@ export function createClient(base?: string) {
credentials: 'same-origin',
});
const wsLink = process.browser
? new GraphQLWsLink(
createWSClient({
url: urlWS.href,
})
)
: null;
const splitLink = process.browser
? split(
({ query }) => {
const definition = getMainDefinition(query);
return (
definition.kind === 'OperationDefinition' &&
definition.operation === 'subscription'
);
},
wsLink,
httpLink
)
: httpLink;
const errorLink = onError(({ graphQLErrors, networkError }) => {
console.log(graphQLErrors);
console.log(networkError);
@ -47,7 +78,7 @@ export function createClient(base?: string) {
return new ApolloClient({
connectToDevTools: process.env['NODE_ENV'] === 'development',
link: from([errorLink, retryLink, httpLink]),
link: from([errorLink, retryLink, splitLink]),
cache,
});
}

View File

@ -30,6 +30,7 @@
"core-js": "^3.6.5",
"env-cmd": "^10.1.0",
"graphql": "^15.7.2",
"graphql-ws": "^5.6.3",
"lodash.debounce": "^4.0.8",
"next": "12.0.7",
"nx": "^13.8.3",

View File

@ -11026,6 +11026,11 @@ graphql-tag@^2.10.1, graphql-tag@^2.12.3:
dependencies:
tslib "^2.1.0"
graphql-ws@^5.6.3:
version "5.6.3"
resolved "https://registry.yarnpkg.com/graphql-ws/-/graphql-ws-5.6.3.tgz#32321594a7b744755df992f24afccc84143b4b7d"
integrity sha512-ZolWOi6bzI35ovGROCZROB9nDbwZiJdIsaPdzW/jkICCGNb3qL/33IONY/yQiBa+Je2uA11HfY4Uxse4+/ePYA==
"graphql@14.0.2 - 14.2.0 || ^14.3.1 || ^15.0.0", graphql@15.8.0, graphql@^15.7.2:
version "15.8.0"
resolved "https://registry.yarnpkg.com/graphql/-/graphql-15.8.0.tgz#33410e96b012fa3bdb1091cc99a94769db212b38"