-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathCacheContext.ts
305 lines (257 loc) · 10.1 KB
/
CacheContext.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
import { addTypenameToDocument } from '@apollo/client/utilities';
import isEqual from '@wry/equality';
import { ApolloTransaction } from '../apollo/Transaction';
import { CacheSnapshot } from '../CacheSnapshot';
import { areChildrenDynamic, expandVariables } from '../ParsedQueryNode';
import { JsonObject } from '../primitive';
import { EntityId, OperationInstance, RawOperation } from '../schema';
import { DocumentNode, isObject } from '../util';
import { ConsoleTracer } from './ConsoleTracer';
import { QueryInfo } from './QueryInfo';
import { Tracer } from './Tracer';
// Augment DocumentNode type with Hermes's properties
// Because react-apollo can call us without doing transformDocument
// to be safe, we will always call transformDocument then flag that
// we have already done so to not repeating the process.
declare module 'graphql/language/ast' {
export interface DocumentNode {
/** Indicating that query has already ran transformDocument */
hasBeenTransformed?: boolean;
}
}
export namespace CacheContext {
export type EntityIdForNode = (node: JsonObject) => EntityId | undefined;
export type EntityIdForValue = (value: any) => EntityId | undefined;
export type EntityIdMapper = (node: JsonObject) => string | number | undefined;
export type EntityTransformer = (node: JsonObject) => void;
export type OnChangeCallback = (newCacheShapshot: CacheSnapshot, editedNodeIds: Set<String>) => void;
/**
* Expected to return an EntityId or undefined, but we loosen the restrictions
* for ease of declaration.
*/
export type ResolverRedirect = (args: JsonObject) => any;
export type ResolverRedirects = {
[typeName: string]: {
[fieldName: string]: ResolverRedirect,
},
};
/**
* Callback that is triggered when an entity is edited within the cache.
*/
export interface EntityUpdater {
// TODO: It's a bit odd that this is the _only_ Apollo-specific interface
// that we're exposing. Do we want to keep that? It does mirror a
// mutation's update callback nicely.
(dataProxy: ApolloTransaction, entity: any, previous: any): void;
}
export interface EntityUpdaters {
[typeName: string]: EntityUpdater;
}
/**
* Configuration for a Hermes cache.
*/
export interface Configuration {
/** Whether __typename should be injected into nodes in queries. */
addTypename?: boolean;
/**
* Given a node, determines a _globally unique_ identifier for it to be used
* by the cache.
*
* Generally, any node that is considered to be an entity (domain object) by
* the application should be given an id. All entities are normalized
* within the cache; everything else is not.
*/
entityIdForNode?: EntityIdMapper;
/**
* Transformation function to be run on entity nodes that change during
* write operation; an entity node is defined by `entityIdForNode`.
*/
entityTransformer?: EntityTransformer;
/**
* Whether values in the graph should be frozen.
*
* Defaults to true unless process.env.NODE_ENV === 'production'
*/
freeze?: boolean;
/**
* Parameterized fields that should redirect to entities in the cache when
* there is no value currently cached for their location.
*
* Note that you may only redirect to _entities_ within the graph.
* Redirection to arbitrary nodes is not supported.
*/
resolverRedirects?: ResolverRedirects;
/**
* Callbacks that are triggered when entities of a given type are changed.
*
* These provide the opportunity to make edits to the cache based on the
* values that were edited within entities. For example: keeping a filtered
* list in sync w/ the values within it.
*
* Note that these callbacks are called immediately before a transaction is
* committed. You will not see their effect _during_ a transaction.
*/
entityUpdaters?: EntityUpdaters;
/**
* Callback that is triggered when there is a change in the cache.
*
* This allow the cache to be integrated with external tools such as Redux.
* It allows other tools to be notified when there are changes.
*/
onChange?: OnChangeCallback;
/**
* The tracer to instrument the cache with.
*
* If not supplied, a ConsoleTracer will be constructed, with `verbose` and
* `logger` passed as its arguments.
*/
tracer?: Tracer;
/**
* Whether strict mode is enabled (defaults to true).
*/
strict?: boolean;
/**
* Whether debugging information should be logged out.
*
* Enabling this will cause the cache to emit log events for most operations
* performed against it.
*
* Ignored if `tracer` is supplied.
*/
verbose?: boolean;
/**
* The logger to use when emitting messages. By default, `console`.
*
* Ignored if `tracer` is supplied.
*/
logger?: ConsoleTracer.Logger;
}
}
/**
* Configuration and shared state used throughout the cache's operation.
*/
export class CacheContext {
/** Retrieve the EntityId for a given node, if any. */
readonly entityIdForValue: CacheContext.EntityIdForValue;
/** Run transformation on changed entity node, if any. */
readonly entityTransformer: CacheContext.EntityTransformer | undefined;
/** Whether we should freeze snapshots after writes. */
readonly freezeSnapshots: boolean;
/** Whether the cache should emit debug level log events. */
readonly verbose: boolean;
/** Configured resolver redirects. */
readonly resolverRedirects: CacheContext.ResolverRedirects;
/** Configured entity updaters. */
readonly entityUpdaters: CacheContext.EntityUpdaters;
/** Configured on-change callback */
readonly onChange: CacheContext.OnChangeCallback | undefined;
/** Whether the cache should operate in strict mode. */
readonly strict: boolean;
/** The tracer we should use. */
readonly tracer: Tracer;
/** Whether __typename should be injected into nodes in queries. */
readonly addTypename: boolean;
/** All currently known & processed GraphQL documents. */
private readonly _queryInfoMap = new Map<string, QueryInfo>();
/** All currently known & parsed queries, for identity mapping. */
private readonly _operationMap = new Map<string, OperationInstance[]>();
constructor(config: CacheContext.Configuration = {}) {
// Infer dev mode from NODE_ENV, by convention.
const nodeEnv = typeof process !== 'undefined' ? process.env.NODE_ENV : 'development';
this.entityIdForValue = _makeEntityIdMapper(config.entityIdForNode);
this.entityTransformer = config.entityTransformer;
this.freezeSnapshots = 'freeze' in config ? !!config.freeze : nodeEnv !== 'production';
this.strict = typeof config.strict === 'boolean' ? config.strict : true;
this.verbose = !!config.verbose;
this.resolverRedirects = config.resolverRedirects || {};
this.onChange = config.onChange;
this.entityUpdaters = config.entityUpdaters || {};
this.tracer = config.tracer || new ConsoleTracer(!!config.verbose, config.logger);
this.addTypename = config.addTypename || false;
}
/**
* Performs any transformations of operation documents.
*
* Cache consumers should call this on any operation document prior to calling
* any other method in the cache.
*/
transformDocument(document: DocumentNode): DocumentNode {
if (this.addTypename && !document.hasBeenTransformed) {
const transformedDocument = addTypenameToDocument(document);
transformedDocument.hasBeenTransformed = true;
return transformedDocument;
}
return document;
}
/**
* Returns a memoized & parsed operation.
*
* To aid in various cache lookups, the result is memoized by all of its
* values, and can be used as an identity for a specific operation.
*/
parseOperation(raw: RawOperation): OperationInstance {
// It appears like Apollo or someone upstream is cloning or otherwise
// modifying the queries that are passed down. Thus, the operation source
// is a more reliable cache key…
const cacheKey = operationCacheKey(raw.document, raw.fragmentName);
let operationInstances = this._operationMap.get(cacheKey);
if (!operationInstances) {
operationInstances = [];
this._operationMap.set(cacheKey, operationInstances);
}
// Do we already have a copy of this guy?
for (const instance of operationInstances) {
if (instance.rootId !== raw.rootId) continue;
if (!isEqual(instance.variables, raw.variables)) continue;
return instance;
}
const updateRaw: RawOperation = {
...raw,
document: this.transformDocument(raw.document),
};
const info = this._queryInfo(cacheKey, updateRaw);
const fullVariables = { ...info.variableDefaults, ...updateRaw.variables } as JsonObject;
const operation = {
info,
rootId: updateRaw.rootId,
parsedQuery: expandVariables(info.parsed, fullVariables),
isStatic: !areChildrenDynamic(info.parsed),
variables: updateRaw.variables,
};
operationInstances.push(operation);
return operation;
}
/**
* Retrieves a memoized QueryInfo for a given GraphQL document.
*/
private _queryInfo(cacheKey: string, raw: RawOperation): QueryInfo {
if (!this._queryInfoMap.has(cacheKey)) {
this._queryInfoMap.set(cacheKey, new QueryInfo(this, raw));
}
return this._queryInfoMap.get(cacheKey)!;
}
}
/**
* Wrap entityIdForNode so that it coerces all values to strings.
*/
export function _makeEntityIdMapper(
mapper: CacheContext.EntityIdMapper = defaultEntityIdMapper,
): CacheContext.EntityIdForValue {
return function entityIdForNode(node: JsonObject) {
if (!isObject(node)) return undefined;
// We don't trust upstream implementations.
const entityId = mapper(node);
if (typeof entityId === 'string') return entityId;
if (typeof entityId === 'number') return String(entityId);
return undefined;
};
}
export function defaultEntityIdMapper(node: { id?: any }) {
return node.id;
}
export function operationCacheKey(document: DocumentNode, fragmentName?: string) {
if (fragmentName) {
return `${fragmentName}❖${document.loc!.source.body}`;
}
return document.loc!.source.body;
}