-
Notifications
You must be signed in to change notification settings - Fork 75
/
createAbsintheSocketLink.js
54 lines (46 loc) · 1.48 KB
/
createAbsintheSocketLink.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
// @flow
import {ApolloLink} from "apollo-link";
import {send, toObservable, unobserveOrCancel} from "@absinthe/socket";
import {compose} from "flow-static-land/lib/Fun";
import {print} from "graphql";
import type {AbsintheSocket, GqlRequest, Observer} from "@absinthe/socket";
import type {DocumentNode} from "graphql/language/ast";
type ApolloOperation<Variables> = {|
query: DocumentNode,
variables: Variables
|};
const unobserveOrCancelIfNeeded = (absintheSocket, notifier, observer) => {
if (notifier && observer) {
unobserveOrCancel(absintheSocket, notifier, observer);
}
};
const notifierToObservable = (absintheSocket, onError, onStart) => notifier =>
toObservable(absintheSocket, notifier, {
onError,
onStart,
unsubscribe: unobserveOrCancelIfNeeded
});
const getRequest = <Variables: Object>({
query,
variables
}: ApolloOperation<Variables>): GqlRequest<Variables> => ({
operation: print(query),
variables
});
/**
* Creates a terminating ApolloLink to request operations using given
* AbsintheSocket instance
*/
const createAbsintheSocketLink = <Result, Variables: void | Object>(
absintheSocket: AbsintheSocket,
onError?: $ElementType<Observer<Result, Variables>, "onError">,
onStart?: $ElementType<Observer<Result, Variables>, "onStart">
) =>
new ApolloLink(
compose(
notifierToObservable(absintheSocket, onError, onStart),
request => send(absintheSocket, request),
getRequest
)
);
export default createAbsintheSocketLink;