-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
Copy pathinMemoryCache.ts
361 lines (304 loc) · 10.4 KB
/
inMemoryCache.ts
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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
import { DocumentNode } from 'graphql';
import { Cache, DataProxy, ApolloCache, Transaction } from 'apollo-cache';
import {
getFragmentQueryDocument,
addTypenameToDocument,
} from 'apollo-utilities';
import { HeuristicFragmentMatcher } from './fragmentMatcher';
import {
OptimisticStoreItem,
ApolloReducerConfig,
NormalizedCache,
NormalizedCacheObject,
} from './types';
import { StoreReader } from './readFromStore';
import { StoreWriter } from './writeToStore';
import { defaultNormalizedCacheFactory, DepTrackingCache } from './depTrackingCache';
import { wrap, CacheKeyNode, OptimisticWrapperFunction } from './optimism';
import { record } from './recordingCache';
const defaultConfig: ApolloReducerConfig = {
fragmentMatcher: new HeuristicFragmentMatcher(),
dataIdFromObject: defaultDataIdFromObject,
addTypename: true,
};
export function defaultDataIdFromObject(result: any): string | null {
if (result.__typename) {
if (result.id !== undefined) {
return `${result.__typename}:${result.id}`;
}
if (result._id !== undefined) {
return `${result.__typename}:${result._id}`;
}
}
return null;
}
export class InMemoryCache extends ApolloCache<NormalizedCacheObject> {
protected data: NormalizedCache;
protected config: ApolloReducerConfig;
protected optimistic: OptimisticStoreItem[] = [];
private watches = new Set<Cache.WatchOptions>();
private addTypename: boolean;
private typenameDocumentCache = new Map<DocumentNode, DocumentNode>();
private storeReader: StoreReader;
private storeWriter: StoreWriter;
private cacheKeyRoot = new CacheKeyNode();
// Set this while in a transaction to prevent broadcasts...
// don't forget to turn it back on!
private silenceBroadcast: boolean = false;
constructor(config: ApolloReducerConfig = {}) {
super();
this.config = { ...defaultConfig, ...config };
// backwards compat
if ((this.config as any).customResolvers) {
console.warn(
'customResolvers have been renamed to cacheRedirects. Please update your config as we will be deprecating customResolvers in the next major version.',
);
this.config.cacheRedirects = (this.config as any).customResolvers;
}
if ((this.config as any).cacheResolvers) {
console.warn(
'cacheResolvers have been renamed to cacheRedirects. Please update your config as we will be deprecating cacheResolvers in the next major version.',
);
this.config.cacheRedirects = (this.config as any).cacheResolvers;
}
this.addTypename = this.config.addTypename;
this.data = defaultNormalizedCacheFactory();
this.storeReader = new StoreReader({
addTypename: this.config.addTypename,
cacheKeyRoot: this.cacheKeyRoot,
});
this.storeWriter = new StoreWriter({
addTypename: this.config.addTypename,
});
const cache = this;
const { maybeBroadcastWatch } = cache;
this.maybeBroadcastWatch = wrap((c: Cache.WatchOptions) => {
return maybeBroadcastWatch.call(this, c);
}, {
makeCacheKey(c: Cache.WatchOptions) {
if (c.optimistic && cache.optimistic.length > 0) {
// If we're reading optimistic data, it doesn't matter if this.data
// is a DepTrackingCache, since it will be ignored.
return;
}
if (c.previousResult) {
// If a previousResult was provided, assume the caller would prefer
// to compare the previous data to the new data to determine whether
// to broadcast, so we should disable caching by returning here, to
// give maybeBroadcastWatch a chance to do that comparison.
return;
}
if (cache.data instanceof DepTrackingCache) {
// Return a cache key (thus enabling caching) only if we're currently
// using a data store that can track cache dependencies.
return cache.cacheKeyRoot.lookup(
c.query,
JSON.stringify(c.variables),
);
}
}
});
}
public restore(data: NormalizedCacheObject): this {
if (data) this.data.replace(data);
return this;
}
public extract(optimistic: boolean = false): NormalizedCacheObject {
if (optimistic && this.optimistic.length > 0) {
const patches = this.optimistic.map(opt => opt.data);
return Object.assign({}, this.data.toObject(), ...patches);
}
return this.data.toObject();
}
public read<T>(query: Cache.ReadOptions): T | null {
if (query.rootId && this.data.get(query.rootId) === undefined) {
return null;
}
const store = (query.optimistic && this.optimistic.length)
? defaultNormalizedCacheFactory(this.extract(true))
: this.data;
return this.storeReader.readQueryFromStore({
store,
query: query.query,
variables: query.variables,
rootId: query.rootId,
fragmentMatcherFunction: this.config.fragmentMatcher.match,
previousResult: query.previousResult,
config: this.config,
});
}
public write(write: Cache.WriteOptions): void {
this.storeWriter.writeResultToStore({
dataId: write.dataId,
result: write.result,
variables: write.variables,
document: write.query,
store: this.data,
dataIdFromObject: this.config.dataIdFromObject,
fragmentMatcherFunction: this.config.fragmentMatcher.match,
});
this.broadcastWatches();
}
public diff<T>(query: Cache.DiffOptions): Cache.DiffResult<T> {
const store = (query.optimistic && this.optimistic.length)
? defaultNormalizedCacheFactory(this.extract(true))
: this.data;
return this.storeReader.diffQueryAgainstStore({
store: store,
query: query.query,
variables: query.variables,
returnPartialData: query.returnPartialData,
previousResult: query.previousResult,
fragmentMatcherFunction: this.config.fragmentMatcher.match,
config: this.config,
});
}
public watch(watch: Cache.WatchOptions): () => void {
this.watches.add(watch);
return () => {
this.watches.delete(watch);
};
}
public evict(query: Cache.EvictOptions): Cache.EvictionResult {
throw new Error(`eviction is not implemented on InMemory Cache`);
}
public reset(): Promise<void> {
this.data.clear();
this.broadcastWatches();
return Promise.resolve();
}
public removeOptimistic(id: string) {
// Throw away optimistic changes of that particular mutation
const toPerform = this.optimistic.filter(item => item.id !== id);
this.optimistic = [];
// Re-run all of our optimistic data actions on top of one another.
toPerform.forEach(change => {
this.recordOptimisticTransaction(change.transaction, change.id);
});
this.broadcastWatches();
}
public performTransaction(transaction: Transaction<NormalizedCacheObject>) {
// TODO: does this need to be different, or is this okay for an in-memory cache?
let alreadySilenced = this.silenceBroadcast;
this.silenceBroadcast = true;
transaction(this);
if (!alreadySilenced) {
// Don't un-silence since this is a nested transaction
// (for example, a transaction inside an optimistic record)
this.silenceBroadcast = false;
}
this.broadcastWatches();
}
public recordOptimisticTransaction(
transaction: Transaction<NormalizedCacheObject>,
id: string,
) {
this.silenceBroadcast = true;
const patch = record(this.extract(true), recordingCache => {
// swapping data instance on 'this' is currently necessary
// because of the current architecture
const dataCache = this.data;
this.data = recordingCache;
this.performTransaction(transaction);
this.data = dataCache;
});
this.optimistic.push({
id,
transaction,
data: patch,
});
this.silenceBroadcast = false;
this.broadcastWatches();
}
public transformDocument(document: DocumentNode): DocumentNode {
if (this.addTypename) {
let result = this.typenameDocumentCache.get(document);
if (!result) {
this.typenameDocumentCache.set(
document,
(result = addTypenameToDocument(document)),
);
}
return result;
}
return document;
}
public readQuery<QueryType, TVariables = any>(
options: DataProxy.Query<TVariables>,
optimistic: boolean = false,
): QueryType {
return this.read({
query: options.query,
variables: options.variables,
optimistic,
});
}
public readFragment<FragmentType, TVariables = any>(
options: DataProxy.Fragment<TVariables>,
optimistic: boolean = false,
): FragmentType | null {
return this.read({
query: getFragmentQueryDocument(
options.fragment,
options.fragmentName,
),
variables: options.variables,
rootId: options.id,
optimistic,
});
}
public writeQuery<TData = any, TVariables = any>(
options: DataProxy.WriteQueryOptions<TData, TVariables>,
): void {
this.write({
dataId: 'ROOT_QUERY',
result: options.data,
query: options.query,
variables: options.variables,
});
}
public writeFragment<TData = any, TVariables = any>(
options: DataProxy.WriteFragmentOptions<TData, TVariables>,
): void {
this.write({
dataId: options.id,
result: options.data,
query: getFragmentQueryDocument(
options.fragment,
options.fragmentName,
),
variables: options.variables,
});
}
protected broadcastWatches() {
if (!this.silenceBroadcast) {
const optimistic = this.optimistic.length > 0;
this.watches.forEach((c: Cache.WatchOptions) => {
this.maybeBroadcastWatch(c);
if (optimistic) {
// If we're broadcasting optimistic data, make sure we rebroadcast
// the real data once we're no longer in an optimistic state.
(this.maybeBroadcastWatch as OptimisticWrapperFunction<
(c: Cache.WatchOptions) => void
>).dirty(c);
}
});
}
}
// This method is wrapped in the constructor so that it will be called only
// if the data that would be broadcast has changed.
private maybeBroadcastWatch(c: Cache.WatchOptions) {
const previousResult = c.previousResult && c.previousResult();
const newData = this.diff({
query: c.query,
variables: c.variables,
previousResult,
optimistic: c.optimistic,
});
if (previousResult &&
previousResult === newData.result) {
return;
}
c.callback(newData);
}
}