-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMongoDBPersistenceEngine.ts
115 lines (100 loc) · 2.66 KB
/
MongoDBPersistenceEngine.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
import type {
Collection,
CollectionOptions,
DbOptions,
MongoClient,
} from "mongodb";
import type {
EventStream,
PersistedEvent,
PersistedSnapshot,
PersistenceEngine,
} from "nact";
import { isNil } from "./isNil";
const DEFAULT_EVENT_JOURNAL_NAME = "nact_events";
const DEFAULT_SNAPSHOT_STORE_NAME = "nact_snapshots";
export class MongoDBPersistenceEngine implements PersistenceEngine {
/**
* Collection which persists `PersistedEvent[]`
*/
eventsCollection: Collection<PersistedEvent>;
/**
* Collection which persists `PersistedSnapshot[]`
*/
snapshotsCollection: Collection<PersistedSnapshot>;
constructor(
private mongoClient: MongoClient,
options?: {
dbName?: string;
dbOptions?: DbOptions;
eventsCollectionName?: string;
eventsCollectionOptions?: CollectionOptions;
snapshotsCollectionName?: string;
snapshotsCollectionOptions?: CollectionOptions;
},
) {
const db = this.mongoClient.db(options?.dbName, options?.dbOptions);
this.eventsCollection = db.collection<PersistedEvent>(
options?.eventsCollectionName ?? DEFAULT_EVENT_JOURNAL_NAME,
options?.eventsCollectionOptions,
);
this.snapshotsCollection = db.collection<PersistedSnapshot>(
options?.snapshotsCollectionName ?? DEFAULT_SNAPSHOT_STORE_NAME,
options?.snapshotsCollectionOptions,
);
}
events(
persistenceKey: string,
offset?: number,
limit?: number,
tags?: string[],
): EventStream {
let cursor = this.eventsCollection
.find({
key: persistenceKey,
...(!isNil(tags)
? {
tags: {
$in: tags,
},
}
: null),
})
.sort({
createdAt: 1,
});
if (!isNil(offset)) {
cursor = cursor.skip(offset);
}
if (!isNil(limit)) {
cursor = cursor.limit(limit);
}
const result = cursor.toArray();
return {
then(onfullfilled) {
return result.then(onfullfilled);
},
async reduce(...args) {
return result.then((events) => events.reduce(...args));
},
};
}
async latestSnapshot(persistenceKey: string) {
const cursor = this.snapshotsCollection
.find({
key: persistenceKey,
})
.sort({
createdAt: -1,
})
.limit(1);
const snapshot = await cursor.next();
return snapshot;
}
async takeSnapshot(persistedSnapshot: PersistedSnapshot): Promise<void> {
await this.snapshotsCollection.insertOne(persistedSnapshot);
}
async persist(persistedEvent: PersistedEvent): Promise<void> {
await this.eventsCollection.insertOne(persistedEvent);
}
}