dynamo-bao 0.8.1 → 0.9.0
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 +103 -1
- package/README.md +3 -3
- package/bin/bao-rebuild-search-text.js +40 -14
- package/bin/dynamo-bao-update-table.js +20 -3
- package/bin/generators/manifest.js +1 -1
- package/bin/generators/model.js +7 -8
- package/bin/lib/confirm.js +24 -0
- package/bin/lib/process-models.js +73 -2
- package/package.json +2 -1
- package/src/config.js +21 -11
- package/src/constants.js +4 -0
- package/src/dynamodb-client.js +18 -1
- package/src/fields.js +55 -1
- package/src/filter-expression.js +46 -17
- package/src/index.js +4 -3
- package/src/key-condition.js +2 -2
- package/src/mixins/batch-loading-mixin.js +8 -0
- package/src/mixins/mutation-mixin.js +95 -17
- package/src/mixins/query-mixin.js +4 -1
- package/src/mixins/unique-constraint-mixin.js +1 -1
- package/src/model-manager.js +33 -4
- package/src/model.js +57 -11
- package/src/tenant-context.js +52 -26
- package/src/utils/search-text.js +1 -1
- package/bin/chokidar-test.js +0 -60
package/CHANGELOG.md
CHANGED
|
@@ -9,6 +9,106 @@ Each version heading links to the tag that was published to npm. Entries before
|
|
|
9
9
|
|
|
10
10
|
## [Unreleased]
|
|
11
11
|
|
|
12
|
+
## [0.9.0] - 2026-10-28
|
|
13
|
+
|
|
14
|
+
### Security
|
|
15
|
+
|
|
16
|
+
- With tenancy enabled, an operation with no tenant in context now throws
|
|
17
|
+
`ConfigurationError`. It used to fall back to the tenant that was current
|
|
18
|
+
when `initModels()` ran, so a request that lost its tenant read and wrote
|
|
19
|
+
that tenant's data.
|
|
20
|
+
- `setCurrentTenant()` inside `runWithBatchContext()` now sets the tenant for
|
|
21
|
+
that context only. It used to set a process-wide tenant that concurrent
|
|
22
|
+
requests picked up. Registered resolvers now take precedence over the
|
|
23
|
+
process-wide tenant, `runWithTenant()` never sees it, and `clearTenant()`
|
|
24
|
+
inside a context clears only that context's tenant.
|
|
25
|
+
- Each distinct tenant id no longer adds a cached `ModelManager` that is
|
|
26
|
+
never freed. A caller sending random tenant ids could grow memory without
|
|
27
|
+
limit.
|
|
28
|
+
- Tenant ids containing `]` or `#`, which could produce another tenant's
|
|
29
|
+
keys, are rejected.
|
|
30
|
+
- A model with a field named like `n1` or `v1` could have that field's
|
|
31
|
+
placeholder overwritten by a write `condition`, writing the value into the
|
|
32
|
+
attribute the condition checked. Filter placeholders now use a reserved
|
|
33
|
+
prefix.
|
|
34
|
+
- `update()` rejects changes to primary key fields, and composite key values
|
|
35
|
+
can't contain the id separator `##__SK__##`. Either one could make an id
|
|
36
|
+
address a different record.
|
|
37
|
+
- `VersionField` is always generated on save and `CreateDateField` is set
|
|
38
|
+
only on create, so callers can't roll a version back to get around
|
|
39
|
+
optimistic locking.
|
|
40
|
+
- An `update()` that re-sends an unchanged unique value is now conditioned
|
|
41
|
+
on the stored value, so a concurrent change can't leave the value without
|
|
42
|
+
its constraint row for another record to claim.
|
|
43
|
+
- Codegen emits YAML values as literals and requires model, field, index
|
|
44
|
+
and constraint names to be JavaScript identifiers. Crafted YAML could
|
|
45
|
+
inject code into generated models or write files outside the output
|
|
46
|
+
directory.
|
|
47
|
+
|
|
48
|
+
### Added
|
|
49
|
+
|
|
50
|
+
- `allowedFilterFields` option on `queryByIndex()`, `iterateAll()` and
|
|
51
|
+
`searchAll()` (`allowedFields` on `FilterExpressionBuilder#build`) to limit
|
|
52
|
+
the fields a filter that comes from user input may reference.
|
|
53
|
+
- `TenantContext.setDefaultTenant()` sets the process-wide tenant
|
|
54
|
+
explicitly, for scripts and tests.
|
|
55
|
+
- `bao-rebuild-search-text --tenant <id>` for tenancy-enabled tables.
|
|
56
|
+
|
|
57
|
+
### Changed
|
|
58
|
+
|
|
59
|
+
- **Breaking:** importing the library no longer loads `.env` from the
|
|
60
|
+
working directory. Apps that relied on this should call
|
|
61
|
+
`require("dotenv").config()` themselves. The CLI tools still load `.env`.
|
|
62
|
+
- **Breaking:** config lookup no longer loads generic `config.js`,
|
|
63
|
+
`config.mjs` or `config.cjs` files, which could be an unrelated project's
|
|
64
|
+
config. It now refuses with a message saying to rename the file to
|
|
65
|
+
`dynamo-bao.config.js` or set `DYNAMO_BAO_CONFIG`.
|
|
66
|
+
- **Breaking:** `bao-update-table` and `bao-rebuild-search-text` ask before
|
|
67
|
+
changing the table. Pass `--yes` in scripts and CI.
|
|
68
|
+
- **Breaking:** field validation is stricter. `StringField` rejects objects,
|
|
69
|
+
arrays and booleans and now enforces `maxLength`. `IntegerField` rejects
|
|
70
|
+
non-integers and `FloatField` rejects non-numbers. Date fields reject
|
|
71
|
+
unparseable strings.
|
|
72
|
+
- `initModels()` no longer requires a tenant when tenancy is enabled.
|
|
73
|
+
- The `logging.level` passed to `initModels()` now takes effect
|
|
74
|
+
(`DYNAMO_BAO_LOG_LEVEL` still wins).
|
|
75
|
+
- Transactional writes send a `ClientRequestToken`, and updates that use
|
|
76
|
+
`ADD` (counters, set changes) are no longer retried, so a retry can't apply
|
|
77
|
+
a write twice.
|
|
78
|
+
|
|
79
|
+
### Fixed
|
|
80
|
+
|
|
81
|
+
- `$not` over more than one condition negated only the first one.
|
|
82
|
+
- Filter keys such as `constructor` or `toString` were looked up through the
|
|
83
|
+
prototype chain and either built an expression on a bogus attribute or
|
|
84
|
+
threw a `TypeError`. Filters are also limited to 16 levels of nesting.
|
|
85
|
+
- `CreateDateField` stored an ISO string as-is instead of converting it to a
|
|
86
|
+
timestamp.
|
|
87
|
+
- Model managers created for a tenant at runtime had no models, client or
|
|
88
|
+
config, so related-model lookups under that tenant could fail.
|
|
89
|
+
- A unique-constraint lookup error was logged with `console.error`,
|
|
90
|
+
bypassing the configured log level.
|
|
91
|
+
|
|
92
|
+
## [0.8.2] - 2026-10-27
|
|
93
|
+
|
|
94
|
+
### Fixed
|
|
95
|
+
|
|
96
|
+
- A conditional `update()` or `delete()` of a row that did not exist was
|
|
97
|
+
reported as `ConditionalError` instead of `ItemNotFoundError` when another
|
|
98
|
+
writer created the row right after the failed write. Since 0.8.0 the
|
|
99
|
+
library read the row after a failed condition check to tell the two apart,
|
|
100
|
+
and that read described a later state. Guarded writes now send
|
|
101
|
+
`ReturnValuesOnConditionCheckFailure`, so the answer comes from the state
|
|
102
|
+
DynamoDB evaluated the condition against. The follow-up read is gone, which
|
|
103
|
+
makes the failure path one call cheaper. It remains only as a fallback for
|
|
104
|
+
injected clients that do not surface the returned item.
|
|
105
|
+
|
|
106
|
+
### Changed
|
|
107
|
+
|
|
108
|
+
- The bundled DynamoDB client attaches `Item` to a
|
|
109
|
+
`ConditionalCheckFailedException` when the request asked for
|
|
110
|
+
`ReturnValuesOnConditionCheckFailure` (`null` when the row did not exist).
|
|
111
|
+
|
|
12
112
|
## [0.8.1] - 2026-10-27
|
|
13
113
|
|
|
14
114
|
### Fixed
|
|
@@ -467,7 +567,9 @@ Initial release: single-table models with fields, GSIs, unique constraints,
|
|
|
467
567
|
related fields, counters, TTL, filters, pagination, batch loading, hooks,
|
|
468
568
|
YAML codegen and a table creation tool.
|
|
469
569
|
|
|
470
|
-
[Unreleased]: https://github.com/aag1024/dynamo-bao/compare/v0.
|
|
570
|
+
[Unreleased]: https://github.com/aag1024/dynamo-bao/compare/v0.9.0...HEAD
|
|
571
|
+
[0.9.0]: https://github.com/aag1024/dynamo-bao/compare/v0.8.2...v0.9.0
|
|
572
|
+
[0.8.2]: https://github.com/aag1024/dynamo-bao/compare/v0.8.1...v0.8.2
|
|
471
573
|
[0.8.1]: https://github.com/aag1024/dynamo-bao/compare/v0.8.0...v0.8.1
|
|
472
574
|
[0.8.0]: https://github.com/aag1024/dynamo-bao/compare/v0.7.3...v0.8.0
|
|
473
575
|
[0.7.3]: https://github.com/aag1024/dynamo-bao/compare/v0.7.2...v0.7.3
|
package/README.md
CHANGED
|
@@ -457,7 +457,7 @@ Create a new Dynamo table for your project. You should have one table per projec
|
|
|
457
457
|
npx bao-init
|
|
458
458
|
```
|
|
459
459
|
|
|
460
|
-
This creates a `config.js` which contains settings for your project like AWS region and the table name.
|
|
460
|
+
This creates a `dynamo-bao.config.js` which contains settings for your project like AWS region and the table name.
|
|
461
461
|
|
|
462
462
|
It also creates a `models.yaml` file with a simple example model, and a `models` directory where
|
|
463
463
|
the generated models will be stored.
|
|
@@ -514,10 +514,10 @@ You should now have generated models in the `models` directory.
|
|
|
514
514
|
|
|
515
515
|
### ESM Support
|
|
516
516
|
|
|
517
|
-
DynamoBao supports generating models as ESM (ECMAScript Modules) for modern JavaScript projects. To enable ESM code generation, add the `codegen` configuration to your `config.js`:
|
|
517
|
+
DynamoBao supports generating models as ESM (ECMAScript Modules) for modern JavaScript projects. To enable ESM code generation, add the `codegen` configuration to your `dynamo-bao.config.js`:
|
|
518
518
|
|
|
519
519
|
```javascript
|
|
520
|
-
// config.js
|
|
520
|
+
// dynamo-bao.config.js
|
|
521
521
|
module.exports = {
|
|
522
522
|
aws: {
|
|
523
523
|
region: "us-west-2",
|
|
@@ -6,12 +6,22 @@
|
|
|
6
6
|
// `searchable: true` on a model with existing data.
|
|
7
7
|
|
|
8
8
|
const resolve = require("./lib/resolve");
|
|
9
|
-
const {
|
|
9
|
+
const { confirm } = require("./lib/confirm");
|
|
10
|
+
const { initModels, runWithBatchContext, TenantContext } =
|
|
11
|
+
resolve("src/index.js");
|
|
10
12
|
const { initConfig } = resolve("src/config.js");
|
|
11
13
|
|
|
12
|
-
const
|
|
13
|
-
|
|
14
|
-
|
|
14
|
+
const args = process.argv.slice(2);
|
|
15
|
+
const tenantFlag = args.indexOf("--tenant");
|
|
16
|
+
const tenantId = tenantFlag === -1 ? null : args[tenantFlag + 1];
|
|
17
|
+
const modelName = args.find(
|
|
18
|
+
(arg, i) =>
|
|
19
|
+
!arg.startsWith("-") && (tenantFlag === -1 || i !== tenantFlag + 1),
|
|
20
|
+
);
|
|
21
|
+
if (!modelName || (tenantFlag !== -1 && !tenantId)) {
|
|
22
|
+
console.error(
|
|
23
|
+
"Usage: bao-rebuild-search-text <ModelName> [--tenant <tenantId>] [--yes]",
|
|
24
|
+
);
|
|
15
25
|
process.exit(1);
|
|
16
26
|
}
|
|
17
27
|
|
|
@@ -40,20 +50,36 @@ if (!modelName) {
|
|
|
40
50
|
process.exit(1);
|
|
41
51
|
}
|
|
42
52
|
|
|
43
|
-
|
|
53
|
+
if (config.tenancy?.enabled && !tenantId) {
|
|
54
|
+
console.error("Tenancy is enabled: pass --tenant <tenantId>.");
|
|
55
|
+
process.exit(1);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const scope = tenantId ? ` for tenant '${tenantId}'` : "";
|
|
59
|
+
if (
|
|
60
|
+
!(await confirm(
|
|
61
|
+
`Re-save every ${modelName} row${scope} in table '${config.db.tableName}'?`,
|
|
62
|
+
))
|
|
63
|
+
) {
|
|
64
|
+
process.exit(1);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
console.log(`Rebuilding _searchText for ${modelName}${scope}...`);
|
|
44
68
|
let total = 0;
|
|
45
69
|
|
|
46
|
-
await
|
|
47
|
-
|
|
48
|
-
for (const
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
70
|
+
await TenantContext.runWithTenant(tenantId, () =>
|
|
71
|
+
runWithBatchContext(async () => {
|
|
72
|
+
for await (const batch of ModelClass.iterateAll({ batchSize: 50 })) {
|
|
73
|
+
for (const item of batch) {
|
|
74
|
+
await item.save({ forceReindex: true });
|
|
75
|
+
total++;
|
|
76
|
+
if (total % 100 === 0) {
|
|
77
|
+
console.log(` rebuilt ${total} so far...`);
|
|
78
|
+
}
|
|
53
79
|
}
|
|
54
80
|
}
|
|
55
|
-
}
|
|
56
|
-
|
|
81
|
+
}),
|
|
82
|
+
);
|
|
57
83
|
|
|
58
84
|
console.log(`Done. Rebuilt _searchText on ${total} ${modelName} item(s).`);
|
|
59
85
|
})().catch((err) => {
|
|
@@ -97,6 +97,7 @@ const ALL_ATTRIBUTE_DEFINITIONS = [
|
|
|
97
97
|
];
|
|
98
98
|
|
|
99
99
|
const { waitForTableActive } = require("./lib/create-table-params");
|
|
100
|
+
const { confirm } = require("./lib/confirm");
|
|
100
101
|
|
|
101
102
|
let client;
|
|
102
103
|
|
|
@@ -118,9 +119,16 @@ async function checkAndAddMissingGSIs(tableName) {
|
|
|
118
119
|
return;
|
|
119
120
|
}
|
|
120
121
|
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
122
|
+
const missingNames = missingGSIs.map((g) => g.IndexName).join(", ");
|
|
123
|
+
console.log(`Missing GSIs: ${missingNames}`);
|
|
124
|
+
if (
|
|
125
|
+
!(await confirm(
|
|
126
|
+
`Add GSIs ${missingNames} to table '${tableName}' (${client.region})?`,
|
|
127
|
+
))
|
|
128
|
+
) {
|
|
129
|
+
console.log("Skipped adding GSIs.");
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
124
132
|
|
|
125
133
|
// DynamoDB only allows adding one GSI per UpdateTable call
|
|
126
134
|
for (const gsi of missingGSIs) {
|
|
@@ -181,6 +189,15 @@ async function checkAndEnableTTL(tableName) {
|
|
|
181
189
|
return;
|
|
182
190
|
}
|
|
183
191
|
|
|
192
|
+
if (
|
|
193
|
+
!(await confirm(
|
|
194
|
+
`Enable TTL on attribute 'ttl' for table '${tableName}' (${client.region})?`,
|
|
195
|
+
))
|
|
196
|
+
) {
|
|
197
|
+
console.log("Skipped enabling TTL.");
|
|
198
|
+
return;
|
|
199
|
+
}
|
|
200
|
+
|
|
184
201
|
console.log("Enabling TTL on attribute 'ttl'...");
|
|
185
202
|
await client.send(
|
|
186
203
|
new UpdateTimeToLiveCommand({
|
|
@@ -46,7 +46,7 @@ function generateManifestFile(modelsDir, manifestPath) {
|
|
|
46
46
|
const relativePath = path.relative(manifestDir, file).replace(/\\/g, "/");
|
|
47
47
|
// Ensure .js extension for ESM imports
|
|
48
48
|
const importPath = relativePath.endsWith('.js') ? relativePath : `${relativePath}.js`;
|
|
49
|
-
return `import * as model${index} from
|
|
49
|
+
return `import * as model${index} from ${JSON.stringify(importPath)};`;
|
|
50
50
|
})
|
|
51
51
|
.join("\n");
|
|
52
52
|
|
package/bin/generators/model.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
const path = require("path");
|
|
2
2
|
const fs = require("fs");
|
|
3
3
|
const { createLogger } = require("../utils/scriptLogger");
|
|
4
|
+
const { validateModelNames } = require("../lib/process-models");
|
|
4
5
|
|
|
5
6
|
// const __dirname = __dirname;
|
|
6
7
|
const logger = createLogger("ModelGen");
|
|
@@ -59,18 +60,14 @@ function generateModelClass(
|
|
|
59
60
|
}
|
|
60
61
|
|
|
61
62
|
if (fieldConfig.type === "RelatedField") {
|
|
62
|
-
return ` ${fieldName}: ${fieldConfig.type}(
|
|
63
|
+
return ` ${fieldName}: ${fieldConfig.type}(${JSON.stringify(fieldConfig.model)}, { required: ${!!fieldConfig.required} }),`;
|
|
63
64
|
}
|
|
64
65
|
|
|
65
66
|
// Build options object from all field config properties except 'type'
|
|
66
67
|
const options = Object.entries(fieldConfig)
|
|
67
68
|
.filter(([key]) => key !== "type")
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
if (typeof value === "string") return `${key}: '${value}'`;
|
|
71
|
-
if (Array.isArray(value)) return `${key}: ${JSON.stringify(value)}`;
|
|
72
|
-
return `${key}: ${value}`;
|
|
73
|
-
});
|
|
69
|
+
// Values are always emitted as literals, never as code.
|
|
70
|
+
.map(([key, value]) => `${key}: ${JSON.stringify(value)}`);
|
|
74
71
|
|
|
75
72
|
const optionsStr = options.length ? `{ ${options.join(", ")} }` : "";
|
|
76
73
|
return ` ${fieldName}: ${fieldConfig.type}(${optionsStr}),`;
|
|
@@ -244,7 +241,7 @@ ${customFieldImports ? customFieldImports + '\n' : ''}
|
|
|
244
241
|
${relatedModelImports ? relatedModelImports + '\n' : ''}
|
|
245
242
|
|
|
246
243
|
class ${modelName} extends BaoModel {
|
|
247
|
-
static modelPrefix =
|
|
244
|
+
static modelPrefix = ${JSON.stringify(modelConfig.modelPrefix)};
|
|
248
245
|
static iterable = ${iterable};
|
|
249
246
|
static iterationBuckets = ${iterationBuckets};
|
|
250
247
|
static searchable = ${searchable};
|
|
@@ -281,6 +278,8 @@ function generateUniqueConstraintMethods(modelConfig) {
|
|
|
281
278
|
}
|
|
282
279
|
|
|
283
280
|
function generateModelFiles(models, outputDir, fieldResolver, moduleSystem = 'commonjs') {
|
|
281
|
+
validateModelNames(models);
|
|
282
|
+
|
|
284
283
|
if (!fs.existsSync(outputDir)) {
|
|
285
284
|
fs.mkdirSync(outputDir, { recursive: true });
|
|
286
285
|
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
const readline = require("readline");
|
|
2
|
+
|
|
3
|
+
// Asks before a command changes a table. --yes (or -y) skips the prompt.
|
|
4
|
+
// With no terminal to ask on, the command refuses rather than proceeding.
|
|
5
|
+
async function confirm(message, argv = process.argv) {
|
|
6
|
+
if (argv.includes("--yes") || argv.includes("-y")) {
|
|
7
|
+
return true;
|
|
8
|
+
}
|
|
9
|
+
if (!process.stdin.isTTY) {
|
|
10
|
+
console.error(`${message}\nNo terminal to confirm on; re-run with --yes.`);
|
|
11
|
+
return false;
|
|
12
|
+
}
|
|
13
|
+
const rl = readline.createInterface({
|
|
14
|
+
input: process.stdin,
|
|
15
|
+
output: process.stdout,
|
|
16
|
+
});
|
|
17
|
+
const answer = await new Promise((resolve) =>
|
|
18
|
+
rl.question(`${message} [y/N] `, resolve),
|
|
19
|
+
);
|
|
20
|
+
rl.close();
|
|
21
|
+
return /^y(es)?$/i.test(answer.trim());
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
module.exports = { confirm };
|
|
@@ -77,7 +77,10 @@ function validateSearchable(modelName, modelDef) {
|
|
|
77
77
|
}
|
|
78
78
|
}
|
|
79
79
|
|
|
80
|
-
if (
|
|
80
|
+
if (
|
|
81
|
+
raw.caseSensitive !== undefined &&
|
|
82
|
+
typeof raw.caseSensitive !== "boolean"
|
|
83
|
+
) {
|
|
81
84
|
throw new Error(
|
|
82
85
|
`Model "${modelName}": \`searchable.caseSensitive\` must be a boolean.`,
|
|
83
86
|
);
|
|
@@ -130,4 +133,72 @@ function applyModelDefaults(models) {
|
|
|
130
133
|
return models;
|
|
131
134
|
}
|
|
132
135
|
|
|
133
|
-
|
|
136
|
+
// Names from model definitions become identifiers, string literals, file
|
|
137
|
+
// names and import paths in generated code, so they must be plain JavaScript
|
|
138
|
+
// identifiers. Anything else could inject code or write outside the output
|
|
139
|
+
// directory.
|
|
140
|
+
const IDENTIFIER = /^[A-Za-z_$][\w$]*$/;
|
|
141
|
+
|
|
142
|
+
function assertIdentifier(value, what) {
|
|
143
|
+
if (typeof value !== "string" || !IDENTIFIER.test(value)) {
|
|
144
|
+
throw new Error(
|
|
145
|
+
`Invalid ${what} ${JSON.stringify(value)}: must be a JavaScript identifier`,
|
|
146
|
+
);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function assertIdSuffix(value, what) {
|
|
151
|
+
if (typeof value !== "string" || !/\d$/.test(value)) {
|
|
152
|
+
throw new Error(`Invalid ${what} ${JSON.stringify(value)}`);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function validateModelNames(models) {
|
|
157
|
+
for (const [modelName, modelDef] of Object.entries(models)) {
|
|
158
|
+
assertIdentifier(modelName, "model name");
|
|
159
|
+
const where = (what) => `${what} in model ${modelName}`;
|
|
160
|
+
|
|
161
|
+
for (const [fieldName, fieldDef] of Object.entries(modelDef.fields || {})) {
|
|
162
|
+
assertIdentifier(fieldName, where("field name"));
|
|
163
|
+
if (fieldDef.type !== undefined) {
|
|
164
|
+
assertIdentifier(fieldDef.type, where(`type of field ${fieldName}`));
|
|
165
|
+
}
|
|
166
|
+
if (fieldDef.model !== undefined) {
|
|
167
|
+
assertIdentifier(fieldDef.model, where(`model of field ${fieldName}`));
|
|
168
|
+
}
|
|
169
|
+
for (const option of Object.keys(fieldDef)) {
|
|
170
|
+
assertIdentifier(option, where(`option of field ${fieldName}`));
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
const { partitionKey, sortKey } = modelDef.primaryKey || {};
|
|
175
|
+
assertIdentifier(partitionKey, where("primary partition key"));
|
|
176
|
+
if (sortKey !== undefined) {
|
|
177
|
+
assertIdentifier(sortKey, where("primary sort key"));
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
for (const [indexName, index] of Object.entries(modelDef.indexes || {})) {
|
|
181
|
+
assertIdentifier(indexName, where("index name"));
|
|
182
|
+
if (index === "primaryKey") continue;
|
|
183
|
+
assertIdentifier(
|
|
184
|
+
index.partitionKey,
|
|
185
|
+
where(`partition key of ${indexName}`),
|
|
186
|
+
);
|
|
187
|
+
assertIdentifier(index.sortKey, where(`sort key of ${indexName}`));
|
|
188
|
+
assertIdSuffix(index.indexId, where(`indexId of ${indexName}`));
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
for (const [name, constraint] of Object.entries(
|
|
192
|
+
modelDef.uniqueConstraints || {},
|
|
193
|
+
)) {
|
|
194
|
+
assertIdentifier(name, where("unique constraint name"));
|
|
195
|
+
assertIdentifier(constraint.field, where(`field of ${name}`));
|
|
196
|
+
assertIdSuffix(
|
|
197
|
+
constraint.uniqueConstraintId,
|
|
198
|
+
where(`uniqueConstraintId of ${name}`),
|
|
199
|
+
);
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
module.exports = { applyModelDefaults, validateModelNames };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dynamo-bao",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.9.0",
|
|
4
4
|
"description": "Simple powerful data modeling primitives for DynamoDB in JavaScript.",
|
|
5
5
|
"main": "src/index.js",
|
|
6
6
|
"exports": {
|
|
@@ -17,6 +17,7 @@
|
|
|
17
17
|
},
|
|
18
18
|
"files": [
|
|
19
19
|
"bin/",
|
|
20
|
+
"!bin/chokidar-test.js",
|
|
20
21
|
"src/",
|
|
21
22
|
"README.md",
|
|
22
23
|
"CHANGELOG.md"
|
package/src/config.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
const fs = require("fs");
|
|
2
2
|
const path = require("path");
|
|
3
|
-
const
|
|
3
|
+
const { pathToFileURL } = require("url");
|
|
4
4
|
|
|
5
5
|
async function findConfig() {
|
|
6
6
|
// First check environment variable
|
|
@@ -22,10 +22,10 @@ async function findConfig() {
|
|
|
22
22
|
"dynamo-bao.config.cjs",
|
|
23
23
|
".dynamo-bao/config.js",
|
|
24
24
|
".dynamo-bao/config.mjs",
|
|
25
|
-
"config.js",
|
|
26
|
-
"config.mjs",
|
|
27
|
-
"config.cjs",
|
|
28
25
|
];
|
|
26
|
+
// Older versions also loaded these generic names, which meant running any
|
|
27
|
+
// project's config.js. Refuse them rather than silently using defaults.
|
|
28
|
+
const legacyNames = ["config.js", "config.mjs", "config.cjs"];
|
|
29
29
|
const searchPaths = [
|
|
30
30
|
process.cwd(), // Project root
|
|
31
31
|
];
|
|
@@ -40,10 +40,20 @@ async function findConfig() {
|
|
|
40
40
|
return normalizeConfig(rawConfig, configDir);
|
|
41
41
|
}
|
|
42
42
|
}
|
|
43
|
+
for (const name of legacyNames) {
|
|
44
|
+
if (fs.existsSync(path.join(searchPath, name))) {
|
|
45
|
+
throw new Error(
|
|
46
|
+
`Found ${name} but no dynamo-bao.config.js in ${searchPath}. ` +
|
|
47
|
+
"dynamo-bao no longer loads generic config file names: rename it " +
|
|
48
|
+
`to dynamo-bao.config.js, or set DYNAMO_BAO_CONFIG=${name}.`,
|
|
49
|
+
);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
43
52
|
}
|
|
44
53
|
|
|
45
|
-
// If no config file found, create default config from env
|
|
46
|
-
|
|
54
|
+
// If no config file found, create default config from env. Only the CLI
|
|
55
|
+
// tools reach this, so loading .env here doesn't affect library users.
|
|
56
|
+
require("dotenv").config();
|
|
47
57
|
return {
|
|
48
58
|
aws: {
|
|
49
59
|
region: process.env.AWS_REGION || "us-west-2",
|
|
@@ -78,8 +88,7 @@ async function loadConfigFile(configPath) {
|
|
|
78
88
|
return require(configPath);
|
|
79
89
|
} else if (configPath.endsWith(".mjs") || configPath.endsWith(".js")) {
|
|
80
90
|
// Use dynamic import for ESM files
|
|
81
|
-
const
|
|
82
|
-
const module = await import(fileUrl);
|
|
91
|
+
const module = await import(pathToFileURL(configPath).href);
|
|
83
92
|
return module.default || module;
|
|
84
93
|
} else {
|
|
85
94
|
// Default to require for legacy files
|
|
@@ -142,10 +151,11 @@ async function initConfig() {
|
|
|
142
151
|
return config;
|
|
143
152
|
}
|
|
144
153
|
|
|
145
|
-
//
|
|
154
|
+
// Defaults read from the environment when the library is imported. This
|
|
155
|
+
// deliberately doesn't load .env: a library shouldn't change process.env, or
|
|
156
|
+
// pick its table and credentials from whatever .env is in the working
|
|
157
|
+
// directory. Apps that use .env should load it themselves.
|
|
146
158
|
try {
|
|
147
|
-
// For now, create a basic synchronous config
|
|
148
|
-
const dotenvResult = dotenv.config();
|
|
149
159
|
config = {
|
|
150
160
|
aws: {
|
|
151
161
|
region: process.env.AWS_REGION || "us-west-2",
|
package/src/constants.js
CHANGED
|
@@ -47,6 +47,9 @@ const SYSTEM_FIELDS = [
|
|
|
47
47
|
|
|
48
48
|
const UNIQUE_CONSTRAINT_KEY = "_raft_uc";
|
|
49
49
|
|
|
50
|
+
// Joins pk and sk in the string primary id of a composite-key model.
|
|
51
|
+
const GID_SEPARATOR = "##__SK__##";
|
|
52
|
+
|
|
50
53
|
module.exports = {
|
|
51
54
|
GSI_INDEX_ID1,
|
|
52
55
|
GSI_INDEX_ID2,
|
|
@@ -64,4 +67,5 @@ module.exports = {
|
|
|
64
67
|
UNIQUE_CONSTRAINT_ID3,
|
|
65
68
|
SYSTEM_FIELDS,
|
|
66
69
|
UNIQUE_CONSTRAINT_KEY,
|
|
70
|
+
GID_SEPARATOR,
|
|
67
71
|
};
|
package/src/dynamodb-client.js
CHANGED
|
@@ -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 };
|
package/src/fields.js
CHANGED
|
@@ -155,10 +155,27 @@ class BaoBaseField {
|
|
|
155
155
|
* A field that stores a string value.
|
|
156
156
|
*/
|
|
157
157
|
class StringField extends BaoBaseField {
|
|
158
|
+
constructor(options = {}) {
|
|
159
|
+
super(options);
|
|
160
|
+
this.maxLength = options.maxLength;
|
|
161
|
+
}
|
|
162
|
+
|
|
158
163
|
validate(value) {
|
|
159
164
|
if (this.required && !value) {
|
|
160
165
|
throw new ValidationError("Field is required", null, value);
|
|
161
166
|
}
|
|
167
|
+
if (
|
|
168
|
+
value !== null &&
|
|
169
|
+
value !== undefined &&
|
|
170
|
+
typeof value !== "string" &&
|
|
171
|
+
typeof value !== "number"
|
|
172
|
+
) {
|
|
173
|
+
throw new ValidationError(
|
|
174
|
+
"StringField value must be a string",
|
|
175
|
+
null,
|
|
176
|
+
value,
|
|
177
|
+
);
|
|
178
|
+
}
|
|
162
179
|
if (value && this.maxLength && value.length > this.maxLength) {
|
|
163
180
|
throw new ValidationError(
|
|
164
181
|
`Value exceeds maximum length of ${this.maxLength}`,
|
|
@@ -195,6 +212,9 @@ class DateTimeField extends BaoBaseField {
|
|
|
195
212
|
value,
|
|
196
213
|
);
|
|
197
214
|
}
|
|
215
|
+
if (value !== undefined && value !== null && isNaN(this.toDy(value))) {
|
|
216
|
+
throw new ValidationError("Invalid date value", null, value);
|
|
217
|
+
}
|
|
198
218
|
}
|
|
199
219
|
|
|
200
220
|
toDy(value) {
|
|
@@ -250,6 +270,21 @@ class DateTimeField extends BaoBaseField {
|
|
|
250
270
|
* A field that stores an integer value.
|
|
251
271
|
*/
|
|
252
272
|
class IntegerField extends BaoBaseField {
|
|
273
|
+
validate(value) {
|
|
274
|
+
super.validate(value);
|
|
275
|
+
if (value !== undefined && value !== null) {
|
|
276
|
+
const num = Number(value);
|
|
277
|
+
if (typeof value === "boolean" || !Number.isInteger(num)) {
|
|
278
|
+
throw new ValidationError(
|
|
279
|
+
"IntegerField value must be an integer",
|
|
280
|
+
null,
|
|
281
|
+
value,
|
|
282
|
+
);
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
return true;
|
|
286
|
+
}
|
|
287
|
+
|
|
253
288
|
getInitialValue() {
|
|
254
289
|
return this.options.defaultValue !== undefined
|
|
255
290
|
? this.options.defaultValue
|
|
@@ -283,6 +318,20 @@ class IntegerField extends BaoBaseField {
|
|
|
283
318
|
* A field that stores a floating point number value.
|
|
284
319
|
*/
|
|
285
320
|
class FloatField extends BaoBaseField {
|
|
321
|
+
validate(value) {
|
|
322
|
+
super.validate(value);
|
|
323
|
+
if (value !== undefined && value !== null) {
|
|
324
|
+
if (typeof value === "boolean" || !Number.isFinite(Number(value))) {
|
|
325
|
+
throw new ValidationError(
|
|
326
|
+
"FloatField value must be a number",
|
|
327
|
+
null,
|
|
328
|
+
value,
|
|
329
|
+
);
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
return true;
|
|
333
|
+
}
|
|
334
|
+
|
|
286
335
|
getInitialValue() {
|
|
287
336
|
return this.options.defaultValue !== undefined
|
|
288
337
|
? this.options.defaultValue
|
|
@@ -325,6 +374,8 @@ class CreateDateField extends DateTimeField {
|
|
|
325
374
|
...options,
|
|
326
375
|
required: true,
|
|
327
376
|
});
|
|
377
|
+
// Set once on create; updates leave the stored value alone.
|
|
378
|
+
this.immutable = true;
|
|
328
379
|
}
|
|
329
380
|
|
|
330
381
|
getInitialValue() {
|
|
@@ -335,7 +386,7 @@ class CreateDateField extends DateTimeField {
|
|
|
335
386
|
if (!value) {
|
|
336
387
|
return Date.now();
|
|
337
388
|
}
|
|
338
|
-
return
|
|
389
|
+
return super.toDy(value);
|
|
339
390
|
}
|
|
340
391
|
}
|
|
341
392
|
|
|
@@ -643,6 +694,9 @@ class VersionField extends BaoBaseField {
|
|
|
643
694
|
required: true,
|
|
644
695
|
});
|
|
645
696
|
this.defaultValue = options.defaultValue || ulid;
|
|
697
|
+
// Every save gets a fresh version; a caller-supplied value is ignored,
|
|
698
|
+
// so it can't be rolled back to defeat optimistic locking.
|
|
699
|
+
this.serverGenerated = true;
|
|
646
700
|
}
|
|
647
701
|
|
|
648
702
|
validate(value) {
|