-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreateInMemorySnapshotStorage.ts
More file actions
64 lines (61 loc) · 2.09 KB
/
createInMemorySnapshotStorage.ts
File metadata and controls
64 lines (61 loc) · 2.09 KB
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
import type {
AggregateRootDefinition,
AggregateRootDefinitionMap,
AggregateRootDefinitionMapTypes,
AggregateStateVersion,
} from "../AggregateRootDefinition.ts";
import type { SnapshotStorage } from "../SnapshotStorage.ts";
import type { AggregateRootInstance } from "../AggregateRootInstance.ts";
/**
* An in-memory implementation of snapshot storage.
*
* Unlike an event store, in-memory snapshot storage can be a useful concept in production
* because having snapshots stored in memory for the duration of the process saves a lot
* of traffic to the database over the lifetime of the process. This is provided the application
* can tolerate a "warm up" for each aggregate root, where on first load, all events will still
* be loaded and reduced.
*
* For cases where too many events exist to replay and reduce on demand, persistent snapshot
* storage can be used.
*/
export function createInMemorySnapshotStorage<
TAggregateDefinitionMap extends AggregateRootDefinitionMap<TAggregateMapTypes>,
TAggregateMapTypes extends AggregateRootDefinitionMapTypes,
>(): SnapshotStorage<TAggregateDefinitionMap, TAggregateMapTypes> {
const storage: Record<string, AggregateRootInstance<unknown, AggregateRootDefinition<unknown, unknown>>> =
{};
return {
persist: async ({
aggregateRoot,
stateVersion,
}) => {
const key = snapshotKey(
aggregateRoot.aggregateRootType as string,
aggregateRoot.aggregateRootId,
stateVersion,
);
storage[key] = aggregateRoot;
},
retrieve: async ({
aggregateRootType,
aggregateRootId,
stateVersion,
}) => {
const key = snapshotKey(aggregateRootType as string, aggregateRootId, stateVersion);
return storage[key] as AggregateRootInstance<
typeof aggregateRootType,
AggregateRootDefinition<
unknown,
unknown
>
>;
},
};
}
function snapshotKey(
aggregateType: string,
aggregateId: string,
aggregateRootStateVersion: AggregateStateVersion,
): string {
return `${aggregateType}:${aggregateId}:${aggregateRootStateVersion}`;
}