-
Notifications
You must be signed in to change notification settings - Fork 24
/
GraphiQLSubscriptionsFetcher.js
47 lines (40 loc) · 1.26 KB
/
GraphiQLSubscriptionsFetcher.js
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
import { parse } from 'graphql';
const hasSubscriptionOperation = (graphQlParams) => {
const queryDoc = parse(graphQlParams.query);
for (let definition of queryDoc.definitions) {
if (definition.kind === 'OperationDefinition') {
const operation = definition.operation;
if (operation === 'subscription') {
return true;
}
}
}
return false;
};
export const graphQLFetcher = (subscriptionsClient, fallbackFetcher) => {
let activeSubscriptionId = null;
return (graphQLParams) => {
if (subscriptionsClient && activeSubscriptionId !== null) {
subscriptionsClient.unsubscribe(activeSubscriptionId);
}
if (subscriptionsClient && hasSubscriptionOperation(graphQLParams)) {
return {
subscribe() {
observer.next('Your subscription data will appear here after server publication!');
activeSubscriptionId = subscriptionsClient.subscribe({
query: graphQLParams.query,
variables: graphQLParams.variables,
}, function (error, result) {
if (error) {
observer.error(error);
} else {
observer.next(result);
}
});
}
};
} else {
return fallbackFetcher(graphQLParams);
}
};
};