/
graphql-sse.ts
52 lines (46 loc) · 1.24 KB
/
graphql-sse.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import {
SubscriptionProvider,
SubscriptionProviderExecuteOptions,
} from '../subscription-provider';
import { Observable } from 'rxjs';
import { Client, createClient } from 'graphql-sse';
export class GraphQLSSESubscriptionProvider extends SubscriptionProvider {
client?: Client;
cleanup?: () => void;
createClient() {
this.client = createClient({
url: this.subscriptionUrl,
headers: this.extraOptions?.headers,
});
}
execute(options: SubscriptionProviderExecuteOptions) {
this.createClient();
if (!this.client) {
throw new Error('Could not create subscription client!');
}
return new Observable(subscriber => {
this.cleanup = this.client!.subscribe(
{
query: options.query,
variables: options.variables,
operationName: options.operationName,
},
{
next: (...args) => subscriber.next(...args),
error: (...args) => subscriber.error(...args),
complete: () => subscriber.complete(),
}
);
});
}
async close() {
try {
this.cleanup?.();
this.cleanup = undefined;
await this.client?.dispose();
this.client = undefined;
} catch (err) {
console.error(err);
}
}
}