@twin.org/entity-storage-connector-dynamodb 0.0.1-next.2

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,647 @@
1
+ 'use strict';
2
+
3
+ var clientDynamodb = require('@aws-sdk/client-dynamodb');
4
+ var libDynamodb = require('@aws-sdk/lib-dynamodb');
5
+ var utilDynamodb = require('@aws-sdk/util-dynamodb');
6
+ var core = require('@twin.org/core');
7
+ var entity = require('@twin.org/entity');
8
+ var loggingModels = require('@twin.org/logging-models');
9
+
10
+ // Copyright 2024 IOTA Stiftung.
11
+ // SPDX-License-Identifier: Apache-2.0.
12
+ /**
13
+ * Class for performing entity storage operations using Dynamo DB.
14
+ */
15
+ class DynamoDbEntityStorageConnector {
16
+ /**
17
+ * Limit the number of entities when finding.
18
+ * @internal
19
+ */
20
+ static _PAGE_SIZE = 40;
21
+ /**
22
+ * Partition id field name.
23
+ * @internal
24
+ */
25
+ static _PARTITION_ID_NAME = "partitionId";
26
+ /**
27
+ * Partition id field value.
28
+ * @internal
29
+ */
30
+ static _PARTITION_ID_VALUE = "1";
31
+ /**
32
+ * Runtime name for the class.
33
+ */
34
+ CLASS_NAME = "DynamoDbEntityStorageConnector";
35
+ /**
36
+ * The schema for the entity.
37
+ * @internal
38
+ */
39
+ _entitySchema;
40
+ /**
41
+ * The primary key.
42
+ * @internal
43
+ */
44
+ _primaryKey;
45
+ /**
46
+ * The configuration for the connector.
47
+ * @internal
48
+ */
49
+ _config;
50
+ /**
51
+ * Create a new instance of DynamoDbEntityStorageConnector.
52
+ * @param options The options for the connector.
53
+ * @param options.entitySchema The schema for the entity.
54
+ * @param options.loggingConnectorType The type of logging connector to use, defaults to no logging.
55
+ * @param options.config The configuration for the connector.
56
+ */
57
+ constructor(options) {
58
+ core.Guards.object(this.CLASS_NAME, "options", options);
59
+ core.Guards.stringValue(this.CLASS_NAME, "options.entitySchema", options.entitySchema);
60
+ core.Guards.object(this.CLASS_NAME, "options.config", options.config);
61
+ core.Guards.stringValue(this.CLASS_NAME, "options.config.accessKeyId", options.config.accessKeyId);
62
+ core.Guards.stringValue(this.CLASS_NAME, "options.config.secretAccessKey", options.config.secretAccessKey);
63
+ core.Guards.stringValue(this.CLASS_NAME, "options.config.region", options.config.region);
64
+ core.Guards.stringValue(this.CLASS_NAME, "options.config.tableName", options.config.tableName);
65
+ this._entitySchema = entity.EntitySchemaFactory.get(options.entitySchema);
66
+ this._primaryKey = entity.EntitySchemaHelper.getPrimaryKey(this._entitySchema);
67
+ this._config = options.config;
68
+ this._config.endpoint = core.Is.stringValue(this._config.endpoint)
69
+ ? this._config.endpoint
70
+ : undefined;
71
+ }
72
+ /**
73
+ * Bootstrap the component by creating and initializing any resources it needs.
74
+ * @param nodeLoggingConnectorType The node logging connector type, defaults to "node-logging".
75
+ * @returns True if the bootstrapping process was successful.
76
+ */
77
+ async bootstrap(nodeLoggingConnectorType) {
78
+ const nodeLogging = loggingModels.LoggingConnectorFactory.getIfExists(nodeLoggingConnectorType ?? "node-logging");
79
+ if (!(await this.tableExists(this._config.tableName))) {
80
+ await nodeLogging?.log({
81
+ level: "info",
82
+ source: this.CLASS_NAME,
83
+ ts: Date.now(),
84
+ message: "tableCreating",
85
+ data: {
86
+ tableName: this._config.tableName
87
+ }
88
+ });
89
+ try {
90
+ const dbConnection = this.createConnection();
91
+ const tableParams = {
92
+ AttributeDefinitions: [],
93
+ KeySchema: [],
94
+ ProvisionedThroughput: {
95
+ ReadCapacityUnits: 1,
96
+ WriteCapacityUnits: 1
97
+ },
98
+ TableName: this._config.tableName
99
+ };
100
+ // We always add a partition key to the table as a non optional hash key
101
+ // is always required when querying using sort parameters
102
+ tableParams.AttributeDefinitions?.push({
103
+ AttributeName: DynamoDbEntityStorageConnector._PARTITION_ID_NAME,
104
+ AttributeType: "S"
105
+ });
106
+ tableParams.KeySchema?.push({
107
+ AttributeName: DynamoDbEntityStorageConnector._PARTITION_ID_NAME,
108
+ KeyType: "HASH"
109
+ });
110
+ const gsi = [];
111
+ if (core.Is.arrayValue(this._entitySchema.properties)) {
112
+ for (const prop of this._entitySchema.properties) {
113
+ if (prop.isPrimary) {
114
+ tableParams.AttributeDefinitions?.push({
115
+ AttributeName: prop.property,
116
+ AttributeType: prop.type === "integer" || prop.type === "number" ? "N" : "S"
117
+ });
118
+ tableParams.KeySchema?.push({
119
+ AttributeName: prop.property,
120
+ KeyType: "RANGE"
121
+ });
122
+ }
123
+ else if (core.Is.stringValue(prop.sortDirection) || prop.isSecondary) {
124
+ // You can only query and sort items if you have a secondary index
125
+ // defined for the property
126
+ tableParams.AttributeDefinitions?.push({
127
+ AttributeName: prop.property,
128
+ AttributeType: prop.type === "integer" || prop.type === "number" ? "N" : "S"
129
+ });
130
+ gsi.push({
131
+ IndexName: `${prop.property}Index`,
132
+ KeySchema: [
133
+ {
134
+ AttributeName: DynamoDbEntityStorageConnector._PARTITION_ID_NAME,
135
+ KeyType: "HASH"
136
+ },
137
+ {
138
+ AttributeName: prop.property,
139
+ KeyType: "RANGE"
140
+ }
141
+ ],
142
+ Projection: {
143
+ ProjectionType: "ALL"
144
+ },
145
+ ProvisionedThroughput: {
146
+ ReadCapacityUnits: 1,
147
+ WriteCapacityUnits: 1
148
+ }
149
+ });
150
+ }
151
+ }
152
+ }
153
+ if (gsi.length > 0) {
154
+ tableParams.GlobalSecondaryIndexes = gsi;
155
+ }
156
+ await dbConnection.createTable(tableParams);
157
+ // Wait for table to exist
158
+ await clientDynamodb.waitUntilTableExists({
159
+ client: dbConnection,
160
+ maxWaitTime: 60000
161
+ }, {
162
+ TableName: this._config.tableName
163
+ });
164
+ await nodeLogging?.log({
165
+ level: "info",
166
+ source: this.CLASS_NAME,
167
+ ts: Date.now(),
168
+ message: "tableCreated",
169
+ data: {
170
+ tableName: this._config.tableName
171
+ }
172
+ });
173
+ }
174
+ catch (err) {
175
+ if (core.BaseError.isErrorCode(err, "ResourceInUseException")) {
176
+ await nodeLogging?.log({
177
+ level: "info",
178
+ source: this.CLASS_NAME,
179
+ ts: Date.now(),
180
+ message: "tableExists",
181
+ data: {
182
+ tableName: this._config.tableName
183
+ }
184
+ });
185
+ }
186
+ else {
187
+ const errors = err instanceof AggregateError ? err.errors : [err];
188
+ for (const error of errors) {
189
+ await nodeLogging?.log({
190
+ level: "error",
191
+ source: this.CLASS_NAME,
192
+ ts: Date.now(),
193
+ message: "tableCreateFailed",
194
+ error: core.BaseError.fromError(error),
195
+ data: {
196
+ tableName: this._config.tableName
197
+ }
198
+ });
199
+ }
200
+ }
201
+ return false;
202
+ }
203
+ }
204
+ else {
205
+ await nodeLogging?.log({
206
+ level: "info",
207
+ source: this.CLASS_NAME,
208
+ ts: Date.now(),
209
+ message: "tableExists",
210
+ data: {
211
+ tableName: this._config.tableName
212
+ }
213
+ });
214
+ }
215
+ return true;
216
+ }
217
+ /**
218
+ * Get an entity.
219
+ * @param id The id of the entity to get, or the index value if secondaryIndex is set.
220
+ * @param secondaryIndex Get the item using a secondary index.
221
+ * @returns The object if it can be found or undefined.
222
+ */
223
+ async get(id, secondaryIndex) {
224
+ core.Guards.stringValue(this.CLASS_NAME, "id", id);
225
+ try {
226
+ const docClient = this.createDocClient();
227
+ if (core.Is.undefined(secondaryIndex)) {
228
+ const getCommand = new libDynamodb.GetCommand({
229
+ TableName: this._config.tableName,
230
+ Key: {
231
+ [DynamoDbEntityStorageConnector._PARTITION_ID_NAME]: DynamoDbEntityStorageConnector._PARTITION_ID_VALUE,
232
+ [this._primaryKey.property]: id
233
+ }
234
+ });
235
+ const response = await docClient.send(getCommand);
236
+ delete response.Item?.[DynamoDbEntityStorageConnector._PARTITION_ID_NAME];
237
+ return response.Item;
238
+ }
239
+ const secIndex = secondaryIndex.toString();
240
+ const globalSecondaryIndex = `${secIndex}Index`;
241
+ const queryCommand = new clientDynamodb.QueryCommand({
242
+ TableName: this._config.tableName,
243
+ IndexName: globalSecondaryIndex,
244
+ KeyConditionExpression: `#${secIndex} = :id AND #${DynamoDbEntityStorageConnector._PARTITION_ID_NAME} = :${DynamoDbEntityStorageConnector._PARTITION_ID_NAME}`,
245
+ ExpressionAttributeNames: {
246
+ [`#${secIndex}`]: secIndex,
247
+ [`#${DynamoDbEntityStorageConnector._PARTITION_ID_NAME}`]: DynamoDbEntityStorageConnector._PARTITION_ID_NAME
248
+ },
249
+ ExpressionAttributeValues: {
250
+ [`:${DynamoDbEntityStorageConnector._PARTITION_ID_NAME}`]: {
251
+ S: DynamoDbEntityStorageConnector._PARTITION_ID_VALUE
252
+ },
253
+ ":id": { S: id }
254
+ }
255
+ });
256
+ const response = await docClient.send(queryCommand);
257
+ if (response.Items?.length === 1) {
258
+ return utilDynamodb.unmarshall(response.Items[0]);
259
+ }
260
+ }
261
+ catch (err) {
262
+ if (core.BaseError.isErrorCode(err, "ResourceNotFoundException")) {
263
+ throw new core.GeneralError(this.CLASS_NAME, "tableDoesNotExist", {
264
+ table: this._config.tableName
265
+ }, err);
266
+ }
267
+ throw new core.GeneralError(this.CLASS_NAME, "getFailed", {
268
+ id
269
+ }, err);
270
+ }
271
+ return undefined;
272
+ }
273
+ /**
274
+ * Set an entity.
275
+ * @param entity The entity to set.
276
+ * @returns The id of the entity.
277
+ */
278
+ async set(entity) {
279
+ core.Guards.object(this.CLASS_NAME, "entity", entity);
280
+ const id = entity[this._primaryKey.property];
281
+ try {
282
+ const docClient = this.createDocClient();
283
+ const putCommand = new libDynamodb.PutCommand({
284
+ TableName: this._config.tableName,
285
+ Item: {
286
+ [DynamoDbEntityStorageConnector._PARTITION_ID_NAME]: DynamoDbEntityStorageConnector._PARTITION_ID_VALUE,
287
+ ...entity
288
+ }
289
+ });
290
+ await docClient.send(putCommand);
291
+ }
292
+ catch (err) {
293
+ if (core.BaseError.isErrorCode(err, "ResourceNotFoundException")) {
294
+ throw new core.GeneralError(this.CLASS_NAME, "tableDoesNotExist", {
295
+ tableName: this._config.tableName
296
+ }, err);
297
+ }
298
+ throw new core.GeneralError(this.CLASS_NAME, "setFailed", {
299
+ id
300
+ }, err);
301
+ }
302
+ }
303
+ /**
304
+ * Remove the entity.
305
+ * @param id The id of the entity to remove.
306
+ * @returns Nothing.
307
+ */
308
+ async remove(id) {
309
+ core.Guards.stringValue(this.CLASS_NAME, "id", id);
310
+ try {
311
+ const docClient = this.createDocClient();
312
+ const deleteCommand = new libDynamodb.DeleteCommand({
313
+ TableName: this._config.tableName,
314
+ Key: {
315
+ [DynamoDbEntityStorageConnector._PARTITION_ID_NAME]: DynamoDbEntityStorageConnector._PARTITION_ID_VALUE,
316
+ [this._primaryKey.property]: id
317
+ }
318
+ });
319
+ await docClient.send(deleteCommand);
320
+ }
321
+ catch (err) {
322
+ if (core.BaseError.isErrorCode(err, "ResourceNotFoundException")) {
323
+ throw new core.GeneralError(this.CLASS_NAME, "tableDoesNotExist", {
324
+ table: this._config.tableName
325
+ }, err);
326
+ }
327
+ throw new core.GeneralError(this.CLASS_NAME, "removeFailed", {
328
+ id
329
+ }, err);
330
+ }
331
+ }
332
+ /**
333
+ * Find all the entities which match the conditions.
334
+ * @param conditions The conditions to match for the entities.
335
+ * @param sortProperties The optional sort order.
336
+ * @param properties The optional properties to return, defaults to all.
337
+ * @param cursor The cursor to request the next page of entities.
338
+ * @param pageSize The suggested number of entities to return in each chunk, in some scenarios can return a different amount.
339
+ * @returns All the entities for the storage matching the conditions,
340
+ * and a cursor which can be used to request more entities.
341
+ */
342
+ async query(conditions, sortProperties, properties, cursor, pageSize) {
343
+ const sql = "";
344
+ try {
345
+ const returnSize = pageSize ?? DynamoDbEntityStorageConnector._PAGE_SIZE;
346
+ let indexName;
347
+ // If we have a sortable property defined in the descriptor then we must use
348
+ // the secondary index for the query
349
+ if (core.Is.arrayValue(sortProperties)) {
350
+ if (sortProperties.length > 1) {
351
+ throw new core.GeneralError(this.CLASS_NAME, "sortSingle");
352
+ }
353
+ for (const sortProperty of sortProperties) {
354
+ const propertySchema = this._entitySchema.properties?.find(e => e.property === sortProperty.property);
355
+ if (core.Is.undefined(propertySchema) ||
356
+ (!propertySchema.isPrimary &&
357
+ !propertySchema.isSecondary &&
358
+ core.Is.empty(propertySchema.sortDirection))) {
359
+ throw new core.GeneralError(this.CLASS_NAME, "sortNotIndexed", {
360
+ property: sortProperty.property
361
+ });
362
+ }
363
+ indexName = propertySchema.isPrimary
364
+ ? undefined
365
+ : `${sortProperty.property}Index`;
366
+ }
367
+ }
368
+ const attributeNames = { "#partitionId": "partitionId" };
369
+ const attributeValues = {
370
+ [`:${DynamoDbEntityStorageConnector._PARTITION_ID_NAME}`]: {
371
+ S: DynamoDbEntityStorageConnector._PARTITION_ID_VALUE
372
+ }
373
+ };
374
+ const expressions = this.buildQueryParameters("", conditions, attributeNames, attributeValues);
375
+ let keyExpression = "#partitionId = :partitionId";
376
+ if (expressions.keyCondition.length > 0) {
377
+ keyExpression += ` AND ${expressions.keyCondition}`;
378
+ }
379
+ const query = new clientDynamodb.QueryCommand({
380
+ TableName: this._config.tableName,
381
+ IndexName: indexName,
382
+ KeyConditionExpression: keyExpression,
383
+ FilterExpression: core.Is.stringValue(expressions.filterCondition)
384
+ ? expressions.filterCondition
385
+ : undefined,
386
+ ExpressionAttributeNames: attributeNames,
387
+ ExpressionAttributeValues: attributeValues,
388
+ ProjectionExpression: properties?.map(p => p).join(", "),
389
+ Limit: returnSize,
390
+ ExclusiveStartKey: core.Is.empty(cursor)
391
+ ? undefined
392
+ : core.ObjectHelper.fromBytes(core.Converter.base64ToBytes(cursor))
393
+ });
394
+ const connection = this.createDocClient();
395
+ const results = await connection.send(query);
396
+ let entities = [];
397
+ if (core.Is.arrayValue(results.Items)) {
398
+ entities = results.Items.map(item => utilDynamodb.unmarshall(item));
399
+ }
400
+ return {
401
+ entities,
402
+ cursor: core.Is.empty(results.LastEvaluatedKey)
403
+ ? undefined
404
+ : core.Converter.bytesToBase64(core.ObjectHelper.toBytes(results.LastEvaluatedKey))
405
+ };
406
+ }
407
+ catch (err) {
408
+ if (core.BaseError.isErrorCode(err, "ResourceNotFoundException")) {
409
+ throw new core.GeneralError(this.CLASS_NAME, "tableDoesNotExist", {
410
+ table: this._config.tableName
411
+ }, err);
412
+ }
413
+ throw new core.GeneralError(this.CLASS_NAME, "queryFailed", {
414
+ sql
415
+ }, err);
416
+ }
417
+ }
418
+ /**
419
+ * Delete the table.
420
+ * @returns Nothing.
421
+ */
422
+ async tableDelete() {
423
+ try {
424
+ const dbConnection = this.createConnection();
425
+ await dbConnection.deleteTable({ TableName: this._config.tableName });
426
+ }
427
+ catch { }
428
+ }
429
+ /**
430
+ * Create an SQL condition clause.
431
+ * @param objectPath The path for the nested object.
432
+ * @param condition The conditions to create the query from.
433
+ * @param attributeNames The attribute names to use in the query.
434
+ * @param attributeValues The attribute values to use in the query.
435
+ * @returns The condition clause.
436
+ * @internal
437
+ */
438
+ buildQueryParameters(objectPath, condition, attributeNames, attributeValues) {
439
+ // If no conditions are defined then return empty string
440
+ if (core.Is.undefined(condition)) {
441
+ return {
442
+ keyCondition: "",
443
+ filterCondition: ""
444
+ };
445
+ }
446
+ if ("conditions" in condition) {
447
+ // It's a group of comparisons, so check the individual items and combine with the logical operator
448
+ const joinConditions = condition.conditions.map(c => this.buildQueryParameters(objectPath, c, attributeNames, attributeValues));
449
+ const logicalOperator = this.mapConditionalOperator(condition.logicalOperator);
450
+ const keyCondition = joinConditions.map(j => j.keyCondition).join(` ${logicalOperator} `);
451
+ const filterCondition = joinConditions
452
+ .map(j => j.filterCondition)
453
+ .join(` ${logicalOperator} `);
454
+ return {
455
+ keyCondition: core.Is.stringValue(keyCondition) ? ` (${keyCondition}) ` : "",
456
+ filterCondition: core.Is.stringValue(filterCondition) ? ` (${filterCondition}) ` : ""
457
+ };
458
+ }
459
+ const schemaProp = this._entitySchema.properties?.find(p => p.property === condition.property);
460
+ // It's a single value so just create the property comparison for the condition
461
+ const comparison = this.mapComparisonOperator(objectPath, condition, schemaProp?.type, attributeNames, attributeValues);
462
+ return {
463
+ keyCondition: schemaProp?.isPrimary ? comparison : "",
464
+ filterCondition: schemaProp?.isPrimary ? "" : comparison
465
+ };
466
+ }
467
+ /**
468
+ * Map the framework comparison operators to those in DynamoDB.
469
+ * @param objectPath The prefix to use for the condition.
470
+ * @param comparator The operator to map.
471
+ * @param type The type of the property.
472
+ * @param attributeNames The attribute names to use in the query.
473
+ * @param attributeValues The attribute values to use in the query.
474
+ * @returns The comparison expression.
475
+ * @throws GeneralError if the comparison operator is not supported.
476
+ * @internal
477
+ */
478
+ mapComparisonOperator(objectPath, comparator, type, attributeNames, attributeValues) {
479
+ let prop = objectPath;
480
+ if (prop.length > 0) {
481
+ prop += ".";
482
+ }
483
+ prop += comparator.property;
484
+ let attributeName = this.populateAttributeNames(prop, attributeNames);
485
+ let propName = `:${attributeName.replace(/\./g, "").replace(/#/g, "")}`;
486
+ if (core.Is.array(comparator.value)) {
487
+ const dbValues = comparator.value.map(v => this.propertyToDbValue(v, type));
488
+ const arrAttributeNames = [];
489
+ for (let i = 0; i < dbValues.length; i++) {
490
+ const arrAttributeName = `${propName}${i}`;
491
+ attributeValues[arrAttributeName] = dbValues[i];
492
+ arrAttributeNames.push(arrAttributeName);
493
+ }
494
+ propName = attributeName;
495
+ attributeName = `(${arrAttributeNames.join(", ")})`;
496
+ }
497
+ else {
498
+ attributeValues[propName] = this.propertyToDbValue(comparator.value, type);
499
+ }
500
+ if (comparator.comparison === entity.ComparisonOperator.Equals) {
501
+ return `${attributeName} = ${propName}`;
502
+ }
503
+ else if (comparator.comparison === entity.ComparisonOperator.NotEquals) {
504
+ return `${attributeName} <> ${propName}`;
505
+ }
506
+ else if (comparator.comparison === entity.ComparisonOperator.GreaterThan) {
507
+ return `${attributeName} > ${propName}`;
508
+ }
509
+ else if (comparator.comparison === entity.ComparisonOperator.LessThan) {
510
+ return `${attributeName} < ${propName}`;
511
+ }
512
+ else if (comparator.comparison === entity.ComparisonOperator.GreaterThanOrEqual) {
513
+ return `${attributeName} >= ${propName}`;
514
+ }
515
+ else if (comparator.comparison === entity.ComparisonOperator.LessThanOrEqual) {
516
+ return `${attributeName} <= ${propName}`;
517
+ }
518
+ else if (comparator.comparison === entity.ComparisonOperator.Includes) {
519
+ return `contains(${attributeName}, ${propName})`;
520
+ }
521
+ else if (comparator.comparison === entity.ComparisonOperator.NotIncludes) {
522
+ return `notContains(${attributeName}, ${propName})`;
523
+ }
524
+ else if (comparator.comparison === entity.ComparisonOperator.In) {
525
+ return `${propName} IN ${attributeName}`;
526
+ }
527
+ throw new core.GeneralError(this.CLASS_NAME, "comparisonNotSupported", {
528
+ comparison: comparator.comparison
529
+ });
530
+ }
531
+ /**
532
+ * Create a unique name for the attribute.
533
+ * @param name The name to create a unique name for.
534
+ * @param attributeNames The attribute names to use in the query.
535
+ * @returns The unique name.
536
+ * @internal
537
+ */
538
+ populateAttributeNames(name, attributeNames) {
539
+ const parts = name.split(".");
540
+ const attributeNameParts = [];
541
+ for (const part of parts) {
542
+ const hashPart = `#${part}`;
543
+ if (core.Is.empty(attributeNames[hashPart])) {
544
+ attributeNames[hashPart] = part;
545
+ }
546
+ attributeNameParts.push(hashPart);
547
+ }
548
+ return attributeNameParts.join(".");
549
+ }
550
+ /**
551
+ * Map the framework conditional operators to those in DynamoDB.
552
+ * @param operator The operator to map.
553
+ * @returns The conditional operator.
554
+ * @throws GeneralError if the conditional operator is not supported.
555
+ * @internal
556
+ */
557
+ mapConditionalOperator(operator) {
558
+ if ((operator ?? entity.LogicalOperator.And) === entity.LogicalOperator.And) {
559
+ return "AND";
560
+ }
561
+ else if (operator === entity.LogicalOperator.Or) {
562
+ return "OR";
563
+ }
564
+ throw new core.GeneralError(this.CLASS_NAME, "conditionalNotSupported", { operator });
565
+ }
566
+ /**
567
+ * Format a value to insert into DB.
568
+ * @param value The value to format.
569
+ * @param type The type for the property.
570
+ * @returns The value after conversion.
571
+ * @internal
572
+ */
573
+ propertyToDbValue(value, type) {
574
+ if (core.Is.object(value)) {
575
+ const map = {};
576
+ for (const key in value) {
577
+ map[key] = this.propertyToDbValue(value[key]);
578
+ }
579
+ return {
580
+ M: map
581
+ };
582
+ }
583
+ if (type === "integer" || type === "number") {
584
+ return { N: core.Coerce.string(value) ?? "" };
585
+ }
586
+ else if (type === "boolean") {
587
+ return { BOOL: core.Coerce.boolean(value) ?? false };
588
+ }
589
+ return { S: core.Coerce.string(value) ?? "" };
590
+ }
591
+ /**
592
+ * Create a doc client connection.
593
+ * @returns The dynamo db document client.
594
+ * @internal
595
+ */
596
+ createDocClient() {
597
+ return libDynamodb.DynamoDBDocumentClient.from(new clientDynamodb.DynamoDB({
598
+ apiVersion: "2012-10-08",
599
+ ...this.createConnectionConfig()
600
+ }), {
601
+ marshallOptions: {
602
+ removeUndefinedValues: true
603
+ }
604
+ });
605
+ }
606
+ /**
607
+ * Create a new DB connection.
608
+ * @returns The dynamo db connection.
609
+ * @internal
610
+ */
611
+ createConnection() {
612
+ return new clientDynamodb.DynamoDB(this.createConnectionConfig());
613
+ }
614
+ /**
615
+ * Create a new DB connection configuration.
616
+ * @returns The dynamo db connection configuration.
617
+ * @internal
618
+ */
619
+ createConnectionConfig() {
620
+ return {
621
+ credentials: {
622
+ accessKeyId: this._config.accessKeyId,
623
+ secretAccessKey: this._config.secretAccessKey
624
+ },
625
+ endpoint: this._config.endpoint,
626
+ region: this._config.region
627
+ };
628
+ }
629
+ /**
630
+ * Check if the table exists.
631
+ * @param tableName The table to check.
632
+ * @returns True if the table exists.
633
+ * @internal
634
+ */
635
+ async tableExists(tableName) {
636
+ try {
637
+ const dbConnection = this.createConnection();
638
+ await dbConnection.describeTable({ TableName: tableName });
639
+ return true;
640
+ }
641
+ catch {
642
+ return false;
643
+ }
644
+ }
645
+ }
646
+
647
+ exports.DynamoDbEntityStorageConnector = DynamoDbEntityStorageConnector;