@twin.org/entity-storage-connector-cosmosdb 0.0.1-next.12

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,595 @@
1
+ import { CosmosClient, CosmosDbDiagnosticLevel, PartitionKeyKind } from '@azure/cosmos';
2
+ import { Guards, BaseError, Is, GeneralError, Coerce, ObjectHelper } from '@twin.org/core';
3
+ import { EntitySchemaFactory, EntitySchemaHelper, SortDirection, ComparisonOperator, LogicalOperator } from '@twin.org/entity';
4
+ import { LoggingConnectorFactory } from '@twin.org/logging-models';
5
+
6
+ // Copyright 2024 IOTA Stiftung.
7
+ // SPDX-License-Identifier: Apache-2.0.
8
+ /**
9
+ * Class for performing entity storage operations using Cosmos DB.
10
+ */
11
+ class CosmosDbEntityStorageConnector {
12
+ /**
13
+ * Limit the number of entities when finding.
14
+ * @internal
15
+ */
16
+ static _PAGE_SIZE = 40;
17
+ /**
18
+ * Partition id field name.
19
+ * @internal
20
+ */
21
+ static _PARTITION_ID_NAME = "partitionId";
22
+ /**
23
+ * Partition id field path.
24
+ * @internal
25
+ */
26
+ static _PARTITION_ID_PATH = "/partitionId";
27
+ /**
28
+ * Partition id field value.
29
+ * @internal
30
+ */
31
+ static _PARTITION_ID_VALUE = "1";
32
+ /**
33
+ * Runtime name for the class.
34
+ */
35
+ CLASS_NAME = "CosmosDbEntityStorageConnector";
36
+ /**
37
+ * The schema for the entity.
38
+ * @internal
39
+ */
40
+ _entitySchema;
41
+ /**
42
+ * The primary key.
43
+ * @internal
44
+ */
45
+ _primaryKey;
46
+ /**
47
+ * The configuration for the connector.
48
+ * @internal
49
+ */
50
+ _config;
51
+ /**
52
+ * The Cosmos DB client.
53
+ * @internal
54
+ */
55
+ _client;
56
+ /**
57
+ * Container user for the data storage.
58
+ * @internal
59
+ */
60
+ _container;
61
+ /**
62
+ * Create a new instance of CosmosDbEntityStorageConnector.
63
+ * @param options The options for the connector.
64
+ * @param options.entitySchema The schema for the entity.
65
+ * @param options.loggingConnectorType The type of logging connector to use, defaults to no logging.
66
+ * @param options.config The configuration for the connector.
67
+ */
68
+ constructor(options) {
69
+ Guards.object(this.CLASS_NAME, "options", options);
70
+ Guards.stringValue(this.CLASS_NAME, "options.entitySchema", options.entitySchema);
71
+ Guards.object(this.CLASS_NAME, "options.config", options.config);
72
+ Guards.stringValue(this.CLASS_NAME, "options.config.endpoint", options.config.endpoint);
73
+ Guards.stringValue(this.CLASS_NAME, "options.config.key", options.config.key);
74
+ Guards.stringValue(this.CLASS_NAME, "options.config.databaseId", options.config.databaseId);
75
+ Guards.stringValue(this.CLASS_NAME, "options.config.containerId", options.config.containerId);
76
+ this._entitySchema = EntitySchemaFactory.get(options.entitySchema);
77
+ this._primaryKey = EntitySchemaHelper.getPrimaryKey(this._entitySchema);
78
+ this._config = options.config;
79
+ this._client = new CosmosClient({
80
+ endpoint: this._config.endpoint,
81
+ key: this._config.key,
82
+ diagnosticLevel: CosmosDbDiagnosticLevel.debug
83
+ });
84
+ this._container = this._client
85
+ .database(this._config.databaseId)
86
+ .container(this._config.containerId);
87
+ }
88
+ /**
89
+ * Initialize the Cosmos DB environment.
90
+ * @param nodeLoggingConnectorType Optional type of the logging connector.
91
+ * @returns A promise that resolves to a boolean indicating success.
92
+ */
93
+ async bootstrap(nodeLoggingConnectorType) {
94
+ const nodeLogging = LoggingConnectorFactory.getIfExists(nodeLoggingConnectorType ?? "node-logging");
95
+ // Create the database if it does not exist
96
+ try {
97
+ await nodeLogging?.log({
98
+ level: "info",
99
+ source: this.CLASS_NAME,
100
+ ts: Date.now(),
101
+ message: "databaseCreating",
102
+ data: {
103
+ databaseId: this._config.databaseId
104
+ }
105
+ });
106
+ const { resource: databaseDefinition } = await this._client.databases.createIfNotExists({
107
+ id: this._config.databaseId
108
+ });
109
+ Guards.stringValue(this.CLASS_NAME, "databaseDefinition.id", databaseDefinition?.id);
110
+ await nodeLogging?.log({
111
+ level: "info",
112
+ source: this.CLASS_NAME,
113
+ ts: Date.now(),
114
+ message: "databaseExists",
115
+ data: {
116
+ databaseId: databaseDefinition.id
117
+ }
118
+ });
119
+ }
120
+ catch (error) {
121
+ if (BaseError.isErrorCode(error, "Conflict")) {
122
+ await nodeLogging?.log({
123
+ level: "info",
124
+ source: this.CLASS_NAME,
125
+ ts: Date.now(),
126
+ message: "databaseAlreadyExists",
127
+ data: {
128
+ databaseId: this._config.databaseId
129
+ }
130
+ });
131
+ }
132
+ else {
133
+ const errors = error instanceof AggregateError ? error.errors : [error];
134
+ for (const err of errors) {
135
+ await nodeLogging?.log({
136
+ level: "error",
137
+ source: this.CLASS_NAME,
138
+ ts: Date.now(),
139
+ message: "databaseCreateFailed",
140
+ error: BaseError.fromError(err),
141
+ data: {
142
+ databaseId: this._config.databaseId
143
+ }
144
+ });
145
+ }
146
+ return false;
147
+ }
148
+ }
149
+ // Create the container if it does not exist
150
+ try {
151
+ const { resource: containerDefinition } = await this._client
152
+ .database(this._config.databaseId)
153
+ .containers.createIfNotExists({
154
+ id: this._config.containerId,
155
+ partitionKey: {
156
+ kind: PartitionKeyKind.Hash,
157
+ paths: [CosmosDbEntityStorageConnector._PARTITION_ID_PATH]
158
+ }
159
+ }, { offerThroughput: 400 });
160
+ if (containerDefinition) {
161
+ await nodeLogging?.log({
162
+ level: "info",
163
+ source: this.CLASS_NAME,
164
+ ts: Date.now(),
165
+ message: "containerExists",
166
+ data: {
167
+ containerId: this._config.containerId
168
+ }
169
+ });
170
+ }
171
+ else {
172
+ await nodeLogging?.log({
173
+ level: "error",
174
+ source: this.CLASS_NAME,
175
+ ts: Date.now(),
176
+ message: "containerNotExisting",
177
+ data: {
178
+ containerId: this._config.containerId
179
+ }
180
+ });
181
+ return false;
182
+ }
183
+ }
184
+ catch (error) {
185
+ await nodeLogging?.log({
186
+ level: "error",
187
+ source: this.CLASS_NAME,
188
+ ts: Date.now(),
189
+ message: "containerCreateFailed",
190
+ error: BaseError.fromError(error),
191
+ data: {
192
+ containerId: this._config.containerId
193
+ }
194
+ });
195
+ return false;
196
+ }
197
+ return true;
198
+ }
199
+ /**
200
+ * Get the schema for the entities.
201
+ * @returns The schema for the entities.
202
+ */
203
+ getSchema() {
204
+ return this._entitySchema;
205
+ }
206
+ /**
207
+ * Get an entity from Cosmos DB.
208
+ * @param id The id of the entity to get, or the index value if secondaryIndex is set.
209
+ * @param secondaryIndex Get the item using a secondary index.
210
+ * @param conditions The optional conditions to match for the entities.
211
+ * @returns The object if it can be found or undefined.
212
+ */
213
+ async get(id, secondaryIndex, conditions) {
214
+ Guards.stringValue(this.CLASS_NAME, "id", id);
215
+ try {
216
+ // No secondary index or conditions
217
+ if (Is.empty(secondaryIndex) && !Is.arrayValue(conditions)) {
218
+ const { resource: item } = await this._container
219
+ .item(id, CosmosDbEntityStorageConnector._PARTITION_ID_VALUE)
220
+ .read();
221
+ return this.itemToEntity(item);
222
+ }
223
+ const whereQuery = [
224
+ `c.${CosmosDbEntityStorageConnector._PARTITION_ID_NAME} = @partitionKey`
225
+ ];
226
+ // With a secondary index
227
+ if (Is.stringValue(secondaryIndex)) {
228
+ const secIndex = secondaryIndex.toString();
229
+ whereQuery.push(`c.${secIndex} = @id`);
230
+ }
231
+ else {
232
+ whereQuery.push(`c.${this._primaryKey.property} = @id`);
233
+ }
234
+ // With conditions
235
+ if (Is.arrayValue(conditions)) {
236
+ for (const c of conditions) {
237
+ const schemaProp = this._entitySchema.properties?.find(p => p.property === c.property);
238
+ whereQuery.push(`c.${String(c.property)} = ${this.propertyToDbValue(c.value, schemaProp?.type)}`);
239
+ }
240
+ }
241
+ const query = {
242
+ query: `SELECT * FROM c WHERE ${whereQuery.join(" AND ")}`,
243
+ parameters: [
244
+ { name: "@id", value: id },
245
+ { name: "@partitionKey", value: CosmosDbEntityStorageConnector._PARTITION_ID_VALUE }
246
+ ]
247
+ };
248
+ const { resources: items } = await this._container.items.query(query).fetchAll();
249
+ if (items.length === 1) {
250
+ return this.itemToEntity(items[0]);
251
+ }
252
+ }
253
+ catch (err) {
254
+ if (BaseError.isErrorCode(err, "NotFound")) {
255
+ throw new GeneralError(this.CLASS_NAME, "containerDoesNotExist", {
256
+ container: this._config.containerId
257
+ }, err);
258
+ }
259
+ throw new GeneralError(this.CLASS_NAME, "getFailed", {
260
+ id
261
+ }, err);
262
+ }
263
+ return undefined;
264
+ }
265
+ /**
266
+ * Set an entity.
267
+ * @param entity The entity to set.
268
+ * @param conditions The optional conditions to match for the entities.
269
+ * @returns The id of the entity.
270
+ */
271
+ async set(entity, conditions) {
272
+ Guards.object(this.CLASS_NAME, "entity", entity);
273
+ const id = entity[this._primaryKey.property];
274
+ try {
275
+ if (Is.arrayValue(conditions)) {
276
+ const item = await this._container.item(id, CosmosDbEntityStorageConnector._PARTITION_ID_VALUE);
277
+ const { resource: itemData } = await item.read();
278
+ if (Is.notEmpty(itemData) && !this.verifyConditions(conditions, itemData)) {
279
+ return;
280
+ }
281
+ }
282
+ await this._container.items.upsert({
283
+ id,
284
+ [CosmosDbEntityStorageConnector._PARTITION_ID_NAME]: CosmosDbEntityStorageConnector._PARTITION_ID_VALUE,
285
+ ...entity
286
+ });
287
+ }
288
+ catch (err) {
289
+ if (BaseError.isErrorCode(err, "ResourceNotFoundException")) {
290
+ throw new GeneralError(this.CLASS_NAME, "containerDoesNotExist", {
291
+ containerId: this._config.containerId
292
+ }, err);
293
+ }
294
+ throw new GeneralError(this.CLASS_NAME, "setFailed", {
295
+ id
296
+ }, err);
297
+ }
298
+ }
299
+ /**
300
+ * Remove the entity.
301
+ * @param id The id of the entity to remove.
302
+ * @param conditions The optional conditions to match for the entities.
303
+ * @returns Nothing.
304
+ */
305
+ async remove(id, conditions) {
306
+ Guards.stringValue(this.CLASS_NAME, "id", id);
307
+ try {
308
+ const item = await this._container.item(id, CosmosDbEntityStorageConnector._PARTITION_ID_VALUE);
309
+ const { resource: itemData } = await item.read();
310
+ if (Is.notEmpty(itemData)) {
311
+ if (Is.arrayValue(conditions) && !this.verifyConditions(conditions, itemData)) {
312
+ return;
313
+ }
314
+ await item.delete();
315
+ }
316
+ }
317
+ catch (err) {
318
+ if (BaseError.fromError(err) &&
319
+ Is.object(err) &&
320
+ err.body?.code === "NotFound") {
321
+ return;
322
+ }
323
+ throw new GeneralError(this.CLASS_NAME, "removeFailed", {
324
+ id
325
+ }, err);
326
+ }
327
+ }
328
+ /**
329
+ * Find all the entities which match the conditions.
330
+ * @param conditions The conditions to match for the entities.
331
+ * @param sortProperties The optional sort order.
332
+ * @param properties The optional properties to return, defaults to all.
333
+ * @param cursor The cursor to request the next page of entities.
334
+ * @param pageSize The suggested number of entities to return in each chunk, in some scenarios can return a different amount.
335
+ * @returns All the entities for the storage matching the conditions,
336
+ * and a cursor which can be used to request more entities.
337
+ */
338
+ async query(conditions, sortProperties, properties, cursor, pageSize) {
339
+ const sql = "";
340
+ try {
341
+ const returnSize = pageSize ?? CosmosDbEntityStorageConnector._PAGE_SIZE;
342
+ let orderByClause = "";
343
+ if (Array.isArray(sortProperties)) {
344
+ if (sortProperties.length > 1) {
345
+ throw new GeneralError(this.CLASS_NAME, "sortSingle");
346
+ }
347
+ for (const sortProperty of sortProperties) {
348
+ const propertySchema = this._entitySchema.properties?.find(e => e.property === sortProperty.property);
349
+ if (!propertySchema ||
350
+ (!propertySchema.isPrimary &&
351
+ !propertySchema.isSecondary &&
352
+ !propertySchema.sortDirection)) {
353
+ throw new GeneralError(this.CLASS_NAME, "sortNotIndexed", {
354
+ property: sortProperty.property
355
+ });
356
+ }
357
+ const direction = sortProperty.sortDirection === SortDirection.Ascending ? "asc" : "desc";
358
+ orderByClause = `ORDER BY c.${String(sortProperty.property)} ${direction}`;
359
+ }
360
+ }
361
+ const attributeNames = {};
362
+ const attributeValues = {};
363
+ let queryClause = this.buildQueryParameters("", conditions, attributeNames, attributeValues);
364
+ if (queryClause.length > 0) {
365
+ queryClause = ` AND ${queryClause}`;
366
+ }
367
+ const querySpecs = {
368
+ query: `SELECT ${properties ? properties.map(p => `c.${p}`).join(", ") : "*"} FROM c WHERE c.partitionId = @partitionId ${queryClause} ${orderByClause}`,
369
+ parameters: [
370
+ { name: "@partitionId", value: CosmosDbEntityStorageConnector._PARTITION_ID_VALUE },
371
+ ...Object.keys(attributeValues).map(key => ({ name: `@${key}`, value: attributeValues[key] }))
372
+ ]
373
+ };
374
+ const feedOptions = {
375
+ maxItemCount: returnSize,
376
+ continuationToken: cursor
377
+ };
378
+ const feedResponse = await this._container.items.query(querySpecs, feedOptions).fetchNext();
379
+ return {
380
+ entities: feedResponse.resources.map(i => this.itemToEntity(i)),
381
+ cursor: feedResponse.continuationToken
382
+ };
383
+ }
384
+ catch (err) {
385
+ throw new GeneralError(this.CLASS_NAME, "queryFailed", { sql }, err);
386
+ }
387
+ }
388
+ /**
389
+ * Delete the container.
390
+ * @returns Nothing.
391
+ */
392
+ async containerDelete() {
393
+ try {
394
+ await this._container.deleteAllItemsForPartitionKey(CosmosDbEntityStorageConnector._PARTITION_ID_VALUE);
395
+ await this._container.delete();
396
+ }
397
+ catch {
398
+ // Ignore errors
399
+ }
400
+ }
401
+ /**
402
+ * Create an SQL condition clause.
403
+ * @param objectPath The path for the nested object.
404
+ * @param condition The conditions to create the query from.
405
+ * @param attributeNames The attribute names to use in the query.
406
+ * @param attributeValues The attribute values to use in the query.
407
+ * @returns The condition clause.
408
+ * @internal
409
+ */
410
+ buildQueryParameters(objectPath, condition, attributeNames, attributeValues) {
411
+ // If no conditions are defined then return empty string
412
+ if (Is.undefined(condition)) {
413
+ return "";
414
+ }
415
+ if ("conditions" in condition) {
416
+ if (condition.conditions.length === 0) {
417
+ return "";
418
+ }
419
+ // It's a group of comparisons, so check the individual items and combine with the logical operator
420
+ const joinConditions = condition.conditions.map(c => this.buildQueryParameters(objectPath, c, attributeNames, attributeValues));
421
+ const logicalOperator = this.mapConditionalOperator(condition.logicalOperator);
422
+ const queryClause = joinConditions
423
+ .filter(j => j.length > 0)
424
+ .map(j => j)
425
+ .join(` ${logicalOperator} `);
426
+ return Is.stringValue(queryClause) ? ` (${queryClause}) ` : "";
427
+ }
428
+ const schemaProp = this._entitySchema.properties?.find(p => p.property === condition.property);
429
+ // It's a single value so just create the property comparison for the condition
430
+ const comparison = this.mapComparisonOperator(objectPath, condition, schemaProp?.type, attributeNames, attributeValues);
431
+ return comparison;
432
+ }
433
+ /**
434
+ * Map the framework comparison operators to those in CosmosDB.
435
+ * @param objectPath The prefix to use for the condition.
436
+ * @param comparator The operator to map.
437
+ * @param type The type of the property.
438
+ * @param attributeValues The attribute values to use in the query.
439
+ * @returns The comparison expression.
440
+ * @throws GeneralError if the comparison operator is not supported.
441
+ * @internal
442
+ */
443
+ mapComparisonOperator(objectPath, comparator, type, attributeNames, attributeValues) {
444
+ let prop = objectPath;
445
+ if (prop.length > 0) {
446
+ prop += ".";
447
+ }
448
+ prop += comparator.property;
449
+ let attributeName = this.populateAttributeNames(prop, attributeNames);
450
+ let propName = `${attributeName.replace(/\./g, "").replace(/@/g, "")}`;
451
+ if (Is.array(comparator.value)) {
452
+ const dbValues = comparator.value.map(v => this.propertyToDbValue(v, type));
453
+ const arrAttributeNames = [];
454
+ for (let i = 0; i < dbValues.length; i++) {
455
+ const arrAttributeName = `${propName}${i}`;
456
+ attributeValues[arrAttributeName] = dbValues[i];
457
+ arrAttributeNames.push(arrAttributeName);
458
+ }
459
+ propName = attributeName;
460
+ attributeName = `(${arrAttributeNames.map(name => `@${name}`).join(", ")})`;
461
+ }
462
+ else {
463
+ attributeValues[propName] = comparator.value;
464
+ }
465
+ const matches = attributeName.split(".").length;
466
+ if (matches && comparator.comparison === ComparisonOperator.Equals) {
467
+ attributeName = attributeName
468
+ .split(".")
469
+ .map(part => `["${part}"]`)
470
+ .join("");
471
+ return `c${attributeName} = @${propName}`;
472
+ }
473
+ else if (comparator.comparison === ComparisonOperator.Equals) {
474
+ return `c.${attributeName} = @${propName}`;
475
+ }
476
+ else if (comparator.comparison === ComparisonOperator.NotEquals) {
477
+ return `c.${attributeName} <> @${propName}`;
478
+ }
479
+ else if (comparator.comparison === ComparisonOperator.GreaterThan) {
480
+ return `c.${attributeName} > @${propName}`;
481
+ }
482
+ else if (comparator.comparison === ComparisonOperator.LessThan) {
483
+ return `c.${attributeName} < @${propName}`;
484
+ }
485
+ else if (comparator.comparison === ComparisonOperator.GreaterThanOrEqual) {
486
+ return `c.${attributeName} >= @${propName}`;
487
+ }
488
+ else if (comparator.comparison === ComparisonOperator.LessThanOrEqual) {
489
+ return `c.${attributeName} <= @${propName}`;
490
+ }
491
+ else if (typeof attributeValues[propName] === "object" &&
492
+ comparator.comparison === ComparisonOperator.Includes) {
493
+ return `array_contains(c.${attributeName}, @${propName})`;
494
+ }
495
+ else if (comparator.comparison === ComparisonOperator.Includes) {
496
+ return `contains(c.${attributeName}, @${propName})`;
497
+ }
498
+ else if (comparator.comparison === ComparisonOperator.NotIncludes) {
499
+ return `notContains(c.${attributeName}, @${propName})`;
500
+ }
501
+ else if (comparator.comparison === ComparisonOperator.In) {
502
+ return `c.${propName} IN ${attributeName}`;
503
+ }
504
+ throw new GeneralError(this.CLASS_NAME, "comparisonNotSupported", {
505
+ comparison: comparator.comparison
506
+ });
507
+ }
508
+ /**
509
+ * Format a value to insert into DB.
510
+ * @param value The value to format.
511
+ * @param type The type for the property.
512
+ * @returns The value after conversion.
513
+ * @internal
514
+ */
515
+ propertyToDbValue(value, type) {
516
+ if (Is.object(value)) {
517
+ const map = {};
518
+ for (const key in value) {
519
+ map[key] = this.propertyToDbValue(value[key]);
520
+ }
521
+ return map;
522
+ }
523
+ if (type === "string") {
524
+ return `${Coerce.string(value)}`;
525
+ }
526
+ else if (type === "integer" || type === "number") {
527
+ return Coerce.string(value) ?? "";
528
+ }
529
+ else if (type === "boolean") {
530
+ return Coerce.boolean(value) ?? false;
531
+ }
532
+ return Coerce.string(value) ?? "";
533
+ }
534
+ /**
535
+ * Create a unique name for the attribute.
536
+ * @param name The name to create a unique name for.
537
+ * @param attributeNames The attribute names to use in the query.
538
+ * @returns The unique name.
539
+ * @internal
540
+ */
541
+ populateAttributeNames(name, attributeNames) {
542
+ const parts = name.split(".");
543
+ const attributeNameParts = [];
544
+ for (const part of parts) {
545
+ const hashPart = `${part}`;
546
+ if (Is.empty(attributeNames[hashPart])) {
547
+ attributeNames[hashPart] = part;
548
+ }
549
+ attributeNameParts.push(hashPart);
550
+ }
551
+ return attributeNameParts.join(".");
552
+ }
553
+ /**
554
+ * Map the framework conditional operators to those in CosmosDB.
555
+ * @param operator The operator to map.
556
+ * @returns The conditional operator.
557
+ * @throws GeneralError if the conditional operator is not supported.
558
+ * @internal
559
+ */
560
+ mapConditionalOperator(operator) {
561
+ if ((operator ?? LogicalOperator.And) === LogicalOperator.And) {
562
+ return "AND";
563
+ }
564
+ else if (operator === LogicalOperator.Or) {
565
+ return "OR";
566
+ }
567
+ throw new GeneralError(this.CLASS_NAME, "conditionalNotSupported", { operator });
568
+ }
569
+ /**
570
+ * Creates the CosmosDB container to be used if it doesn't exists in the context yet.
571
+ * @returns The existing container.
572
+ * @throws GeneralError if the container was not created.
573
+ * @internal
574
+ */
575
+ verifyConditions(conditions, obj) {
576
+ return conditions.every(condition => ObjectHelper.propertyGet(obj, condition.property) === condition.value);
577
+ }
578
+ /**
579
+ * Convert an entity to an item.
580
+ * @param item The item to convert.
581
+ * @returns The entity.
582
+ * @internal
583
+ */
584
+ itemToEntity(item) {
585
+ ObjectHelper.propertyDelete(item, "partitionId");
586
+ ObjectHelper.propertyDelete(item, "_attachments");
587
+ ObjectHelper.propertyDelete(item, "_etag");
588
+ ObjectHelper.propertyDelete(item, "_rid");
589
+ ObjectHelper.propertyDelete(item, "_self");
590
+ ObjectHelper.propertyDelete(item, "_ts");
591
+ return item;
592
+ }
593
+ }
594
+
595
+ export { CosmosDbEntityStorageConnector };
@@ -0,0 +1,88 @@
1
+ import { type EntityCondition, type IEntitySchema, SortDirection } from "@twin.org/entity";
2
+ import type { IEntityStorageConnector } from "@twin.org/entity-storage-models";
3
+ import type { ICosmosDbEntityStorageConnectorConfig } from "./models/ICosmosDbEntityStorageConnectorConfig";
4
+ /**
5
+ * Class for performing entity storage operations using Cosmos DB.
6
+ */
7
+ export declare class CosmosDbEntityStorageConnector<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 CosmosDbEntityStorageConnector.
14
+ * @param options The options for the connector.
15
+ * @param options.entitySchema The schema for the entity.
16
+ * @param options.loggingConnectorType The type of logging connector to use, defaults to no logging.
17
+ * @param options.config The configuration for the connector.
18
+ */
19
+ constructor(options: {
20
+ entitySchema: string;
21
+ loggingConnectorType?: string;
22
+ config: ICosmosDbEntityStorageConnectorConfig;
23
+ });
24
+ /**
25
+ * Initialize the Cosmos DB environment.
26
+ * @param nodeLoggingConnectorType Optional type of the logging connector.
27
+ * @returns A promise that resolves to a boolean indicating success.
28
+ */
29
+ bootstrap(nodeLoggingConnectorType?: string): Promise<boolean>;
30
+ /**
31
+ * Get the schema for the entities.
32
+ * @returns The schema for the entities.
33
+ */
34
+ getSchema(): IEntitySchema;
35
+ /**
36
+ * Get an entity from Cosmos DB.
37
+ * @param id The id of the entity to get, or the index value if secondaryIndex is set.
38
+ * @param secondaryIndex Get the item using a secondary index.
39
+ * @param conditions The optional conditions to match for the entities.
40
+ * @returns The object if it can be found or undefined.
41
+ */
42
+ get(id: string, secondaryIndex?: keyof T, conditions?: {
43
+ property: keyof T;
44
+ value: unknown;
45
+ }[]): Promise<T | undefined>;
46
+ /**
47
+ * Set an entity.
48
+ * @param entity The entity to set.
49
+ * @param conditions The optional conditions to match for the entities.
50
+ * @returns The id of the entity.
51
+ */
52
+ set(entity: T, conditions?: {
53
+ property: keyof T;
54
+ value: unknown;
55
+ }[]): Promise<void>;
56
+ /**
57
+ * Remove the entity.
58
+ * @param id The id of the entity to remove.
59
+ * @param conditions The optional conditions to match for the entities.
60
+ * @returns Nothing.
61
+ */
62
+ remove(id: string, conditions?: {
63
+ property: keyof T;
64
+ value: unknown;
65
+ }[]): Promise<void>;
66
+ /**
67
+ * Find all the entities which match the conditions.
68
+ * @param conditions The conditions to match for the entities.
69
+ * @param sortProperties The optional sort order.
70
+ * @param properties The optional properties to return, defaults to all.
71
+ * @param cursor The cursor to request the next page of entities.
72
+ * @param pageSize The suggested number of entities to return in each chunk, in some scenarios can return a different amount.
73
+ * @returns All the entities for the storage matching the conditions,
74
+ * and a cursor which can be used to request more entities.
75
+ */
76
+ query(conditions?: EntityCondition<T>, sortProperties?: {
77
+ property: keyof T;
78
+ sortDirection: SortDirection;
79
+ }[], properties?: (keyof T)[], cursor?: string, pageSize?: number): Promise<{
80
+ entities: Partial<T>[];
81
+ cursor?: string;
82
+ }>;
83
+ /**
84
+ * Delete the container.
85
+ * @returns Nothing.
86
+ */
87
+ containerDelete(): Promise<void>;
88
+ }
@@ -0,0 +1,2 @@
1
+ export * from "./cosmosDbEntityStorageConnector";
2
+ export * from "./models/ICosmosDbEntityStorageConnectorConfig";