UNPKG

1.93 kBJavaScriptView Raw
1const React = require('react');
2const {
3 Mixin,
4 strategies: {
5 sync: { override, callable },
6 },
7} = require('hops-mixin');
8
9const { ApolloProvider } = require('react-apollo');
10const { default: ApolloClient } = require('apollo-client');
11const { HttpLink } = require('apollo-link-http');
12const {
13 InMemoryCache,
14 IntrospectionFragmentMatcher,
15 HeuristicFragmentMatcher,
16} = require('apollo-cache-inmemory');
17require('cross-fetch/polyfill');
18
19class GraphQLMixin extends Mixin {
20 constructor(config, element, { graphql: options = {} } = {}) {
21 super(config, element);
22
23 this.options = options;
24 }
25
26 getApolloClient() {
27 if (this.client) {
28 return this.client;
29 }
30 return (this.client = this.createClient(this.options));
31 }
32
33 createClient(options) {
34 return new ApolloClient(this.enhanceClientOptions(options));
35 }
36
37 enhanceClientOptions(options) {
38 return {
39 ...options,
40 link: this.getApolloLink(),
41 cache: this.getApolloCache(),
42 };
43 }
44
45 getApolloLink() {
46 return (
47 this.options.link ||
48 new HttpLink({
49 uri: this.config.graphqlUri,
50 fetch: global.fetch,
51 })
52 );
53 }
54
55 getApolloCache() {
56 return (
57 this.options.cache ||
58 new InMemoryCache({
59 fragmentMatcher: this.createFragmentMatcher(),
60 }).restore(global['APOLLO_STATE'])
61 );
62 }
63
64 createFragmentMatcher() {
65 if (global['APOLLO_FRAGMENT_TYPES']) {
66 return new IntrospectionFragmentMatcher({
67 introspectionQueryResultData: global['APOLLO_FRAGMENT_TYPES'],
68 });
69 }
70 return new HeuristicFragmentMatcher();
71 }
72
73 enhanceElement(reactElement) {
74 return React.createElement(
75 ApolloProvider,
76 { client: this.getApolloClient() },
77 reactElement
78 );
79 }
80}
81
82GraphQLMixin.strategies = {
83 getApolloLink: override,
84 getApolloCache: override,
85 createFragmentMatcher: callable,
86};
87
88module.exports = GraphQLMixin;