dynamo-bao 0.2.9 → 0.2.11

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.
@@ -1,13 +1,13 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- import {
3
+ const {
4
4
  DynamoDBClient,
5
5
  CreateTableCommand,
6
6
  ListTablesCommand,
7
- } from "../src/dynamodb-client.js";
8
- import readline from "readline";
9
- import fs from "fs";
10
- import path from "path";
7
+ } = require("../src/dynamodb-client.js");
8
+ const readline = require("readline");
9
+ const fs = require("fs");
10
+ const path = require("path");
11
11
 
12
12
  // Create DynamoDB client at the top level
13
13
  const client = new DynamoDBClient();
@@ -51,7 +51,7 @@ const prompt = (query) => {
51
51
  };
52
52
 
53
53
  async function writeConfigFile(tableName) {
54
- const region = client.region || process.env.AWS_REGION || 'us-east-1';
54
+ const region = client.region || process.env.AWS_REGION || "us-east-1";
55
55
  const configContent = `const path = require("path");
56
56
 
57
57
  const config = {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dynamo-bao",
3
- "version": "0.2.9",
3
+ "version": "0.2.11",
4
4
  "description": "Simple powerful data modeling primitives for DynamoDB in JavaScript.",
5
5
  "main": "src/index.js",
6
6
  "exports": {
package/src/model.js CHANGED
@@ -76,8 +76,8 @@ class BaoModel {
76
76
  * prevent data from being shared between tests/tests to run in parallel.
77
77
  * However, it should not be used outside of this context. For examples,
78
78
  * showing how to use this, see the tests.
79
- *
80
- * @deprecated Use TenantContext.setCurrentTenant() with the new multi-tenancy
79
+ *
80
+ * @deprecated Use TenantContext.setCurrentTenant() with the new multi-tenancy
81
81
  * system for both testing and production tenant isolation. See tutorial 08-multi-tenancy.
82
82
  * @param {string} testId - The ID of the test.
83
83
  */
@@ -90,7 +90,7 @@ class BaoModel {
90
90
  }
91
91
 
92
92
  static get manager() {
93
- const { TenantContext } = require('./tenant-context');
93
+ const { TenantContext } = require("./tenant-context");
94
94
  const tenantId = TenantContext.getCurrentTenant();
95
95
  return ModelManager.getInstance(tenantId || this._tenantId);
96
96
  }
@@ -192,25 +192,25 @@ class BaoModel {
192
192
  if (!this.iterable) {
193
193
  return {};
194
194
  }
195
-
195
+
196
196
  const tenantId = this.manager.getTenantId();
197
197
  let iterPk;
198
-
198
+
199
199
  if (this.iterationBuckets === 1) {
200
- iterPk = tenantId ?
201
- `[${tenantId}]#${this.modelPrefix}#iter` :
202
- `${this.modelPrefix}#iter`;
200
+ iterPk = tenantId
201
+ ? `[${tenantId}]#${this.modelPrefix}#iter`
202
+ : `${this.modelPrefix}#iter`;
203
203
  } else {
204
204
  const bucketNum = this._hashObjectId(objectId) % this.iterationBuckets;
205
- const bucket = bucketNum.toString().padStart(3, '0');
206
- iterPk = tenantId ?
207
- `[${tenantId}]#${this.modelPrefix}#iter#${bucket}` :
208
- `${this.modelPrefix}#iter#${bucket}`;
205
+ const bucket = bucketNum.toString().padStart(3, "0");
206
+ iterPk = tenantId
207
+ ? `[${tenantId}]#${this.modelPrefix}#iter#${bucket}`
208
+ : `${this.modelPrefix}#iter#${bucket}`;
209
209
  }
210
-
210
+
211
211
  return {
212
212
  [ITERATION_PK_FIELD]: iterPk,
213
- [ITERATION_SK_FIELD]: objectId
213
+ [ITERATION_SK_FIELD]: objectId,
214
214
  };
215
215
  }
216
216
 
