Graphql-ws with apollo client v2 #269
-
Hello, My setup consists of a backend based on apollo server, a frontend app based on Nuxt JS - which has only compatibility with Apollo client V2, and a new Frontend App with Vue3 with Apollo Client V3. On the new app everything related to Graphql-ws works as expected, but is there a way I can make Graphql-ws work with Apollo Client v2? The recipe for apollo client from what I can see is based on apollo client v3. Any recommendations for how I could approach the problem would be very appreciated, as I've transitioned the backend and the new front end app to graphql-ws but I also need to be able to use it in the NuxtJS app with Apollo v2. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 10 replies
-
v3 is not much different from v2. Here's a quick and untested integration of import { print } from 'graphql';
import { createClient, ClientOptions, Client } from 'graphql-ws';
import { ApolloLink, Operation, FetchResult, Observable } from 'apollo-link'; // yarn add apollo-link
// **literally** copied over from the "Client usage with Apollo" recipe
class WebSocketLink extends ApolloLink {
private client: Client;
constructor(options: ClientOptions) {
super();
this.client = createClient(options);
}
public request(operation: Operation): Observable<FetchResult> {
return new Observable((sink) => {
return this.client.subscribe<FetchResult>(
{ ...operation, query: print(operation.query) },
{
next: sink.next.bind(sink),
complete: sink.complete.bind(sink),
error: (err) => {
if (Array.isArray(err))
// GraphQLError[]
return sink.error(
new Error(err.map(({ message }) => message).join(', ')),
);
if (err instanceof CloseEvent)
return sink.error(
new Error(
`Socket closed with event ${err.code} ${err.reason || ''}`, // reason will be available on clean closes only
),
);
return sink.error(err);
},
},
);
});
}
} You can then use the P.S. Updated the recipe to reflect the subtle differences too: d980213. |
Beta Was this translation helpful? Give feedback.
v3 is not much different from v2. Here's a quick and untested integration of
graphql-ws
with Apollo Client v2: