-
Notifications
You must be signed in to change notification settings - Fork 30
/
OptimisticUpdateQueue.ts
65 lines (56 loc) · 1.7 KB
/
OptimisticUpdateQueue.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
import { CacheContext } from './context';
import { GraphSnapshot } from './GraphSnapshot';
import { SnapshotEditor } from './operations';
import { JsonObject } from './primitive';
import { ChangeId, NodeId, QuerySnapshot } from './schema';
/**
* Tracks an individual optimistic update.
*/
export interface OptimisticUpdate {
id: ChangeId;
deltas: QuerySnapshot[];
}
/**
* Manages a queue of optimistic updates, and the values they express on top of
* existing cache snapshots.
*/
export class OptimisticUpdateQueue {
constructor(
/**
* The queue of updates, in order of oldest (lowest precedence) to newest
* (highest precedence).
*/
private _updates = [] as OptimisticUpdate[],
) {}
/**
* Appends a new optimistic update to the queue.
*/
enqueue(id: ChangeId, deltas: QuerySnapshot[]): OptimisticUpdateQueue {
// TODO: Assert unique change ids.
return new OptimisticUpdateQueue([...this._updates, { id, deltas }]);
}
/**
* Removes an update from the queue.
*/
remove(id: ChangeId): OptimisticUpdateQueue {
return new OptimisticUpdateQueue(this._updates.filter(u => u.id !== id));
}
/**
* Whether there are any updates to apply.
*/
hasUpdates(): boolean {
return this._updates.length > 0;
}
/**
* Applies the current optimistic updates to a snapshot.
*/
apply(context: CacheContext, snapshot: GraphSnapshot): { snapshot: GraphSnapshot, editedNodeIds: Set<NodeId> } {
const editor = new SnapshotEditor(context, snapshot);
for (const update of this._updates) {
for (const delta of update.deltas) {
editor.mergePayload(delta.query, delta.payload as JsonObject);
}
}
return editor.commit();
}
}