@@ -218,7 +218,7 @@ class BaoModel {
218
218
  let hash = 0;
219
219
  for (let i = 0; i < objectId.length; i++) {
220
220
  const char = objectId.charCodeAt(i);
221
- hash = ((hash << 5) - hash) + char;
221
+ hash = (hash << 5) - hash + char;
222
222
  hash = hash & hash;
223
223
  }
224
224
  return Math.abs(hash);
@@ -228,92 +228,110 @@ class BaoModel {
228
228
  return this.iterable ? this.iterationBuckets : 1;
229
229
  }
230
230
 
231
- static async* iterateAll(options = {}) {
231
+ static async *iterateAll(options = {}) {
232
232
  if (!this.iterable) {
233
233
  throw new Error(`Model ${this.name} is not configured as iterable`);
234
234
  }
235
-
235
+
236
236
  const { batchSize = 100, filter = null, loaderContext = null } = options;
237
-
237
+
238
238
  if (this.iterationBuckets === 1) {
239
- yield* this._iterateSingleBucket(null, { batchSize, filter, loaderContext });
239
+ yield* this._iterateSingleBucket(null, {
240
+ batchSize,
241
+ filter,
242
+ loaderContext,
243
+ });
240
244
  } else {
241
245
  for (let bucket = 0; bucket < this.iterationBuckets; bucket++) {
242
- yield* this._iterateSingleBucket(bucket, { batchSize, filter, loaderContext });
246
+ yield* this._iterateSingleBucket(bucket, {
247
+ batchSize,
248
+ filter,
249
+ loaderContext,
250
+ });
243
251
  }
244
252
  }
245
253
  }
246
254
 
247
- static async* iterateBucket(bucketNum, options = {}) {
255
+ static async *iterateBucket(bucketNum, options = {}) {
248
256
  if (!this.iterable) {
249
257
  throw new Error(`Model ${this.name} is not configured as iterable`);
250
258
  }
251
-
259
+
252
260
  if (bucketNum < 0 || bucketNum >= this.iterationBuckets) {
253
- throw new Error(`Invalid bucket number ${bucketNum}. Must be 0-${this.iterationBuckets - 1}`);
261
+ throw new Error(
262
+ `Invalid bucket number ${bucketNum}. Must be 0-${this.iterationBuckets - 1}`,
263
+ );
254
264
  }
255
-
265
+
256
266
  yield* this._iterateSingleBucket(bucketNum, options);
257
267
  }
258
268
 
259
- static async* _iterateSingleBucket(bucketNum, options = {}) {
269
+ static async *_iterateSingleBucket(bucketNum, options = {}) {
260
270
  const { batchSize = 100, filter = null, loaderContext = null } = options;
261
271
  const tenantId = this.manager.getTenantId();
262
-
272
+
263
273
  let iterPk;
264
274
  if (this.iterationBuckets === 1) {
265
- iterPk = tenantId ?
266
- `[${tenantId}]#${this.modelPrefix}#iter` :
267
- `${this.modelPrefix}#iter`;
275
+ iterPk = tenantId
276
+ ? `[${tenantId}]#${this.modelPrefix}#iter`
277
+ : `${this.modelPrefix}#iter`;
268
278
  } else {
269
- const bucket = bucketNum.toString().padStart(3, '0');
270
- iterPk = tenantId ?
271
- `[${tenantId}]#${this.modelPrefix}#iter#${bucket}` :
272
- `${this.modelPrefix}#iter#${bucket}`;
279
+ const bucket = bucketNum.toString().padStart(3, "0");
280
+ iterPk = tenantId
281
+ ? `[${tenantId}]#${this.modelPrefix}#iter#${bucket}`
282
+ : `${this.modelPrefix}#iter#${bucket}`;
273
283
  }
274
-
284
+
275
285
  let lastEvaluatedKey = null;
276
-
286
+
277
287
  do {
278
288
  const { QueryCommand } = require("./dynamodb-client");
279
289
  const params = {
280
290
  TableName: this.table,
281
291
  IndexName: ITERATION_INDEX_NAME,
282
- KeyConditionExpression: '#pk = :pk',
283
- ExpressionAttributeNames: { '#pk': ITERATION_PK_FIELD },
284
- ExpressionAttributeValues: { ':pk': iterPk },
292
+ KeyConditionExpression: "#pk = :pk",
293
+ ExpressionAttributeNames: { "#pk": ITERATION_PK_FIELD },
294
+ ExpressionAttributeValues: { ":pk": iterPk },
285
295
  Limit: batchSize,
286
- ReturnConsumedCapacity: 'TOTAL'
296
+ ReturnConsumedCapacity: "TOTAL",
287
297
  };
288
-
298
+
289
299
  if (lastEvaluatedKey) {
290
300
  params.ExclusiveStartKey = lastEvaluatedKey;
291
301
  }
292
-
302
+
293
303
  if (filter) {
294
304
  const { FilterExpressionBuilder } = require("./filter-expression");
295
305
  const filterBuilder = new FilterExpressionBuilder();
296
306
  const filterExpression = filterBuilder.build(filter, this);
297
307
  if (filterExpression) {
298
308
  params.FilterExpression = filterExpression.FilterExpression;
299
- Object.assign(params.ExpressionAttributeNames, filterExpression.ExpressionAttributeNames);
300
- Object.assign(params.ExpressionAttributeValues, filterExpression.ExpressionAttributeValues);
309
+ Object.assign(
310
+ params.ExpressionAttributeNames,
311
+ filterExpression.ExpressionAttributeNames,
312
+ );
313
+ Object.assign(
314
+ params.ExpressionAttributeValues,
315
+ filterExpression.ExpressionAttributeValues,
316
+ );
301
317
  }
302
318
  }
303
-
319
+
304
320
  const response = await this.documentClient.send(new QueryCommand(params));
305
-
321
+
306
322
  if (response.Items && response.Items.length > 0) {
307
- const objectIds = response.Items.map(item => item[ITERATION_SK_FIELD]);
308
-
323
+ const objectIds = response.Items.map(
324
+ (item) => item[ITERATION_SK_FIELD],
325
+ );
326
+
309
327
  const { items } = await this.batchFind(objectIds, loaderContext);
310
328
  const batch = Object.values(items);
311
-
329
+
312
330
  if (batch.length > 0) {
313
331
  yield batch;
314
332
  }
315
333
  }
316
-
334
+
317
335
  lastEvaluatedKey = response.LastEvaluatedKey;
318
336
  } while (lastEvaluatedKey);
319
337
  }
@@ -392,46 +410,31 @@ class BaoModel {
392
410
  }
393
411
 
394
412
  const pkField = this._getField(this.primaryKey.pk);
395
- const skField = this._getField(this.primaryKey.sk);
413
+ const pkValue = pkField
414
+ ? pkField.toGsi(this._getPkValue(data))
415
+ : this._getPkValue(data);
396
416
 
397
- if (skField === undefined && this.primaryKey.sk !== "modelPrefix") {
398
- throw new ConfigurationError(
399
- `SK field is required for getPkSk call`,
400
- this.name,
401
- );
417
+ if (pkValue === undefined || pkValue === null) {
418
+ throw new ValidationError(`PK must be defined to get a PkSk`);
402
419
  }
403
420
 
404
- if (pkField === undefined && this.primaryKey.pk !== "modelPrefix") {
405
- throw new ConfigurationError(
406
- `PK field is required for getPkSk call`,
407
- this.name,
408
- );
409
- }
421
+ const key = { pk: pkValue };
410
422
 
411
- // If the field is set, use the GSI value, otherwise use the raw value
412
- const pkValue = pkField
413
- ? pkField.toGsi(this._getPkValue(data))
414
- : this._getPkValue(data);
415
- const skValue = skField
416
- ? skField.toGsi(this._getSkValue(data))
417
- : this._getSkValue(data);
418
-
419
- if (
420
- pkValue === undefined ||
421
- skValue === undefined ||
422
- pkValue === null ||
423
- skValue === null
424
- ) {
425
- throw new ValidationError(`PK and SK must be defined to get a PkSk`);
426
- }
427
-
428
- let key = {
429
- pk: pkValue,
430
- sk: skValue,
431
- };
423
+ if (this.primaryKey.sk) {
424
+ const skField = this._getField(this.primaryKey.sk);
425
+ const skValue = skField
426
+ ? skField.toGsi(this._getSkValue(data))
427
+ : this._getSkValue(data);
432
428
 
433
- logger.debug("_getPrimaryKeyValues", key);
429
+ if (skValue === undefined || skValue === null) {
430
+ throw new ValidationError(
431
+ `SK must be defined for a composite primary key`,
432
+ );
433
+ }
434
+ key.sk = skValue;
435
+ }
434
436
 
437
+ logger.debug("_getPrimaryKeyValues", key);
435
438
  return key;
436
439
  }
437
440
 
@@ -480,8 +483,17 @@ class BaoModel {
480
483
  }
481
484
 
482
485
  static _parsePrimaryId(primaryId) {
483
- if (!primaryId) {
484
- throw new DataFormatError("Primary ID is required to parse");
486
+ if (typeof primaryId === "object" && primaryId !== null) {
487
+ if (primaryId.pk !== undefined) {
488
+ return primaryId;
489
+ }
490
+ return this._getPrimaryKeyValues(primaryId);
491
+ }
492
+
493
+ if (typeof primaryId !== "string") {
494
+ throw new ValidationError(
495
+ `primaryId must be a string or an object. Got ${typeof primaryId}`,
496
+ );
485
497
  }
486
498
 
487
499
  if (primaryId.indexOf(GID_SEPARATOR) !== -1) {
@@ -492,9 +504,8 @@ class BaoModel {
492
504
  return { pk: this.modelPrefix, sk: primaryId };
493
505
  } else if (this.primaryKey.sk === "modelPrefix") {
494
506
  return { pk: primaryId, sk: this.modelPrefix };
495
- } else {
496
- throw new DataFormatError(`Invalid primary ID: ${primaryId}`);
497
507
  }
508
+ return { pk: primaryId };
498
509
  }
499
510
  }
500
511
 
@@ -739,7 +750,7 @@ class BaoModel {
739
750
  _sk: UNIQUE_CONSTRAINT_KEY,
740
751
  },
741
752
  ReturnConsumedCapacity: "TOTAL",
742
- })
753
+ }),
743
754
  );
744
755
 
745
756
  if (!result.Item) {
@@ -869,7 +880,8 @@ class BaoModel {
869
880
  // Factory functions to maintain compatibility
870
881
  const PrimaryKeyConfig = (pk, sk) => new PrimaryKeyConfigClass(pk, sk);
871
882
  const IndexConfig = (pk, sk, indexId) => new IndexConfigClass(pk, sk, indexId);
872
- const UniqueConstraintConfig = (field, constraintId) => new UniqueConstraintConfigClass(field, constraintId);
883
+ const UniqueConstraintConfig = (field, constraintId) =>
884
+ new UniqueConstraintConfigClass(field, constraintId);
873
885
 
874
886
  module.exports = {
875
887
  BaoModel,