Last active
March 25, 2021 02:34
-
-
Save shaykav/7a775550dd7613ea6623fb11fcd37fef to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { ApolloLink, Operation, FetchResult, Observable } from 'apollo-boost'; | |
import { print, GraphQLError } from 'graphql'; | |
import { createClient, ClientOptions, Client } from 'graphql-ws'; | |
// See example taken from https://github.com/enisdenjo/graphql-ws#apollo-client | |
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 (err instanceof Error) { | |
return sink.error(err); | |
} | |
if (err instanceof CloseEvent) { | |
return sink.error( | |
// reason will be available on clean closes | |
new Error( | |
`Socket closed with event ${err.code} ${err.reason || ''}`, | |
), | |
); | |
} | |
return sink.error( | |
new Error( | |
(err as GraphQLError[]) | |
.map(({ message }) => message) | |
.join(', '), | |
), | |
); | |
}, | |
}, | |
); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment