/
queue-worker.js
81 lines (73 loc) · 2.15 KB
/
queue-worker.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import fetch from 'node-fetch';
import WebSocket from 'ws';
import gql from 'graphql-tag';
import { host, port } from './config';
import { ApolloClient } from 'apollo-client';
import { InMemoryCache, IntrospectionFragmentMatcher } from 'apollo-cache-inmemory';
import { HttpLink } from 'apollo-link-http';
import { ApolloLink, split } from 'apollo-link';
import { WebSocketLink } from 'apollo-link-ws';
import { getMainDefinition } from 'apollo-utilities';
const START_REGISTRATION_QUEUE = gql`
mutation {
startRegistrationQueue
}
`;
const REGISTRATION_QUEUED = gql`
subscription onRegistrationQueued {
registrationQueued
}
`;
const REGISTRATION_FINISHED = gql`
subscription onRegistrationFinished {
registrationFinished
}
`;
const RESET_REGISTRATION_QUEUE = gql`
mutation {
resetRegistrationQueue
}
`;
export default introspectionQueryResultData => {
const fragmentMatcher = new IntrospectionFragmentMatcher({
introspectionQueryResultData
});
const wsLink = new WebSocketLink({
uri: `ws://${host}:${port}/graphql`,
options: {
reconnect: true
},
webSocketImpl: WebSocket
});
const cache = new InMemoryCache({ fragmentMatcher });
const httpLink = new HttpLink({ uri: `http://${host}:${port}/graphql`, fetch });
const link = split(
// split based on operation type
({ query }) => {
const { kind, operation } = getMainDefinition(query);
return kind === 'OperationDefinition' && operation === 'subscription';
},
wsLink,
ApolloLink.from([httpLink]),
);
const client = new ApolloClient({
link,
cache
});
const startRegistrationQueue = async () => await client.mutate({ mutation: START_REGISTRATION_QUEUE });
client.mutate({ mutation: RESET_REGISTRATION_QUEUE })
.then(() => {
client
.subscribe({ query: REGISTRATION_QUEUED })
.subscribe({
next: startRegistrationQueue,
error(err) { console.error('err', err); }
});
client
.subscribe({ query: REGISTRATION_FINISHED })
.subscribe({
next: startRegistrationQueue,
error(err) { console.error('err', err); }
});
});
};