forked from urql-graphql/urql
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.tsx
303 lines (280 loc) · 7.61 KB
/
client.tsx
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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
import { Component, ReactNode } from 'react';
import { IClient, IMutation, IQuery } from '../interfaces/index';
import { hashString } from '../modules/hash';
import { formatTypeNames } from '../modules/typenames';
export interface IClientProps {
client: IClient; // Client instance
children: (obj: object) => ReactNode; // Render prop
query: IQuery | IQuery[]; // Query object or array of Query objects
mutation?: IMutation; // Mutation object (map)
cache?: boolean;
typeInvalidation?: boolean;
shouldInvalidate?: (
changedTypes: string[],
typeNames: string[],
response: object,
data: object
) => boolean;
}
export interface IClientFetchOpts {
skipCache: boolean; // Should skip cache?
}
export interface IClientState {
fetching: boolean; // Loading
loaded: boolean; // Initial load
error?: Error; // Error
data: object[] | IClientState[]; // Data
}
export default class UrqlClient extends Component<IClientProps, IClientState> {
static defaultProps = {
cache: true,
typeInvalidation: true,
};
state = {
data: null,
error: null,
fetching: false,
loaded: false,
};
query = null; // Stored Query
mutations = {}; // Stored Mutation
typeNames = []; // Typenames that exist on current query
subscriptionID = null; // Change subscription ID
componentDidMount() {
this.formatProps(this.props);
}
componentDidUpdate(prevProps) {
const nextProps = this.props;
if (
prevProps.query !== nextProps.query ||
prevProps.mutation !== nextProps.mutation
) {
this.formatProps(nextProps);
}
}
componentWillUnmount() {
// Unsub from change listener
this.props.client.unsubscribe(this.subscriptionID);
}
invalidate = queryObject => {
const { cache } = this.props.client;
if (queryObject) {
const stringified = JSON.stringify(formatTypeNames(queryObject));
const hash = hashString(stringified);
return cache.invalidate(hash);
} else {
return Array.isArray(this.props.query)
? Promise.all(
this.props.query.map(q =>
cache.invalidate(hashString(JSON.stringify(q)))
)
)
: cache.invalidate(hashString(JSON.stringify(this.query)));
}
};
invalidateAll = () => {
return this.props.client.cache.invalidateAll();
};
read = query => {
const formatted = formatTypeNames(query);
const stringified = JSON.stringify(formatted);
const hash = hashString(stringified);
return this.props.client.cache.read(hash);
};
updateCache = callback => {
return this.props.client.cache.update(callback);
};
formatProps = props => {
// If query exists
if (props.query) {
// Loop through and add typenames
this.query = Array.isArray(props.query)
? props.query.map(formatTypeNames)
: formatTypeNames(props.query);
// Subscribe to change listener
this.subscriptionID = props.client.subscribe(this.update);
// Fetch initial data
this.fetch(undefined, true);
}
// If mutation exists and has keys
if (props.mutation) {
this.mutations = {};
// Loop through and add typenames
Object.keys(props.mutation).forEach(key => {
this.mutations[key] = formatTypeNames(props.mutation[key]);
});
// bind to mutate
Object.keys(this.mutations).forEach(m => {
const query = this.mutations[m].query;
this.mutations[m] = variables => {
return this.mutate({
query,
variables: {
...this.mutations[m].variables,
...variables,
},
});
};
if (!this.props.query) {
this.forceUpdate();
}
});
}
};
update = (changedTypes, response, refresh) => {
if (refresh === true) {
this.fetch();
}
let invalidated = false;
if (this.props.shouldInvalidate) {
invalidated = this.props.shouldInvalidate(
changedTypes,
this.typeNames,
response,
this.state.data
);
} else if (this.props.typeInvalidation !== false) {
// Check connection typenames, derived from query, for presence of mutated typenames
this.typeNames.forEach(typeName => {
if (changedTypes.indexOf(typeName) !== -1) {
invalidated = true;
}
});
}
// If it has any of the type names that changed
if (invalidated) {
// Refetch the data from the server
this.fetch({ skipCache: true });
}
};
refreshAllFromCache = () => {
return this.props.client.refreshAllFromCache();
};
fetch = (
opts: IClientFetchOpts = { skipCache: false },
initial?: boolean
) => {
const { client } = this.props;
let { skipCache } = opts;
if (this.props.cache === false) {
skipCache = true;
}
// If query is not an array
if (!Array.isArray(this.query)) {
// Start loading state
this.setState({
error: null,
fetching: true,
});
// Fetch the query
client
.executeQuery(this.query, skipCache)
.then(result => {
// Store the typenames
if (result.typeNames) {
this.typeNames = result.typeNames;
}
// Update data
this.setState({
data: result.data,
fetching: false,
loaded: initial ? true : this.state.loaded,
});
})
.catch(e => {
this.setState({
error: e,
fetching: false,
});
});
} else {
// Start fetching state
this.setState({
error: null,
fetching: true,
});
// Iterate over and fetch queries
const partialData = [];
return Promise.all(
this.query.map(query => {
return client.executeQuery(query, skipCache).then(result => {
if (result.typeNames) {
// Add and dedupe typenames
this.typeNames = [...this.typeNames, ...result.typeNames].filter(
(v, i, a) => a.indexOf(v) === i
);
}
partialData.push(result.data);
return result.data;
});
})
)
.then(results => {
this.setState({
data: results,
fetching: false,
loaded: true,
});
})
.catch(e => {
this.setState({
data: partialData,
error: e,
fetching: false,
});
});
}
};
mutate = mutation => {
const { client } = this.props;
// Set fetching state
this.setState({
error: null,
fetching: true,
});
return new Promise((resolve, reject) => {
// Execute mutation
client
.executeMutation(mutation)
.then((...args) => {
this.setState(
{
fetching: false,
},
() => {
resolve(...args);
}
);
})
.catch(e => {
this.setState(
{
error: e,
fetching: false,
},
() => {
reject(e);
}
);
});
});
};
render() {
const cache = {
invalidate: this.invalidate,
invalidateAll: this.invalidateAll,
read: this.read,
update: this.updateCache,
};
return typeof this.props.children === 'function'
? this.props.children({
...this.state,
...this.mutations,
cache,
client: this.props.client,
refetch: this.fetch,
refreshAllFromCache: this.refreshAllFromCache,
})
: null;
}
}