@twin.org/entity-storage-connector-mongodb 0.0.1-next.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,335 @@
1
+ import { Guards, BaseError, Is, GeneralError } from '@twin.org/core';
2
+ import { EntitySchemaFactory, EntitySchemaHelper, SortDirection, LogicalOperator, ComparisonOperator } from '@twin.org/entity';
3
+ import { LoggingConnectorFactory } from '@twin.org/logging-models';
4
+ import { MongoClient } from 'mongodb';
5
+
6
+ // Copyright 2024 IOTA Stiftung.
7
+ // SPDX-License-Identifier: Apache-2.0.
8
+ /**
9
+ * Class for performing entity storage operations using MongoDb.
10
+ */
11
+ class MongoDbEntityStorageConnector {
12
+ /**
13
+ * Limit the number of entities when finding.
14
+ * @internal
15
+ */
16
+ static _PAGE_SIZE = 40;
17
+ /**
18
+ * Runtime name for the class.
19
+ */
20
+ CLASS_NAME = "MongoDbEntityStorageConnector";
21
+ /**
22
+ * The schema for the entity.
23
+ * @internal
24
+ */
25
+ _entitySchema;
26
+ /**
27
+ * The configuration for the connector.
28
+ * @internal
29
+ */
30
+ _config;
31
+ /**
32
+ * The MongoDb client.
33
+ * @internal
34
+ */
35
+ _client;
36
+ /**
37
+ * Create a new instance of MongoDbEntityStorageConnector.
38
+ * @param options The options for the connector.
39
+ */
40
+ constructor(options) {
41
+ Guards.object(this.CLASS_NAME, "options", options);
42
+ Guards.stringValue(this.CLASS_NAME, "options.entitySchema", options.entitySchema);
43
+ Guards.object(this.CLASS_NAME, "options.config", options.config);
44
+ Guards.stringValue(this.CLASS_NAME, "options.config.host", options.config.host);
45
+ Guards.stringValue(this.CLASS_NAME, "options.config.database", options.config.database);
46
+ Guards.stringValue(this.CLASS_NAME, "options.config.collection", options.config.collection);
47
+ this._entitySchema = EntitySchemaFactory.get(options.entitySchema);
48
+ this._config = options.config;
49
+ this._client = new MongoClient(this.createConnectionConfig());
50
+ }
51
+ /**
52
+ * Initialize the MongoDb environment.
53
+ * @param nodeLoggingConnectorType Optional type of the logging connector.
54
+ * @returns A promise that resolves to a boolean indicating success.
55
+ */
56
+ async bootstrap(nodeLoggingConnectorType) {
57
+ const nodeLogging = LoggingConnectorFactory.getIfExists(nodeLoggingConnectorType ?? "node-logging");
58
+ try {
59
+ await this._client.connect();
60
+ await nodeLogging?.log({
61
+ level: "info",
62
+ source: this.CLASS_NAME,
63
+ ts: Date.now(),
64
+ message: "databaseCreating",
65
+ data: {
66
+ database: this._config.database
67
+ }
68
+ });
69
+ // Create the database if it does not exist
70
+ this._client.db(this._config.database);
71
+ await nodeLogging?.log({
72
+ level: "info",
73
+ source: this.CLASS_NAME,
74
+ ts: Date.now(),
75
+ message: "databaseExists",
76
+ data: {
77
+ database: this._config.database
78
+ }
79
+ });
80
+ await this.getCollection();
81
+ await nodeLogging?.log({
82
+ level: "info",
83
+ source: this.CLASS_NAME,
84
+ ts: Date.now(),
85
+ message: "collectionExists",
86
+ data: {
87
+ collection: this._config.collection
88
+ }
89
+ });
90
+ }
91
+ catch (error) {
92
+ const errors = error instanceof AggregateError ? error.errors : [error];
93
+ for (const err of errors) {
94
+ await nodeLogging?.log({
95
+ level: "error",
96
+ source: this.CLASS_NAME,
97
+ ts: Date.now(),
98
+ message: "databaseCreateFailed",
99
+ error: BaseError.fromError(err),
100
+ data: {
101
+ database: this._config.database
102
+ }
103
+ });
104
+ }
105
+ return false;
106
+ }
107
+ return true;
108
+ }
109
+ /**
110
+ * Get the schema for the entities.
111
+ * @returns The schema for the entities.
112
+ */
113
+ getSchema() {
114
+ return this._entitySchema;
115
+ }
116
+ /**
117
+ * Get an entity from MongoDb.
118
+ * @param id The id of the entity to get, or the index value if secondaryIndex is set.
119
+ * @param secondaryIndex Get the item using a secondary index.
120
+ * @param conditions The optional conditions to match for the entities.
121
+ * @returns The object if it can be found or undefined.
122
+ */
123
+ async get(id, secondaryIndex, conditions) {
124
+ Guards.stringValue(this.CLASS_NAME, "id", id);
125
+ try {
126
+ const primaryKey = EntitySchemaHelper.getPrimaryKey(this.getSchema());
127
+ const query = Is.empty(secondaryIndex)
128
+ ? { [primaryKey.property]: id }
129
+ : { [secondaryIndex]: id };
130
+ if (conditions) {
131
+ for (const condition of conditions) {
132
+ query[condition.property] = condition.value;
133
+ }
134
+ }
135
+ const collection = await this.getCollection();
136
+ const result = await collection.findOne(query);
137
+ return result;
138
+ }
139
+ catch (err) {
140
+ throw new GeneralError(this.CLASS_NAME, "getFailed", {
141
+ id
142
+ }, err);
143
+ }
144
+ }
145
+ /**
146
+ * Set an entity.
147
+ * @param entity The entity to set.
148
+ * @param conditions The optional conditions to match for the entities.
149
+ * @returns The id of the entity.
150
+ */
151
+ async set(entity, conditions) {
152
+ Guards.object(this.CLASS_NAME, "entity", entity);
153
+ const primaryKey = EntitySchemaHelper.getPrimaryKey(this.getSchema());
154
+ const id = entity[primaryKey.property];
155
+ try {
156
+ const filter = { [primaryKey.property]: id };
157
+ if (Is.arrayValue(conditions)) {
158
+ for (const condition of conditions) {
159
+ filter[condition.property] = condition.value;
160
+ }
161
+ }
162
+ const collection = await this.getCollection();
163
+ await collection.findOneAndUpdate(filter, { $set: entity }, { upsert: true });
164
+ }
165
+ catch (err) {
166
+ throw new GeneralError(this.CLASS_NAME, "setFailed", {
167
+ id
168
+ }, err);
169
+ }
170
+ }
171
+ /**
172
+ * Remove the entity.
173
+ * @param id The id of the entity to remove.
174
+ * @param conditions The optional conditions to match for the entities.
175
+ * @returns Nothing.
176
+ */
177
+ async remove(id, conditions) {
178
+ Guards.stringValue(this.CLASS_NAME, "id", id);
179
+ try {
180
+ const primaryKey = EntitySchemaHelper.getPrimaryKey(this.getSchema());
181
+ const query = { [primaryKey.property]: id };
182
+ if (conditions) {
183
+ for (const condition of conditions) {
184
+ query[condition.property] = condition.value;
185
+ }
186
+ }
187
+ const collection = await this.getCollection();
188
+ await collection.deleteOne(query);
189
+ }
190
+ catch (err) {
191
+ throw new GeneralError(this.CLASS_NAME, "removeFailed", { id }, err);
192
+ }
193
+ }
194
+ /**
195
+ * Find all the entities which match the conditions.
196
+ * @param conditions The conditions to match for the entities.
197
+ * @param sortProperties The optional sort order.
198
+ * @param properties The optional properties to return, defaults to all.
199
+ * @param cursor The cursor to request the next page of entities.
200
+ * @param pageSize The suggested number of entities to return in each chunk, in some scenarios can return a different amount.
201
+ * @returns All the entities for the storage matching the conditions,
202
+ * and a cursor which can be used to request more entities.
203
+ */
204
+ async query(conditions, sortProperties, properties, cursor, pageSize) {
205
+ const returnSize = pageSize ?? MongoDbEntityStorageConnector._PAGE_SIZE;
206
+ const filter = {};
207
+ if (conditions) {
208
+ this.buildQueryParameters("", conditions, filter);
209
+ }
210
+ const sort = {};
211
+ if (Array.isArray(sortProperties)) {
212
+ for (const sortProperty of sortProperties) {
213
+ const direction = sortProperty.sortDirection === SortDirection.Ascending ? 1 : -1;
214
+ sort[sortProperty.property] = direction;
215
+ }
216
+ }
217
+ const projection = {};
218
+ if (properties) {
219
+ for (const property of properties) {
220
+ projection[property] = 1;
221
+ }
222
+ }
223
+ const cursorValue = cursor ? Number(cursor) : 0;
224
+ const collection = await this.getCollection();
225
+ const entities = await collection
226
+ ?.find(filter, { projection })
227
+ .sort(sort)
228
+ .skip(cursorValue)
229
+ .limit(returnSize)
230
+ .toArray();
231
+ return {
232
+ entities: entities ?? [],
233
+ cursor: entities?.length === returnSize ? String(cursorValue + returnSize) : undefined
234
+ };
235
+ }
236
+ /**
237
+ * Drop the collection.
238
+ * @returns Nothing.
239
+ */
240
+ async collectionDrop() {
241
+ try {
242
+ const collection = await this.getCollection();
243
+ await collection.drop();
244
+ }
245
+ catch {
246
+ // Ignore errors
247
+ }
248
+ }
249
+ /**
250
+ * Create a new DB connection configuration.
251
+ * @returns The MongoDb connection configuration.
252
+ * @internal
253
+ */
254
+ createConnectionConfig() {
255
+ const { host, port, user, password, database } = this._config;
256
+ const portPart = port ? `:${port}` : "";
257
+ if (user && password) {
258
+ return `mongodb://${user}:${password}@${host}${portPart}/${database}`;
259
+ }
260
+ return `mongodb://${host}${portPart}/${database}`;
261
+ }
262
+ /**
263
+ * Return a Mongo DB collection.
264
+ * @returns The MongoDb collection.
265
+ * @internal
266
+ */
267
+ async getCollection() {
268
+ const { database, collection } = this._config;
269
+ return this._client.db(database).collection(collection);
270
+ }
271
+ /**
272
+ * Create an MongoDB filter query.
273
+ * @param objectPath The path for the nested object.
274
+ * @param condition The conditions to create the query from.
275
+ * @param filter The filter query to use.
276
+ * @internal
277
+ */
278
+ buildQueryParameters(objectPath, condition, filter) {
279
+ if (!condition) {
280
+ return;
281
+ }
282
+ if ("conditions" in condition) {
283
+ const subConditions = condition.conditions.map(c => {
284
+ const subFilter = {};
285
+ this.buildQueryParameters(objectPath, c, subFilter);
286
+ return subFilter;
287
+ });
288
+ if (condition.logicalOperator === LogicalOperator.And) {
289
+ filter.$and = subConditions;
290
+ }
291
+ else if (condition.logicalOperator === LogicalOperator.Or) {
292
+ filter.$or = subConditions;
293
+ }
294
+ else {
295
+ Object.assign(filter, subConditions[0]);
296
+ }
297
+ }
298
+ else {
299
+ const prop = objectPath ? `${objectPath}.${condition.property}` : String(condition.property);
300
+ const comparison = this.mapComparisonOperator(condition.comparison, condition.value);
301
+ filter[prop] = comparison;
302
+ }
303
+ }
304
+ /**
305
+ * Map the framework comparison operators to those in MongoDB.
306
+ * @param comparison The comparison operator.
307
+ * @param value The value to compare.
308
+ * @returns The MongoDB comparison expression.
309
+ * @internal
310
+ */
311
+ mapComparisonOperator(comparison, value) {
312
+ switch (comparison) {
313
+ case ComparisonOperator.Equals:
314
+ return value;
315
+ case ComparisonOperator.NotEquals:
316
+ return { $ne: value };
317
+ case ComparisonOperator.GreaterThan:
318
+ return { $gt: value };
319
+ case ComparisonOperator.LessThan:
320
+ return { $lt: value };
321
+ case ComparisonOperator.GreaterThanOrEqual:
322
+ return { $gte: value };
323
+ case ComparisonOperator.LessThanOrEqual:
324
+ return { $lte: value };
325
+ case ComparisonOperator.In:
326
+ return { $in: Array.isArray(value) ? value : [value] };
327
+ case ComparisonOperator.Includes:
328
+ return { $elemMatch: { $eq: value } };
329
+ default:
330
+ throw new GeneralError(this.CLASS_NAME, "unsupportedComparisonOperator", { comparison });
331
+ }
332
+ }
333
+ }
334
+
335
+ export { MongoDbEntityStorageConnector };
@@ -0,0 +1,3 @@
1
+ export * from "./mongoDbEntityStorageConnector";
2
+ export * from "./models/IMongoDbEntityStorageConnectorConfig";
3
+ export * from "./models/IMongoDbEntityStorageConnectorConstructorOptions";
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Configuration for the MongoDb Entity Storage Connector.
3
+ */
4
+ export interface IMongoDbEntityStorageConnectorConfig {
5
+ /**
6
+ * The host for the MongoDb instance.
7
+ */
8
+ host: string;
9
+ /**
10
+ * The port for the MongoDb instance.
11
+ */
12
+ port?: number;
13
+ /**
14
+ * The user for the MongoDb instance.
15
+ */
16
+ user?: string;
17
+ /**
18
+ * The password for the MongoDb instance.
19
+ */
20
+ password?: string;
21
+ /**
22
+ * The name of the database to be used.
23
+ */
24
+ database: string;
25
+ /**
26
+ * The name of the collection to be used.
27
+ */
28
+ collection: string;
29
+ }
@@ -0,0 +1,19 @@
1
+ import type { IMongoDbEntityStorageConnectorConfig } from "./IMongoDbEntityStorageConnectorConfig";
2
+ /**
3
+ * The options for the MongoDb entity storage connector constructor.
4
+ */
5
+ export interface IMongoDbEntityStorageConnectorConstructorOptions {
6
+ /**
7
+ * The schema for the entity.
8
+ */
9
+ entitySchema: string;
10
+ /**
11
+ * The type of logging connector to use.
12
+ * @default logging
13
+ */
14
+ loggingConnectorType?: string;
15
+ /**
16
+ * The configuration for the connector.
17
+ */
18
+ config: IMongoDbEntityStorageConnectorConfig;
19
+ }
@@ -0,0 +1,81 @@
1
+ import { type EntityCondition, type IEntitySchema, SortDirection } from "@twin.org/entity";
2
+ import type { IEntityStorageConnector } from "@twin.org/entity-storage-models";
3
+ import type { IMongoDbEntityStorageConnectorConstructorOptions } from "./models/IMongoDbEntityStorageConnectorConstructorOptions";
4
+ /**
5
+ * Class for performing entity storage operations using MongoDb.
6
+ */
7
+ export declare class MongoDbEntityStorageConnector<T = unknown> implements IEntityStorageConnector<T> {
8
+ /**
9
+ * Runtime name for the class.
10
+ */
11
+ readonly CLASS_NAME: string;
12
+ /**
13
+ * Create a new instance of MongoDbEntityStorageConnector.
14
+ * @param options The options for the connector.
15
+ */
16
+ constructor(options: IMongoDbEntityStorageConnectorConstructorOptions);
17
+ /**
18
+ * Initialize the MongoDb environment.
19
+ * @param nodeLoggingConnectorType Optional type of the logging connector.
20
+ * @returns A promise that resolves to a boolean indicating success.
21
+ */
22
+ bootstrap(nodeLoggingConnectorType?: string): Promise<boolean>;
23
+ /**
24
+ * Get the schema for the entities.
25
+ * @returns The schema for the entities.
26
+ */
27
+ getSchema(): IEntitySchema;
28
+ /**
29
+ * Get an entity from MongoDb.
30
+ * @param id The id of the entity to get, or the index value if secondaryIndex is set.
31
+ * @param secondaryIndex Get the item using a secondary index.
32
+ * @param conditions The optional conditions to match for the entities.
33
+ * @returns The object if it can be found or undefined.
34
+ */
35
+ get(id: string, secondaryIndex?: keyof T, conditions?: {
36
+ property: keyof T;
37
+ value: unknown;
38
+ }[]): Promise<T | undefined>;
39
+ /**
40
+ * Set an entity.
41
+ * @param entity The entity to set.
42
+ * @param conditions The optional conditions to match for the entities.
43
+ * @returns The id of the entity.
44
+ */
45
+ set(entity: T, conditions?: {
46
+ property: keyof T;
47
+ value: unknown;
48
+ }[]): Promise<void>;
49
+ /**
50
+ * Remove the entity.
51
+ * @param id The id of the entity to remove.
52
+ * @param conditions The optional conditions to match for the entities.
53
+ * @returns Nothing.
54
+ */
55
+ remove(id: string, conditions?: {
56
+ property: keyof T;
57
+ value: unknown;
58
+ }[]): Promise<void>;
59
+ /**
60
+ * Find all the entities which match the conditions.
61
+ * @param conditions The conditions to match for the entities.
62
+ * @param sortProperties The optional sort order.
63
+ * @param properties The optional properties to return, defaults to all.
64
+ * @param cursor The cursor to request the next page of entities.
65
+ * @param pageSize The suggested number of entities to return in each chunk, in some scenarios can return a different amount.
66
+ * @returns All the entities for the storage matching the conditions,
67
+ * and a cursor which can be used to request more entities.
68
+ */
69
+ query(conditions?: EntityCondition<T>, sortProperties?: {
70
+ property: keyof T;
71
+ sortDirection: SortDirection;
72
+ }[], properties?: (keyof T)[], cursor?: string, pageSize?: number): Promise<{
73
+ entities: Partial<T>[];
74
+ cursor?: string;
75
+ }>;
76
+ /**
77
+ * Drop the collection.
78
+ * @returns Nothing.
79
+ */
80
+ collectionDrop(): Promise<void>;
81
+ }
@@ -0,0 +1,5 @@
1
+ # @twin.org/entity-storage-connector-mongodb - Changelog
2
+
3
+ ## v0.0.1-next.20
4
+
5
+ - Initial Release
@@ -0,0 +1 @@
1
+ # @twin.org/entity-storage-connector-mongodb - Examples