dynamo-bao 0.8.0 → 0.8.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.
package/CHANGELOG.md ADDED
@@ -0,0 +1,535 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project are documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+ Each version heading links to the tag that was published to npm. Entries before
8
+ 0.4.0 were reconstructed from commit history after the fact and are brief.
9
+
10
+ ## [Unreleased]
11
+
12
+ ## [0.8.2] - 2026-10-27
13
+
14
+ ### Fixed
15
+
16
+ - A conditional `update()` or `delete()` of a row that did not exist was
17
+ reported as `ConditionalError` instead of `ItemNotFoundError` when another
18
+ writer created the row right after the failed write. Since 0.8.0 the
19
+ library read the row after a failed condition check to tell the two apart,
20
+ and that read described a later state. Guarded writes now send
21
+ `ReturnValuesOnConditionCheckFailure`, so the answer comes from the state
22
+ DynamoDB evaluated the condition against. The follow-up read is gone, which
23
+ makes the failure path one call cheaper. It remains only as a fallback for
24
+ injected clients that do not surface the returned item.
25
+
26
+ ### Changed
27
+
28
+ - The bundled DynamoDB client attaches `Item` to a
29
+ `ConditionalCheckFailedException` when the request asked for
30
+ `ReturnValuesOnConditionCheckFailure` (`null` when the row did not exist).
31
+
32
+ ## [0.8.1] - 2026-10-27
33
+
34
+ ### Fixed
35
+
36
+ - `update()` on a model with a GSI that uses `modelPrefix` as one half of its
37
+ key threw "Update includes GSI partition key modelPrefix but is missing sort
38
+ key" unless the update also carried the other half. 0.8.0 stopped
39
+ pre-reading the row on plain updates, and the partial-key guard
40
+ then treated the constant half as a newly provided key. The index is now
41
+ skipped when the field half is not in the update, since its key cannot
42
+ change. Plain field and counter updates on such models stay at one
43
+ `UpdateItem`. Models with a `modelPrefix` primary key behave the same in
44
+ `legacy` and `tenant-scoped` modes; `migrating` mode still reads first
45
+ because it writes in place.
46
+
47
+ ## [0.8.0] - 2026-10-27
48
+
49
+ Cuts DynamoDB round trips and per-item CPU in the core read and write paths.
50
+ No key formats, index keys or constraint rows change.
51
+
52
+ ### Changed
53
+
54
+ - `find()` in a batch context now flushes on the next tick (`setImmediate`)
55
+ instead of waiting for a 5 ms timer. Finds issued in the same tick still
56
+ share one `BatchGetItem`. Pass `batchDelay: <ms>` to keep a timer window, or
57
+ `batchDelay: 0` to send a single `GetItem` immediately.
58
+ - `update()` no longer reads the item before writing unless the update needs
59
+ the current row: a touched GSI key, string set, unique constraint, searchable
60
+ field, `forceReindex`, or a model in `migrating` key mode. Otherwise it sends
61
+ one conditional `UpdateItem` guarded by `attribute_exists`, and a missing row
62
+ raises `ItemNotFoundError` as before.
63
+ - `delete()` on a model without unique constraints is a single conditional
64
+ `DeleteItem`. Models with unique constraints still read first so the
65
+ constraint rows can be removed in the same transaction.
66
+ - Updates of unique-constraint fields that use plain `SET` no longer read the
67
+ item back after the transaction. Only atomic `ADD`/`DELETE` updates do.
68
+ - `batchFind()` sends its 100-key chunks concurrently (up to 5 in flight) and
69
+ returns the cached instance for ids already in the request cache.
70
+ - `iterateAll()` prefetches the next page while the current page is being
71
+ hydrated, and accepts `concurrency` to walk several iteration buckets in
72
+ parallel.
73
+ - Items loaded from DynamoDB skip constructor work they do not need: no system
74
+ field copy, no initial values. Field getters and setters are defined once on
75
+ the model prototype instead of on every instance.
76
+ - Debug logging no longer builds its arguments unless debug output is enabled.
77
+ Several misdirected `logger.log` calls in the query and field code were fixed
78
+ or removed. "Models initialized" is logged at debug level instead of info.
79
+ - Expected condition failures (`ConditionalCheckFailedException`, cancelled
80
+ transactions) are logged at debug level. Only unexpected save errors are
81
+ logged at error level, once.
82
+
83
+ ### Fixed
84
+
85
+ - `find()` with an object primary id in a batch context could resolve to
86
+ `ObjectNotFound`. Object and string forms of the same id now share one batch
87
+ entry.
88
+ - `create()` with a `$and` condition produced a "redundant parentheses"
89
+ `ValidationException`.
90
+
91
+ ### Removed
92
+
93
+ - The `DEFAULT_BATCH_DELAY_MS` export. The default is no longer a delay.
94
+
95
+ ### Internal
96
+
97
+ - A batch's `timer` property is now a cancel function rather than a timeout
98
+ handle. Tests that cleared it with `clearTimeout` should call it instead.
99
+ - `Logger` gained `isLevelEnabled(level)` and `isDebugEnabled()`.
100
+
101
+ ## [0.7.3] - 2026-10-27
102
+
103
+ ### Changed
104
+
105
+ - Raised the `js-yaml` minimum to `^4.3.2`, which fixes four quadratic-CPU
106
+ advisories (GHSA-h67p-54hq-rp68, GHSA-52cp-r559-cp3m, GHSA-5p4m-2wfm-xmqj,
107
+ GHSA-2883-xcg3-v3hh). It is the only runtime dependency that was flagged and
108
+ is used only by `bao-codegen`. (#16)
109
+ - Applied `npm audit fix` to dev-only transitive dependencies. (#16)
110
+ - Switched the generated docs from `clean-jsdoc-theme` to `docdash` with a
111
+ custom stylesheet, dark mode and no build-date footer. Source pages on
112
+ GitHub Pages lost their `src_` prefix and test helpers no longer appear
113
+ under "Global". (#17)
114
+
115
+ ## [0.7.2] - 2026-10-27
116
+
117
+ ### Fixed
118
+
119
+ - `update()` with an object primary id on an iterable model failed with
120
+ "Type mismatch for Index Key" on `_iter_sk`. The id is now converted to its
121
+ string form first, which also stops an object id from being stored as the
122
+ owner on a unique-constraint row. (#15)
123
+ - Relative counter values such as `"+3"` on a counter used in an index key
124
+ were written into the key as the literal string. Creates now write the
125
+ number. Updates write loaded value plus delta, guarded by a condition on the
126
+ loaded value; a concurrent change raises `ConditionalError`. Counters in no
127
+ index keep the atomic `ADD`. (#15)
128
+ - `npm publish` warned about every `bin` entry. The leading `./` was removed
129
+ and the repository URL normalised. (#15)
130
+
131
+ ## [0.7.1] - 2026-10-27
132
+
133
+ ### Changed
134
+
135
+ - `create()` on a model with unique constraints takes one DynamoDB call
136
+ instead of three. The uniqueness read before the transaction is gone (the
137
+ constraint `Put` already carries `attribute_not_exists`) and the new item is
138
+ built in memory instead of read back. A duplicate create now costs the
139
+ cancelled transaction plus one read to name the field. (#14)
140
+ - `find(id, { bypassCache: true })` always issues its own `GetItem` and never
141
+ joins a batch. (#14)
142
+ - Capacity reported on update results no longer includes earlier operations'
143
+ capacity, so `getBatchContextCapacity()` equals what DynamoDB returned. (#14)
144
+ - Explicit `keyMigration.modelPrefixPkMode` is required to enable key
145
+ migration.
146
+
147
+ ### Fixed
148
+
149
+ - Request-scoped loader cache: creates and updates store the written row and
150
+ deletes remove it, so a `find` later in the same request no longer returns
151
+ stale data. An update that changed a unique field used to return the
152
+ pre-update row. (#14)
153
+ - Cache keys now include the model and tenant. `ModelB.find(id)` could return
154
+ a `ModelA` row with the same id, and after a tenant switch inside one request
155
+ the second tenant could get the first tenant's cached row. (#14)
156
+ - Batches are grouped per tenant. Parallel finds from two tenants in one batch
157
+ window were resolved with the first caller's tenant keys. (#14)
158
+ - A `{ pk, sk }` object id and its string form share one cache entry. (#14)
159
+ - Models with a field named `pk` can be created. (#14)
160
+ - `save({ condition })` on a new instance combines the caller's condition with
161
+ the does-not-exist guard instead of replacing it. (#14)
162
+ - `DateTimeField` accepts `null` to clear the field. (#14)
163
+
164
+ ## [0.7.0] - 2026-06-04
165
+
166
+ ### Added
167
+
168
+ - Opt-in tenant scoping for models whose primary key partition is the model
169
+ prefix, with a safe expand, migrate, contract rollout controlled by
170
+ `keyMigration.modelPrefixPkMode` (`legacy`, `migrating`, `tenant-scoped`).
171
+ The default `legacy` mode is byte-identical to earlier behaviour. In
172
+ `migrating` mode reads fall back to both historical key shapes, updates
173
+ write in place guarded by `attribute_exists`, and legacy-fallback reads
174
+ report their consumed capacity. (#13)
175
+ - `PutCommand` on the DynamoDB client, used by backfill relocation. (#13)
176
+
177
+ ### Changed
178
+
179
+ - The batch resolver sums every `ConsumedCapacity` entry, fixing an undercount
180
+ for multi-page batch reads over 100 items. (#13)
181
+ - Search iteration index capacity is accounted for.
182
+
183
+ ## [0.6.1] - 2026-05-27
184
+
185
+ ### Fixed
186
+
187
+ - Tenant key formatting for models with a model-prefix partition key. This
188
+ change was effectively reverted by the migration path in 0.7.0: it scoped
189
+ the key atomically with no migration, which stranded existing rows for
190
+ by-id reads. Upgrade to 0.7.0 or later rather than to this version.
191
+
192
+ ### Changed
193
+
194
+ - Tightened the `formidable` dev dependency range.
195
+
196
+ ## [0.6.0] - 2026-05-08
197
+
198
+ ### Added
199
+
200
+ - `_searchText` is a first-class filter target. Use `$contains`,
201
+ `$beginsWith`, `$eq`, `$ne` or `$exists` on it in `query`, `queryByIndex`,
202
+ `iterateAll({ filter })` and condition expressions; the value is normalised
203
+ with the model's `searchConfig`. (#11)
204
+ - `SECURITY.md` documenting an audit finding in the docs theme's `showdown`
205
+ dependency (not exploitable in this project's threat model). (#11)
206
+
207
+ ### Fixed
208
+
209
+ - `minTermLength` applied only at write time. Short query terms were sent to
210
+ DynamoDB verbatim and silently matched nothing. They are now dropped from
211
+ the predicate, and an error is raised if every term is dropped. (#11)
212
+
213
+ ## [0.5.0] - 2026-05-06
214
+
215
+ ### Added
216
+
217
+ - Searchable iterable models. A declarative `searchable: { fields: [...] }`
218
+ block in the model YAML populates a normalised `_searchText` attribute on
219
+ every save, with `caseSensitive`, `minTermLength` and `dedupe` options.
220
+ (#10)
221
+ - `Model.searchAll(terms, options)` and
222
+ `Model.searchBucket(bucketNum, terms, options)` async generators, with
223
+ `$and` (default) or `$or` term matching, and
224
+ `Model.tokenizeSearchQuery(query)` that respects quoted phrases. (#10)
225
+ - A new `iter_search_index` GSI replaces the legacy `iter_index` for
226
+ iteration and search. `bao-update-table` adds it to existing tables; the
227
+ legacy index is left in place for manual removal. The
228
+ `db.iterationIndexName` config override keeps iteration on the legacy index
229
+ during a transition. (#10)
230
+ - `bao-rebuild-search-text <ModelName>` CLI for backfilling `_searchText`.
231
+ (#10)
232
+ - Codegen validates `searchable.fields` against existing string fields. (#10)
233
+
234
+ ## [0.4.2] - 2026-03-31
235
+
236
+ ### Fixed
237
+
238
+ - Generated code imports `dynamo-bao` by bare package specifier instead of a
239
+ relative path.
240
+
241
+ ### Changed
242
+
243
+ - `bao-create-table` is documented.
244
+
245
+ ## [0.4.1] - 2026-03-31
246
+
247
+ ### Added
248
+
249
+ - `bao-create-table` command. The bin scripts were cleaned up alongside it.
250
+
251
+ ### Fixed
252
+
253
+ - Flaky pagination tests caused by GSI eventual consistency.
254
+ - A `form-data` vulnerability in a dev dependency.
255
+
256
+ ## [0.4.0] - 2026-02-16
257
+
258
+ ### Added
259
+
260
+ - Support for five GSIs (`gsi4` and `gsi5`), previously three. The table
261
+ creation script provisions them. (#8)
262
+ - `bao-update-table` command to add missing GSIs and enable TTL on an existing
263
+ table. (#8)
264
+
265
+ ### Changed
266
+
267
+ - Partial updates to one half of a GSI key pair backfill the other half from
268
+ the stored item so the index does not go stale. If the counterpart was never
269
+ stored, the update throws with guidance to include both fields or use
270
+ `forceReindex`. (#8)
271
+ - `forceReindex` recomputes every GSI key from the current item and preserves
272
+ the new values. (#8)
273
+ - Table creation enables TTL via `UpdateTimeToLive` after the table is active
274
+ instead of inline. (#8)
275
+
276
+ ## [0.3.9] - 2026-01-25
277
+
278
+ ### Added
279
+
280
+ - `getBatchContextCapacity()` returns the total read and write capacity
281
+ consumed by every operation inside the current `runWithBatchContext` scope,
282
+ for per-request usage metering. (#7)
283
+
284
+ ## [0.3.8] - 2025-12-17
285
+
286
+ ### Fixed
287
+
288
+ - A `const` declaration error introduced in 0.3.7.
289
+
290
+ ## [0.3.7] - 2025-12-17
291
+
292
+ ### Fixed
293
+
294
+ - Unique constraints on a field whose value is `null`.
295
+
296
+ ## [0.3.6] - 2025-12-17
297
+
298
+ ### Changed
299
+
300
+ - More robust retries after a transactional write.
301
+
302
+ ### Removed
303
+
304
+ - The `serverless` dependency.
305
+
306
+ ## [0.3.5] - 2025-10-22
307
+
308
+ ### Added
309
+
310
+ - `forceReindex` option on updates.
311
+
312
+ ## [0.3.4] - 2025-07-26
313
+
314
+ ### Changed
315
+
316
+ - The log level is read from `DYNAMO_BAO_LOG_LEVEL` rather than `LOG_LEVEL`.
317
+
318
+ ## [0.3.3] - 2025-07-24
319
+
320
+ ### Fixed
321
+
322
+ - A logging issue.
323
+
324
+ ## [0.3.2] - 2025-07-16
325
+
326
+ ### Changed
327
+
328
+ - Better syntax for string sets.
329
+
330
+ ## [0.3.1] - 2025-07-15
331
+
332
+ ### Added
333
+
334
+ - `StringSetField`.
335
+
336
+ ### Fixed
337
+
338
+ - A pagination test.
339
+
340
+ ## [0.3.0] - 2025-06-26
341
+
342
+ ### Added
343
+
344
+ - `runWithBatchContext()` and request-scoped batching and caching of finds.
345
+
346
+ ## [0.2.12] - 2025-06-25
347
+
348
+ ### Added
349
+
350
+ - Isolated-context batch loading.
351
+
352
+ ## [0.2.11] - 2025-06-23
353
+
354
+ ### Fixed
355
+
356
+ - An import issue in the create-table script.
357
+
358
+ ## [0.2.10] - 2025-06-17
359
+
360
+ ### Added
361
+
362
+ - Composite keys on `delete`.
363
+
364
+ ## [0.2.9] - 2025-06-17
365
+
366
+ ### Added
367
+
368
+ - Basic ESM support.
369
+
370
+ ## [0.2.8] - 2025-06-16
371
+
372
+ ### Added
373
+
374
+ - Cloudflare Workers support.
375
+
376
+ ## [0.2.7] - 2025-06-16
377
+
378
+ ### Added
379
+
380
+ - CommonJS config files.
381
+
382
+ ## [0.2.6] - 2025-06-16
383
+
384
+ ### Fixed
385
+
386
+ - Codegen fixes.
387
+
388
+ ## [0.2.5] - 2025-06-16
389
+
390
+ ### Changed
391
+
392
+ - Model discovery no longer uses `fs.readdirSync`.
393
+
394
+ ## [0.2.4] - 2025-06-16
395
+
396
+ ### Fixed
397
+
398
+ - An error when the custom field directory does not exist.
399
+ - Added a multi-tenant test for indexes.
400
+
401
+ ## [0.2.3] - 2025-06-12
402
+
403
+ ### Changed
404
+
405
+ - Documentation for iteration.
406
+
407
+ ## [0.2.2] - 2025-06-12
408
+
409
+ ### Added
410
+
411
+ - Multi-tenancy.
412
+ - Basic iteration over all items of a model.
413
+
414
+ ## [0.2.1] - 2025-06-10
415
+
416
+ ### Fixed
417
+
418
+ - `chokidar` restored as a dependency for the watcher.
419
+
420
+ ## [0.2.0] - 2025-06-10
421
+
422
+ ### Changed
423
+
424
+ - The DynamoDB client is a custom implementation on `aws4fetch` instead of
425
+ the AWS SDK. Dependencies were cleaned up accordingly.
426
+
427
+ ## [0.1.8] - 2025-06-03
428
+
429
+ ### Changed
430
+
431
+ - Version bump only.
432
+
433
+ ## [0.1.7] - 2025-06-03
434
+
435
+ ### Fixed
436
+
437
+ - `exists()`.
438
+
439
+ ### Changed
440
+
441
+ - Library updates and more error types.
442
+
443
+ ## [0.1.6] - 2025-01-30
444
+
445
+ ### Added
446
+
447
+ - Conditional saves and deletes, including exists / does-not-exist
448
+ conditions.
449
+
450
+ ### Changed
451
+
452
+ - Optimised delete. Old save constraint options removed.
453
+
454
+ ## [0.1.5] - 2025-01-29
455
+
456
+ ### Fixed
457
+
458
+ - Primary key naming.
459
+
460
+ ## [0.1.4] - 2025-01-29
461
+
462
+ ### Changed
463
+
464
+ - Config standardisation and codegen updates.
465
+
466
+ ## [0.1.3] - 2025-01-10
467
+
468
+ ### Added
469
+
470
+ - Basic tutorials and the LICENSE file.
471
+
472
+ ## [0.1.2] - 2025-01-08
473
+
474
+ ### Changed
475
+
476
+ - Simplified config setup.
477
+
478
+ ## [0.1.1] - 2024-12-20
479
+
480
+ ### Changed
481
+
482
+ - Documentation updates.
483
+
484
+ ## [0.1.0] - 2024-12-20
485
+
486
+ Initial release: single-table models with fields, GSIs, unique constraints,
487
+ related fields, counters, TTL, filters, pagination, batch loading, hooks,
488
+ YAML codegen and a table creation tool.
489
+
490
+ [Unreleased]: https://github.com/aag1024/dynamo-bao/compare/v0.8.2...HEAD
491
+ [0.8.2]: https://github.com/aag1024/dynamo-bao/compare/v0.8.1...v0.8.2
492
+ [0.8.1]: https://github.com/aag1024/dynamo-bao/compare/v0.8.0...v0.8.1
493
+ [0.8.0]: https://github.com/aag1024/dynamo-bao/compare/v0.7.3...v0.8.0
494
+ [0.7.3]: https://github.com/aag1024/dynamo-bao/compare/v0.7.2...v0.7.3
495
+ [0.7.2]: https://github.com/aag1024/dynamo-bao/compare/v0.7.1...v0.7.2
496
+ [0.7.1]: https://github.com/aag1024/dynamo-bao/compare/v0.7.0...v0.7.1
497
+ [0.7.0]: https://github.com/aag1024/dynamo-bao/compare/v0.6.1...v0.7.0
498
+ [0.6.1]: https://github.com/aag1024/dynamo-bao/compare/v0.6.0...v0.6.1
499
+ [0.6.0]: https://github.com/aag1024/dynamo-bao/compare/v0.5.0...v0.6.0
500
+ [0.5.0]: https://github.com/aag1024/dynamo-bao/compare/v0.4.2...v0.5.0
501
+ [0.4.2]: https://github.com/aag1024/dynamo-bao/compare/v0.4.1...v0.4.2
502
+ [0.4.1]: https://github.com/aag1024/dynamo-bao/compare/v0.4.0...v0.4.1
503
+ [0.4.0]: https://github.com/aag1024/dynamo-bao/compare/v0.3.9...v0.4.0
504
+ [0.3.9]: https://github.com/aag1024/dynamo-bao/compare/v0.3.8...v0.3.9
505
+ [0.3.8]: https://github.com/aag1024/dynamo-bao/compare/v0.3.7...v0.3.8
506
+ [0.3.7]: https://github.com/aag1024/dynamo-bao/compare/v0.3.6...v0.3.7
507
+ [0.3.6]: https://github.com/aag1024/dynamo-bao/compare/v0.3.5...v0.3.6
508
+ [0.3.5]: https://github.com/aag1024/dynamo-bao/compare/v0.3.4...v0.3.5
509
+ [0.3.4]: https://github.com/aag1024/dynamo-bao/compare/v0.3.3...v0.3.4
510
+ [0.3.3]: https://github.com/aag1024/dynamo-bao/compare/v0.3.2...v0.3.3
511
+ [0.3.2]: https://github.com/aag1024/dynamo-bao/compare/v0.3.1...v0.3.2
512
+ [0.3.1]: https://github.com/aag1024/dynamo-bao/compare/v0.3.0...v0.3.1
513
+ [0.3.0]: https://github.com/aag1024/dynamo-bao/compare/v0.2.12...v0.3.0
514
+ [0.2.12]: https://github.com/aag1024/dynamo-bao/compare/v0.2.11...v0.2.12
515
+ [0.2.11]: https://github.com/aag1024/dynamo-bao/compare/v0.2.10...v0.2.11
516
+ [0.2.10]: https://github.com/aag1024/dynamo-bao/compare/v0.2.9...v0.2.10
517
+ [0.2.9]: https://github.com/aag1024/dynamo-bao/compare/v0.2.8...v0.2.9
518
+ [0.2.8]: https://github.com/aag1024/dynamo-bao/compare/v0.2.7...v0.2.8
519
+ [0.2.7]: https://github.com/aag1024/dynamo-bao/compare/v0.2.6...v0.2.7
520
+ [0.2.6]: https://github.com/aag1024/dynamo-bao/compare/v0.2.5...v0.2.6
521
+ [0.2.5]: https://github.com/aag1024/dynamo-bao/compare/v0.2.4...v0.2.5
522
+ [0.2.4]: https://github.com/aag1024/dynamo-bao/compare/v0.2.3...v0.2.4
523
+ [0.2.3]: https://github.com/aag1024/dynamo-bao/compare/v0.2.2...v0.2.3
524
+ [0.2.2]: https://github.com/aag1024/dynamo-bao/compare/v0.2.1...v0.2.2
525
+ [0.2.1]: https://github.com/aag1024/dynamo-bao/compare/v0.2.0...v0.2.1
526
+ [0.2.0]: https://github.com/aag1024/dynamo-bao/compare/v0.1.8...v0.2.0
527
+ [0.1.8]: https://github.com/aag1024/dynamo-bao/compare/v0.1.7...v0.1.8
528
+ [0.1.7]: https://github.com/aag1024/dynamo-bao/compare/v0.1.6...v0.1.7
529
+ [0.1.6]: https://github.com/aag1024/dynamo-bao/compare/v0.1.5...v0.1.6
530
+ [0.1.5]: https://github.com/aag1024/dynamo-bao/compare/v0.1.4...v0.1.5
531
+ [0.1.4]: https://github.com/aag1024/dynamo-bao/compare/v0.1.3...v0.1.4
532
+ [0.1.3]: https://github.com/aag1024/dynamo-bao/compare/v0.1.2...v0.1.3
533
+ [0.1.2]: https://github.com/aag1024/dynamo-bao/compare/v0.1.1...v0.1.2
534
+ [0.1.1]: https://github.com/aag1024/dynamo-bao/compare/v0.1.0...v0.1.1
535
+ [0.1.0]: https://github.com/aag1024/dynamo-bao/releases/tag/v0.1.0
package/README.md CHANGED
@@ -8,6 +8,8 @@ DynamoBao is a simple lightweight library for building DynamoDB models in JavaSc
8
8
  DynamoDB for years and generally love it, but find getting started difficult and repetitive.
9
9
  DynamoBao is the tool I wish I had when I started.
10
10
 
11
+ Release notes are in [CHANGELOG.md](https://github.com/aag1024/dynamo-bao/blob/main/CHANGELOG.md).
12
+
11
13
  ## Principles
12
14
 
13
15
  - Expose just enough of Dynamo's features to make it easy to model many common types of data.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dynamo-bao",
3
- "version": "0.8.0",
3
+ "version": "0.8.2",
4
4
  "description": "Simple powerful data modeling primitives for DynamoDB in JavaScript.",
5
5
  "main": "src/index.js",
6
6
  "exports": {
@@ -18,7 +18,8 @@
18
18
  "files": [
19
19
  "bin/",
20
20
  "src/",
21
- "README.md"
21
+ "README.md",
22
+ "CHANGELOG.md"
22
23
  ],
23
24
  "keywords": [
24
25
  "dynamodb",
@@ -240,7 +240,16 @@ class DynamoDBClient {
240
240
  if (errorName === 'TransactionCanceledException' && errorBody.CancellationReasons) {
241
241
  error.CancellationReasons = errorBody.CancellationReasons;
242
242
  }
243
-
243
+
244
+ // With ReturnValuesOnConditionCheckFailure, a failed condition check
245
+ // carries the item as it was when the condition was evaluated, or no
246
+ // Item at all when the row did not exist. Surface that as error.Item
247
+ // (null for "did not exist") so callers can tell the two apart
248
+ // without a follow-up read.
249
+ if (command.input.ReturnValuesOnConditionCheckFailure) {
250
+ error.Item = errorBody.Item ? unmarshallItem(errorBody.Item) : null;
251
+ }
252
+
244
253
  throw error;
245
254
  }
246
255
 
@@ -522,6 +531,14 @@ class DynamoDBDocumentClient {
522
531
  }
523
532
 
524
533
  // Marshall JavaScript values to DynamoDB JSON
534
+ function unmarshallItem(item) {
535
+ const out = {};
536
+ Object.keys(item).forEach(key => {
537
+ out[key] = unmarshall(item[key]);
538
+ });
539
+ return out;
540
+ }
541
+
525
542
  function marshall(obj) {
526
543
  if (obj === null) return { NULL: true };
527
544
  if (obj === undefined) return { NULL: true };
@@ -294,7 +294,7 @@ const MutationMethods = {
294
294
  ) {
295
295
  if (
296
296
  !item &&
297
- !(await this._existsAfterGuardFailure(primaryId, options))
297
+ !(await this._existsAfterGuardFailure(primaryId, options, error))
298
298
  ) {
299
299
  throw new ItemNotFoundError("Item not found", primaryId);
300
300
  }
@@ -336,18 +336,26 @@ const MutationMethods = {
336
336
  params.ConditionExpression,
337
337
  "attribute_exists(#__existsPk)",
338
338
  );
339
+ // Ask DynamoDB to return the row the condition was evaluated against,
340
+ // so a failed check can be attributed without a follow-up read (see
341
+ // _existsAfterGuardFailure).
342
+ params.ReturnValuesOnConditionCheckFailure = "ALL_OLD";
339
343
  },
340
344
 
341
345
  /**
342
346
  * After a guarded write fails its condition check, decide whether the row
343
- * exists. With no caller condition the guard is the only thing that could
344
- * have failed, so no read is needed; otherwise one GetItem (cache
345
- * bypassed) tells a missing row apart from an unmet condition. Only the
346
- * failure path pays for this read.
347
+ * existed when the condition was evaluated. With no caller condition the
348
+ * guard is the only thing that could have failed, so the row was missing.
349
+ * Otherwise the error's `Item` (from ReturnValuesOnConditionCheckFailure)
350
+ * is exact: present means the caller's condition failed, null means the
351
+ * row did not exist. A read after the fact is only a fallback for clients
352
+ * that do not surface `Item`; it can be wrong when another writer creates
353
+ * the row between the failed write and the read.
347
354
  * @private
348
355
  */
349
- async _existsAfterGuardFailure(primaryId, options) {
356
+ async _existsAfterGuardFailure(primaryId, options, error) {
350
357
  if (!options.condition) return false;
358
+ if (error && error.Item !== undefined) return error.Item !== null;
351
359
  const existing = await this.find(primaryId, {
352
360
  batchDelay: 0,
353
361
  bypassCache: true,
@@ -631,20 +639,22 @@ const MutationMethods = {
631
639
  Object.entries(this.indexes).forEach(([, index]) => {
632
640
  const pkField = index.pk;
633
641
  const skField = index.sk;
634
- const pkInUpdate =
635
- pkField === "modelPrefix" ||
636
- indexComputationData[pkField] !== undefined;
637
- const skInUpdate =
638
- skField === "modelPrefix" ||
639
- indexComputationData[skField] !== undefined;
640
-
641
- if (pkInUpdate && !skInUpdate && skField !== "modelPrefix") {
642
+ // Nothing to backfill when one half is the modelPrefix constant:
643
+ // if the field half is in the update both halves are known, and
644
+ // if it is not, the index key does not change.
645
+ if (pkField === "modelPrefix" || skField === "modelPrefix") {
646
+ return;
647
+ }
648
+ const pkInUpdate = indexComputationData[pkField] !== undefined;
649
+ const skInUpdate = indexComputationData[skField] !== undefined;
650
+
651
+ if (pkInUpdate && !skInUpdate) {
642
652
  const currentValue = currentItem._dyData[skField];
643
653
  if (currentValue !== undefined) {
644
654
  indexComputationData[skField] = currentValue;
645
655
  }
646
656
  }
647
- if (skInUpdate && !pkInUpdate && pkField !== "modelPrefix") {
657
+ if (skInUpdate && !pkInUpdate) {
648
658
  const currentValue = currentItem._dyData[pkField];
649
659
  if (currentValue !== undefined) {
650
660
  indexComputationData[pkField] = currentValue;
@@ -1018,7 +1028,7 @@ const MutationMethods = {
1018
1028
  if (error.name === "ConditionalCheckFailedException") {
1019
1029
  if (
1020
1030
  existsGuard &&
1021
- !(await this._existsAfterGuardFailure(primaryId, options))
1031
+ !(await this._existsAfterGuardFailure(primaryId, options, error))
1022
1032
  ) {
1023
1033
  throw new ItemNotFoundError("Item not found", primaryId);
1024
1034
  }
@@ -1219,10 +1229,19 @@ const MutationMethods = {
1219
1229
  }
1220
1230
  }
1221
1231
 
1222
- // Detect partial GSI key updates that would cause index staleness
1232
+ // Detect partial GSI key updates that would cause index staleness.
1233
+ // A "modelPrefix" half is a constant, so an update that leaves the
1234
+ // other half alone leaves the index key unchanged: skip it rather
1235
+ // than treat the constant as a newly provided key.
1223
1236
  if (isUpdate && index.indexId !== undefined) {
1224
- const pkProvided = index.pk === "modelPrefix" || pkValue !== undefined;
1225
- const skProvided = index.sk === "modelPrefix" || skValue !== undefined;
1237
+ if (
1238
+ (index.pk === "modelPrefix" && skValue === undefined) ||
1239
+ (index.sk === "modelPrefix" && pkValue === undefined)
1240
+ ) {
1241
+ return;
1242
+ }
1243
+ const pkProvided = pkValue !== undefined;
1244
+ const skProvided = skValue !== undefined;
1226
1245
  if (pkProvided && !skProvided) {
1227
1246
  throw new Error(
1228
1247
  `Update includes GSI partition key "${index.pk}" for index "${indexName}" ` +