-
Notifications
You must be signed in to change notification settings - Fork 266
/
client.js
176 lines (154 loc) · 5.8 KB
/
client.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
/*!
* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
* Licensed under the Amazon Software License (the "License"). You may not use this file except in compliance with the License. A copy of
* the License is located at
* http://aws.amazon.com/asl/
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
import ApolloClient, { ApolloClientOptions, MutationOptions } from 'apollo-client';
import { NormalizedCache } from 'apollo-cache-inmemory';
import { ApolloLink, FetchResult } from 'apollo-link';
import { HttpLink } from 'apollo-link-http';
import { getMainDefinition, getOperationDefinition, variablesInOperation } from 'apollo-utilities';
import { Action, applyMiddleware, createStore, compose, combineReducers, Store } from 'redux';
import { offline } from '@redux-offline/redux-offline';
import offlineConfig from '@redux-offline/redux-offline/lib/defaults';
import thunk from 'redux-thunk';
import InMemoryCache, { reducer as cacheReducer } from './cache/index';
import { OfflineLink, AuthLink, NonTerminatingHttpLink, SubscriptionHandshakeLink, ComplexObjectLink } from './link';
import { reducer as commitReducer, offlineEffect, discard } from './link/offline-link';
/**
*
* @param {Function} persistCallback
* @param {*} effect
* @returns {Store<NormalizedCache>}
*/
const newStore = (persistCallback = () => null, effect, discard) => {
return createStore(
combineReducers({
rehydrated: (state = false, action) => {
switch (action.type) {
case 'REHYDRATE_STORE':
return true;
default:
return state;
}
},
...cacheReducer(),
...commitReducer(),
}),
// @ts-ignore
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__(),
compose(
applyMiddleware(thunk),
offline({
...offlineConfig,
persistCallback,
persistOptions: {
blacklist: ['rehydrated', 'eclipse']
},
effect,
discard,
})
)
);
};
class AWSAppSyncClient extends ApolloClient {
/**
* @type {Store<{}>}
* @private
*/
aasStore;
/**
* @type {Promise<AWSAppSyncClient>}
*/
hydratedPromise;
hydrated = () => this.hydratedPromise;
/**
*
* @param {string} url
* @param {ApolloClientOptions<InMemoryCache>} options
*/
constructor({ url, region, auth, conflictResolver, complexObjectsCredentials }, options) {
if (!url || !region || !auth) {
throw new Error(`
In order to initialize AWSAppSyncClient, you must specify url, region and auth properties on the config object.
`);
}
let res;
this.hydratedPromise = new Promise((resolve, reject) => {
res = resolve;
});
const store = newStore(
() => {
this.aasStore.dispatch({ type: 'REHYDRATE_STORE' });
res(this);
},
(effect, action) => offlineEffect(this, effect, action),
discard(conflictResolver),
);
const cache = new InMemoryCache(store);
let link = ApolloLink.from([
new OfflineLink(store),
new AuthLink({ url, region, auth }),
ApolloLink.split(
operation => {
const { query } = operation;
const { kind, operation: graphqlOperation } = getMainDefinition(query);
const isSubscription = kind === 'OperationDefinition' && graphqlOperation === 'subscription';
return isSubscription;
},
ApolloLink.from([
new NonTerminatingHttpLink('subsInfo', { uri: url }, true),
new SubscriptionHandshakeLink('subsInfo'),
]),
ApolloLink.from([
new ComplexObjectLink(complexObjectsCredentials),
new HttpLink({ uri: url }),
]),
),
]);
const newOptions = {
...options,
link,
cache,
};
super(newOptions);
this.aasStore = store;
}
/**
*
* @param {MutationOptions} options
* @returns {Promise<FetchResult>}
*/
mutate(options, extraOpts = {}) {
const { mutation, variables: mutationVariables, optimisticResponse, context: origContext = {} } = options;
const { AASContext: { ...origASAContext = {} } = {} } = origContext;
const operationDefinition = getOperationDefinition(mutation);
const varsInOperation = variablesInOperation(operationDefinition);
const variables = Array.from(varsInOperation).reduce((obj, key) => {
obj[key] = mutationVariables[key];
return obj;
}, {});
// refetchQueries left out intentionally when !doIt so we don't run them twice
const { refetchQueries, ...otherOptions } = options;
const { doIt } = origASAContext;
const context = {
...origContext,
AASContext: {
...origASAContext,
mutation,
variables,
optimisticResponse,
refetchQueries,
},
};
return super.mutate({
...otherOptions,
refetchQueries: doIt ? refetchQueries : undefined,
context,
});
}
};
export { AWSAppSyncClient };