UNPKG

1.58 kBJavaScriptView Raw
1const React = require('react');
2const {
3 Mixin,
4 strategies: {
5 sync: { override },
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');
17
18class GraphQLMixin extends Mixin {
19 constructor(config, element, { graphql: options = {} } = {}) {
20 super(config, element);
21
22 this.client = this.createClient(options);
23 }
24
25 createClient(options) {
26 return new ApolloClient(this.enhanceClientOptions(options));
27 }
28
29 enhanceClientOptions(options) {
30 return {
31 ...options,
32 link: options.link || this.getApolloLink(),
33 cache: options.cache || this.createCache(),
34 };
35 }
36
37 getApolloLink() {
38 return new HttpLink({
39 uri: this.config.graphqlUri,
40 });
41 }
42
43 createCache() {
44 return new InMemoryCache({
45 fragmentMatcher: this.createFragmentMatcher(),
46 }).restore(global['APOLLO_STATE']);
47 }
48
49 createFragmentMatcher() {
50 if (global['APOLLO_IQRD']) {
51 return new IntrospectionFragmentMatcher({
52 introspectionQueryResultData: global['APOLLO_IQRD'],
53 });
54 }
55 return new HeuristicFragmentMatcher();
56 }
57
58 enhanceElement(reactElement) {
59 return React.createElement(
60 ApolloProvider,
61 { client: this.client },
62 reactElement
63 );
64 }
65}
66
67GraphQLMixin.strategies = {
68 getApolloLink: override,
69};
70
71module.exports = GraphQLMixin;