dynamo-bao 0.1.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/README.md +333 -0
- package/bin/chokidar-test.js +60 -0
- package/bin/codegen.js +114 -0
- package/bin/dynamo-bao-create-table.js +136 -0
- package/bin/generators/index.js +0 -0
- package/bin/generators/model.js +428 -0
- package/bin/utils/scriptLogger.js +10 -0
- package/bin/watch.js +93 -0
- package/package.json +54 -0
- package/src/config.js +60 -0
- package/src/constants.js +35 -0
- package/src/db.js +21 -0
- package/src/fieldResolver.js +74 -0
- package/src/fields.js +781 -0
- package/src/filter-expression.js +241 -0
- package/src/index.js +127 -0
- package/src/key-condition.js +258 -0
- package/src/mixins/batch-loading-mixin.js +336 -0
- package/src/mixins/mutation-mixin.js +595 -0
- package/src/mixins/query-mixin.js +341 -0
- package/src/mixins/unique-constraint-mixin.js +131 -0
- package/src/mixins/validation-mixin.js +154 -0
- package/src/model-config.js +47 -0
- package/src/model-manager.js +106 -0
- package/src/model.js +689 -0
- package/src/object-not-found.js +44 -0
- package/src/plugin-manager.js +61 -0
- package/src/utils/logger.js +54 -0
- package/src/utils/retry-helper.js +24 -0
|
@@ -0,0 +1,341 @@
|
|
|
1
|
+
const { defaultLogger: logger } = require("../utils/logger");
|
|
2
|
+
const { KeyConditionBuilder } = require("../key-condition");
|
|
3
|
+
const { FilterExpressionBuilder } = require("../filter-expression");
|
|
4
|
+
const { ObjectNotFound } = require("../object-not-found");
|
|
5
|
+
const { PrimaryKeyConfig } = require("../model-config");
|
|
6
|
+
const assert = require("assert");
|
|
7
|
+
const { retryOperation } = require("../utils/retry-helper");
|
|
8
|
+
const { QueryCommand } = require("@aws-sdk/lib-dynamodb");
|
|
9
|
+
|
|
10
|
+
const QueryMethods = {
|
|
11
|
+
/**
|
|
12
|
+
*@memberof BaoModel
|
|
13
|
+
*
|
|
14
|
+
* @description
|
|
15
|
+
* Queries items by their primary key value with an optional sort key condition
|
|
16
|
+
*
|
|
17
|
+
* For more details, see queryByIndex. In general, it's recommended to use
|
|
18
|
+
* queryByIndex and give a name to the index. You can do this by adding
|
|
19
|
+
* an index name in the indexes section of the model definition and setting
|
|
20
|
+
* it to primaryKey. For example:
|
|
21
|
+
*
|
|
22
|
+
* models:
|
|
23
|
+
* TaggedPost:
|
|
24
|
+
* ...
|
|
25
|
+
* indexes:
|
|
26
|
+
* postsForTag: this.primaryKey
|
|
27
|
+
*
|
|
28
|
+
* @param {*} pkValue - The partition key value to query
|
|
29
|
+
* @param {Object|null} skCondition - Optional sort key condition in the format: { fieldName: value } or { fieldName: { $operator: value } }
|
|
30
|
+
* @param {Object} options - Query options (same as queryByIndex options)
|
|
31
|
+
* @returns {Promise<Object>} Returns an object containing items, count, lastEvaluatedKey, and consumedCapacity
|
|
32
|
+
*/
|
|
33
|
+
async queryByPrimaryKey(pkValue, skCondition = null, options = {}) {
|
|
34
|
+
const params = this._getBaseQueryParams(
|
|
35
|
+
"_pk",
|
|
36
|
+
this._formatPrimaryKey(this.modelPrefix, pkValue),
|
|
37
|
+
skCondition,
|
|
38
|
+
options,
|
|
39
|
+
);
|
|
40
|
+
|
|
41
|
+
const response = await retryOperation(() =>
|
|
42
|
+
this.documentClient.send(new QueryCommand(params)),
|
|
43
|
+
);
|
|
44
|
+
|
|
45
|
+
return this._processQueryResponse(response, options);
|
|
46
|
+
},
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
*@memberof BaoModel
|
|
50
|
+
*
|
|
51
|
+
* @description
|
|
52
|
+
* Queries related objects via a mapping table.
|
|
53
|
+
*
|
|
54
|
+
* This is primary used by the code generator to build helper functions
|
|
55
|
+
* for querying related objects. For most common operations, you should
|
|
56
|
+
* not need to use this method directly.
|
|
57
|
+
*/
|
|
58
|
+
async getRelatedObjectsViaMap(
|
|
59
|
+
indexName,
|
|
60
|
+
pkValue,
|
|
61
|
+
targetField,
|
|
62
|
+
mapSkCondition = null,
|
|
63
|
+
limit = null,
|
|
64
|
+
direction = "ASC",
|
|
65
|
+
startKey = null,
|
|
66
|
+
) {
|
|
67
|
+
return await this.queryByIndex(indexName, pkValue, mapSkCondition, {
|
|
68
|
+
loadRelated: true,
|
|
69
|
+
relatedOnly: true,
|
|
70
|
+
relatedFields: [targetField],
|
|
71
|
+
limit,
|
|
72
|
+
direction,
|
|
73
|
+
startKey,
|
|
74
|
+
});
|
|
75
|
+
},
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
*@memberof BaoModel
|
|
79
|
+
*
|
|
80
|
+
* @description
|
|
81
|
+
* This is the primary method for querying data via a named index or primary key.
|
|
82
|
+
* If possible, you should always specify a sort key condition using skCondition.
|
|
83
|
+
* This will use dynamodb's index to query the data without scanning the partition.
|
|
84
|
+
*
|
|
85
|
+
* Optionally, you can specify a filter condition to further narrow down the results.
|
|
86
|
+
* Please note that a filter condition will scan anything in the partition that matches
|
|
87
|
+
* the skCondition, so if you haven't specified a skCondition, this will scan
|
|
88
|
+
* the entire partition (and consume more capacity units). However, there may
|
|
89
|
+
* also be times when this works without issue and is more efficient than adding
|
|
90
|
+
* another index and paying for the write overhead of the index.
|
|
91
|
+
*
|
|
92
|
+
* @param {string} indexName - The name of the index to query based on the model definition
|
|
93
|
+
* @param {string|Object} pkValue - The partition key value to query.
|
|
94
|
+
* @param {Object|null} skCondition - Optional sort key condition in the format: { fieldName: value } or { fieldName: { $operator: value } }
|
|
95
|
+
* Supported operators: $between, $beginsWith
|
|
96
|
+
* Example: { status: 'active' } or { createdAt: { $between: [date1, date2] } }
|
|
97
|
+
* @param {Object} options - Additional query options
|
|
98
|
+
* @param {number} options.limit - Maximum number of items to return (default: model.defaultQueryLimit)
|
|
99
|
+
* @param {string} options.direction - Sort direction, 'ASC' or 'DESC' (default: 'ASC')
|
|
100
|
+
* @param {Object} options.startKey - Exclusive start key for pagination
|
|
101
|
+
* @param {boolean} options.countOnly - If true, returns only the count of matching items
|
|
102
|
+
* @param {Object} options.filter - Additional filter conditions for the query. For full filter syntax, see {@link FilterExpressionBuilder#build}
|
|
103
|
+
* @param {boolean} options.returnWrapped - If false, returns raw DynamoDB items instead of model instances
|
|
104
|
+
* @param {boolean} options.loadRelated - If true, loads related models for RelatedFields
|
|
105
|
+
* @param {string[]} options.relatedFields - Array of field names to load related data for (used with loadRelated)
|
|
106
|
+
* @param {boolean} options.relatedOnly - Used by mapping tables to return only target objects;
|
|
107
|
+
* loadRelated and a single entry in relatedFields must be provided
|
|
108
|
+
*
|
|
109
|
+
* @returns {Promise<Object>} Returns an object containing:
|
|
110
|
+
* - items: Array of model instances or raw items
|
|
111
|
+
* - count: Number of items scanned
|
|
112
|
+
* - lastEvaluatedKey: Key for pagination (if more items exist)
|
|
113
|
+
* - consumedCapacity: DynamoDB response metadata including ConsumedCapacity
|
|
114
|
+
*
|
|
115
|
+
* @throws {Error} If index name is not found in model
|
|
116
|
+
* @throws {Error} If sort key condition references wrong field
|
|
117
|
+
*
|
|
118
|
+
* @example
|
|
119
|
+
* // Basic query
|
|
120
|
+
* const results = await Model.queryByIndex('statusIndex', 'active');
|
|
121
|
+
*
|
|
122
|
+
* // Query with sort key condition
|
|
123
|
+
* const results = await Model.queryByIndex('dateIndex', 'user123', {
|
|
124
|
+
* createdAt: { $between: [startDate, endDate] }
|
|
125
|
+
* });
|
|
126
|
+
*
|
|
127
|
+
* // Query with pagination
|
|
128
|
+
* const results = await Model.queryByIndex('statusIndex', 'active', null, {
|
|
129
|
+
* limit: 10,
|
|
130
|
+
* startKey: lastEvaluatedKey
|
|
131
|
+
* });
|
|
132
|
+
*
|
|
133
|
+
* // Query with related data
|
|
134
|
+
* const results = await Model.queryByIndex('userIndex', userId, null, {
|
|
135
|
+
* loadRelated: true,
|
|
136
|
+
* relatedFields: ['organizationId']
|
|
137
|
+
* });
|
|
138
|
+
*/
|
|
139
|
+
async queryByIndex(indexName, pkValue, skCondition = null, options = {}) {
|
|
140
|
+
const index = this.indexes[indexName];
|
|
141
|
+
if (!index) {
|
|
142
|
+
throw new Error(`Index "${indexName}" not found in ${this.name} model`);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// Validate sort key field if condition is provided
|
|
146
|
+
if (skCondition) {
|
|
147
|
+
const [[fieldName]] = Object.entries(skCondition);
|
|
148
|
+
if (fieldName !== index.sk) {
|
|
149
|
+
throw new Error(
|
|
150
|
+
`Field "${fieldName}" is not the sort key for index "${indexName}"`,
|
|
151
|
+
);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
// Format the partition key using the field's toGsi method
|
|
156
|
+
let formattedPk;
|
|
157
|
+
if (index instanceof PrimaryKeyConfig) {
|
|
158
|
+
formattedPk = this._formatPrimaryKey(this.modelPrefix, pkValue);
|
|
159
|
+
} else {
|
|
160
|
+
const pkField = this._getField(index.pk);
|
|
161
|
+
const gsiValue = pkField.toGsi(pkValue);
|
|
162
|
+
formattedPk = this._formatGsiKey(
|
|
163
|
+
this.modelPrefix,
|
|
164
|
+
index.indexId,
|
|
165
|
+
gsiValue,
|
|
166
|
+
);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
const params = this._getBaseQueryParams(
|
|
170
|
+
index instanceof PrimaryKeyConfig ? "_pk" : `_${index.indexId}_pk`,
|
|
171
|
+
formattedPk,
|
|
172
|
+
skCondition ? { [index.sk]: skCondition[index.sk] } : null,
|
|
173
|
+
{
|
|
174
|
+
...options,
|
|
175
|
+
indexName,
|
|
176
|
+
gsiIndexId: index.indexId,
|
|
177
|
+
gsiSortKeyName: `_${index.indexId}_sk`,
|
|
178
|
+
},
|
|
179
|
+
);
|
|
180
|
+
|
|
181
|
+
// Add debug logging
|
|
182
|
+
logger.log("DynamoDB Query Params:", {
|
|
183
|
+
TableName: params.TableName,
|
|
184
|
+
IndexName: params.IndexName,
|
|
185
|
+
KeyConditionExpression: params.KeyConditionExpression,
|
|
186
|
+
ExpressionAttributeNames: params.ExpressionAttributeNames,
|
|
187
|
+
ExpressionAttributeValues: params.ExpressionAttributeValues,
|
|
188
|
+
});
|
|
189
|
+
|
|
190
|
+
const response = await retryOperation(() =>
|
|
191
|
+
this.documentClient.send(new QueryCommand(params)),
|
|
192
|
+
);
|
|
193
|
+
|
|
194
|
+
// Add debug logging
|
|
195
|
+
logger.log("DynamoDB Response:", {
|
|
196
|
+
Count: response.Count,
|
|
197
|
+
ScannedCount: response.ScannedCount,
|
|
198
|
+
Items: response.Items?.map((item) => ({
|
|
199
|
+
name: item.name,
|
|
200
|
+
category: item.category,
|
|
201
|
+
status: item.status,
|
|
202
|
+
})),
|
|
203
|
+
});
|
|
204
|
+
|
|
205
|
+
let totalItems;
|
|
206
|
+
if (options.countOnly) {
|
|
207
|
+
totalItems = response.Count;
|
|
208
|
+
} else if (options.startKey) {
|
|
209
|
+
totalItems = (options.previousCount || 0) + response.Items.length;
|
|
210
|
+
} else {
|
|
211
|
+
totalItems = response.Items.length;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
return this._processQueryResponse(response, {
|
|
215
|
+
...options,
|
|
216
|
+
totalItems,
|
|
217
|
+
});
|
|
218
|
+
},
|
|
219
|
+
|
|
220
|
+
_getBaseQueryParams(pkFieldName, pkValue, skCondition, options = {}) {
|
|
221
|
+
const keyBuilder = new KeyConditionBuilder();
|
|
222
|
+
let keyConditionExpression = `#pk = :pk`;
|
|
223
|
+
const expressionNames = { "#pk": pkFieldName };
|
|
224
|
+
const expressionValues = { ":pk": pkValue };
|
|
225
|
+
|
|
226
|
+
if (skCondition) {
|
|
227
|
+
logger.log("Building key condition for:", {
|
|
228
|
+
condition: skCondition,
|
|
229
|
+
gsiSortKeyName: options.gsiIndexId
|
|
230
|
+
? `_${options.gsiIndexId}_sk`
|
|
231
|
+
: "_sk",
|
|
232
|
+
});
|
|
233
|
+
|
|
234
|
+
const skExpr = keyBuilder.buildKeyCondition(
|
|
235
|
+
this,
|
|
236
|
+
options.indexName || "primary",
|
|
237
|
+
skCondition,
|
|
238
|
+
options.gsiIndexId ? `_${options.gsiIndexId}_sk` : "_sk",
|
|
239
|
+
);
|
|
240
|
+
if (skExpr) {
|
|
241
|
+
keyConditionExpression += ` AND ${skExpr.condition}`;
|
|
242
|
+
Object.assign(expressionNames, skExpr.names);
|
|
243
|
+
Object.assign(expressionValues, skExpr.values);
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
const params = {
|
|
248
|
+
TableName: this.table,
|
|
249
|
+
KeyConditionExpression: keyConditionExpression,
|
|
250
|
+
ExpressionAttributeNames: expressionNames,
|
|
251
|
+
ExpressionAttributeValues: expressionValues,
|
|
252
|
+
ScanIndexForward: options.direction !== "DESC",
|
|
253
|
+
ReturnConsumedCapacity: "TOTAL",
|
|
254
|
+
Limit: options.limit || this.defaultQueryLimit,
|
|
255
|
+
};
|
|
256
|
+
|
|
257
|
+
// Add Select:COUNT for countOnly queries
|
|
258
|
+
if (options.countOnly) {
|
|
259
|
+
params.Select = "COUNT";
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
// Add the IndexName if gsiIndexId is provided
|
|
263
|
+
if (options.gsiIndexId) {
|
|
264
|
+
params.IndexName = options.gsiIndexId;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
if (options.startKey) {
|
|
268
|
+
params.ExclusiveStartKey = options.startKey;
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
// Add filter expression if provided
|
|
272
|
+
if (options.filter) {
|
|
273
|
+
const filterBuilder = new FilterExpressionBuilder();
|
|
274
|
+
const filterExpression = filterBuilder.build(options.filter, this);
|
|
275
|
+
|
|
276
|
+
if (filterExpression) {
|
|
277
|
+
params.FilterExpression = filterExpression.FilterExpression;
|
|
278
|
+
Object.assign(
|
|
279
|
+
params.ExpressionAttributeNames,
|
|
280
|
+
filterExpression.ExpressionAttributeNames,
|
|
281
|
+
);
|
|
282
|
+
Object.assign(
|
|
283
|
+
params.ExpressionAttributeValues,
|
|
284
|
+
filterExpression.ExpressionAttributeValues,
|
|
285
|
+
);
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
return params;
|
|
290
|
+
},
|
|
291
|
+
|
|
292
|
+
async _processQueryResponse(response, options = {}) {
|
|
293
|
+
if (options.countOnly) {
|
|
294
|
+
return {
|
|
295
|
+
count: response.Count,
|
|
296
|
+
consumedCapacity: response.ConsumedCapacity,
|
|
297
|
+
};
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
const {
|
|
301
|
+
returnWrapped = true,
|
|
302
|
+
loadRelated = false,
|
|
303
|
+
relatedFields = null,
|
|
304
|
+
relatedOnly = false,
|
|
305
|
+
} = options;
|
|
306
|
+
|
|
307
|
+
if (relatedOnly) {
|
|
308
|
+
assert(
|
|
309
|
+
relatedFields && relatedFields.length === 1,
|
|
310
|
+
"relatedOnly requires a single entry in relatedFields",
|
|
311
|
+
);
|
|
312
|
+
assert(loadRelated, "relatedOnly requires loadRelated to be true");
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
// Create model instances
|
|
316
|
+
let items = returnWrapped
|
|
317
|
+
? response.Items.map((item) => this._createFromDyItem(item))
|
|
318
|
+
: response.Items;
|
|
319
|
+
const loaderContext = options.loaderContext || {};
|
|
320
|
+
|
|
321
|
+
// Load related data if requested
|
|
322
|
+
if (returnWrapped && loadRelated) {
|
|
323
|
+
await Promise.all(
|
|
324
|
+
items.map((item) => item.loadRelatedData(relatedFields, loaderContext)),
|
|
325
|
+
);
|
|
326
|
+
|
|
327
|
+
if (relatedOnly) {
|
|
328
|
+
items = items.map((item) => item.getRelated(relatedFields[0]));
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
return {
|
|
333
|
+
items,
|
|
334
|
+
count: items.length,
|
|
335
|
+
lastEvaluatedKey: response.LastEvaluatedKey,
|
|
336
|
+
consumedCapacity: response.ConsumedCapacity,
|
|
337
|
+
};
|
|
338
|
+
},
|
|
339
|
+
};
|
|
340
|
+
|
|
341
|
+
module.exports = QueryMethods;
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
const { GetCommand } = require("@aws-sdk/lib-dynamodb");
|
|
2
|
+
const { defaultLogger: logger } = require("../utils/logger");
|
|
3
|
+
const { UNIQUE_CONSTRAINT_KEY } = require("../constants");
|
|
4
|
+
|
|
5
|
+
const UniqueConstraintMethods = {
|
|
6
|
+
async _validateUniqueConstraints(data, currentId = null) {
|
|
7
|
+
logger.debug("validateUniqueConstraints called on", this.name, {
|
|
8
|
+
modelTestId: this._testId,
|
|
9
|
+
managerTestId: this.manager.getTestId(),
|
|
10
|
+
instanceKey: this._testId || "default",
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
if (!this.uniqueConstraints) {
|
|
14
|
+
return;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const docClient = this.manager.documentClient;
|
|
18
|
+
const tableName = this.manager.tableName;
|
|
19
|
+
|
|
20
|
+
for (const [name, constraint] of Object.entries(this.uniqueConstraints)) {
|
|
21
|
+
const value = data[constraint.field];
|
|
22
|
+
if (!value) continue;
|
|
23
|
+
|
|
24
|
+
try {
|
|
25
|
+
const key = this._formatUniqueConstraintKey.call(
|
|
26
|
+
this,
|
|
27
|
+
constraint.constraintId,
|
|
28
|
+
this.modelPrefix,
|
|
29
|
+
constraint.field,
|
|
30
|
+
value,
|
|
31
|
+
);
|
|
32
|
+
|
|
33
|
+
logger.debug("Checking unique constraint:", {
|
|
34
|
+
key,
|
|
35
|
+
field: constraint.field,
|
|
36
|
+
value,
|
|
37
|
+
testId: this.manager.getTestId(),
|
|
38
|
+
managerTestId: this.manager.getTestId(),
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
const result = await docClient.send(
|
|
42
|
+
new GetCommand({
|
|
43
|
+
TableName: tableName,
|
|
44
|
+
Key: {
|
|
45
|
+
_pk: key,
|
|
46
|
+
_sk: UNIQUE_CONSTRAINT_KEY,
|
|
47
|
+
},
|
|
48
|
+
}),
|
|
49
|
+
);
|
|
50
|
+
|
|
51
|
+
if (result.Item) {
|
|
52
|
+
logger.debug("Found existing constraint:", result.Item);
|
|
53
|
+
if (!currentId || result.Item.relatedId !== currentId) {
|
|
54
|
+
throw new Error(`${constraint.field} must be unique`);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
} catch (innerError) {
|
|
58
|
+
if (innerError.message.includes("must be unique")) {
|
|
59
|
+
throw innerError;
|
|
60
|
+
}
|
|
61
|
+
console.error("Error checking unique constraint:", innerError);
|
|
62
|
+
throw new Error(`Failed to validate ${constraint.field} uniqueness`);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
},
|
|
66
|
+
|
|
67
|
+
async _createUniqueConstraint(field, value, relatedId, constraintId) {
|
|
68
|
+
const testId = this.manager.getTestId();
|
|
69
|
+
const key = this._formatUniqueConstraintKey.call(
|
|
70
|
+
this,
|
|
71
|
+
constraintId,
|
|
72
|
+
this.modelPrefix,
|
|
73
|
+
field,
|
|
74
|
+
value,
|
|
75
|
+
);
|
|
76
|
+
|
|
77
|
+
let item = {
|
|
78
|
+
_pk: key,
|
|
79
|
+
_sk: UNIQUE_CONSTRAINT_KEY,
|
|
80
|
+
uniqueValue: key,
|
|
81
|
+
relatedId: relatedId,
|
|
82
|
+
relatedModel: this.name,
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
if (testId) {
|
|
86
|
+
item._gsi_test_id = testId;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
return {
|
|
90
|
+
Put: {
|
|
91
|
+
TableName: this.table,
|
|
92
|
+
Item: item,
|
|
93
|
+
ConditionExpression:
|
|
94
|
+
"attribute_not_exists(#pk) OR (relatedId = :relatedId AND relatedModel = :modelName)",
|
|
95
|
+
ExpressionAttributeNames: {
|
|
96
|
+
"#pk": "_pk",
|
|
97
|
+
},
|
|
98
|
+
ExpressionAttributeValues: {
|
|
99
|
+
":relatedId": relatedId,
|
|
100
|
+
":modelName": this.name,
|
|
101
|
+
},
|
|
102
|
+
},
|
|
103
|
+
};
|
|
104
|
+
},
|
|
105
|
+
|
|
106
|
+
async _removeUniqueConstraint(field, value, relatedId, constraintId) {
|
|
107
|
+
return {
|
|
108
|
+
Delete: {
|
|
109
|
+
TableName: this.table,
|
|
110
|
+
Key: {
|
|
111
|
+
_pk: this._formatUniqueConstraintKey.call(
|
|
112
|
+
this,
|
|
113
|
+
constraintId,
|
|
114
|
+
this.modelPrefix,
|
|
115
|
+
field,
|
|
116
|
+
value,
|
|
117
|
+
),
|
|
118
|
+
_sk: UNIQUE_CONSTRAINT_KEY,
|
|
119
|
+
},
|
|
120
|
+
ConditionExpression:
|
|
121
|
+
"relatedId = :relatedId AND relatedModel = :modelName",
|
|
122
|
+
ExpressionAttributeValues: {
|
|
123
|
+
":relatedId": relatedId,
|
|
124
|
+
":modelName": this.name,
|
|
125
|
+
},
|
|
126
|
+
},
|
|
127
|
+
};
|
|
128
|
+
},
|
|
129
|
+
};
|
|
130
|
+
|
|
131
|
+
module.exports = UniqueConstraintMethods;
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
const { defaultLogger: logger } = require("../utils/logger");
|
|
2
|
+
const { TtlFieldClass } = require("../fields");
|
|
3
|
+
const { PrimaryKeyConfig } = require("../model-config");
|
|
4
|
+
const {
|
|
5
|
+
GSI_INDEX_ID1,
|
|
6
|
+
GSI_INDEX_ID2,
|
|
7
|
+
GSI_INDEX_ID3,
|
|
8
|
+
UNIQUE_CONSTRAINT_ID1,
|
|
9
|
+
UNIQUE_CONSTRAINT_ID2,
|
|
10
|
+
UNIQUE_CONSTRAINT_ID3,
|
|
11
|
+
} = require("../constants");
|
|
12
|
+
|
|
13
|
+
const ValidationMethods = {
|
|
14
|
+
/**
|
|
15
|
+
*
|
|
16
|
+
* @function _validateConfiguration
|
|
17
|
+
*@memberof BaoModel
|
|
18
|
+
* @private
|
|
19
|
+
* @throws {Error} If modelPrefix is not defined
|
|
20
|
+
* @throws {Error} If primaryKey is not defined
|
|
21
|
+
* @throws {Error} If TTL field is incorrectly named
|
|
22
|
+
* @throws {Error} If field names start with underscore
|
|
23
|
+
* @throws {Error} If index names start with underscore
|
|
24
|
+
* @throws {Error} If index IDs are invalid
|
|
25
|
+
* @throws {Error} If constraint IDs are invalid
|
|
26
|
+
*
|
|
27
|
+
* @example
|
|
28
|
+
* const model = new DynamoModel();
|
|
29
|
+
* model._validateConfiguration();
|
|
30
|
+
*
|
|
31
|
+
* @description
|
|
32
|
+
* Validates the model configuration. This is called by the code generator
|
|
33
|
+
* and should not need to be called directly.
|
|
34
|
+
*
|
|
35
|
+
* Performs the following validations:
|
|
36
|
+
* - Ensures modelPrefix is defined
|
|
37
|
+
* - Ensures primaryKey is defined
|
|
38
|
+
* - Validates TTL field naming
|
|
39
|
+
* - Ensures primary key fields are marked as required
|
|
40
|
+
* - Validates field naming conventions
|
|
41
|
+
* - Validates index configurations
|
|
42
|
+
* - Validates unique constraints
|
|
43
|
+
*/
|
|
44
|
+
_validateConfiguration() {
|
|
45
|
+
if (!this.modelPrefix) {
|
|
46
|
+
throw new Error(`${this.name} must define a modelPrefix`);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
if (!this.primaryKey) {
|
|
50
|
+
throw new Error(`${this.name} must define a primaryKey`);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// Update to use TtlFieldClass instead of TtlField
|
|
54
|
+
Object.entries(this.fields).forEach(([fieldName, field]) => {
|
|
55
|
+
if (field instanceof TtlFieldClass && fieldName !== "ttl") {
|
|
56
|
+
throw new Error(
|
|
57
|
+
`TtlField must be named 'ttl', found '${fieldName}' in ${this.name}`,
|
|
58
|
+
);
|
|
59
|
+
}
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
// Ensure primary key fields are required
|
|
63
|
+
const pkField = this._getField(this.primaryKey.pk);
|
|
64
|
+
if (!pkField.required) {
|
|
65
|
+
logger.warn(
|
|
66
|
+
`Warning: Primary key field '${this.primaryKey.pk}' in ${this.name} was not explicitly marked as required. Marking as required automatically.`,
|
|
67
|
+
);
|
|
68
|
+
pkField.required = true;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const skField = this._getField(this.primaryKey.sk);
|
|
72
|
+
if (!skField.required) {
|
|
73
|
+
logger.warn(
|
|
74
|
+
`Warning: Sort key field '${this.primaryKey.sk}' in ${this.name} was not explicitly marked as required. Marking as required automatically.`,
|
|
75
|
+
);
|
|
76
|
+
skField.required = true;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// Validate field names don't start with underscore
|
|
80
|
+
Object.keys(this.fields).forEach((fieldName) => {
|
|
81
|
+
if (fieldName.startsWith("_")) {
|
|
82
|
+
throw new Error(
|
|
83
|
+
`Field name '${fieldName}' in ${this.name} cannot start with underscore`,
|
|
84
|
+
);
|
|
85
|
+
}
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
const validIndexIds = [
|
|
89
|
+
GSI_INDEX_ID1,
|
|
90
|
+
GSI_INDEX_ID2,
|
|
91
|
+
GSI_INDEX_ID3,
|
|
92
|
+
undefined,
|
|
93
|
+
]; // undefined for PK-based indexes
|
|
94
|
+
|
|
95
|
+
// Validate index names and referenced fields
|
|
96
|
+
Object.entries(this.indexes).forEach(([indexName, index]) => {
|
|
97
|
+
// Check if index name starts with underscore
|
|
98
|
+
if (indexName.startsWith("_")) {
|
|
99
|
+
throw new Error(
|
|
100
|
+
`Index name '${indexName}' in ${this.name} cannot start with underscore`,
|
|
101
|
+
);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// Check if referenced fields start with underscore
|
|
105
|
+
if (index.pk !== "modelPrefix" && index.pk.startsWith("_")) {
|
|
106
|
+
throw new Error(
|
|
107
|
+
`Index '${indexName}' references invalid field '${index.pk}' (cannot start with underscore)`,
|
|
108
|
+
);
|
|
109
|
+
}
|
|
110
|
+
if (index.sk !== "modelPrefix" && index.sk.startsWith("_")) {
|
|
111
|
+
throw new Error(
|
|
112
|
+
`Index '${indexName}' references invalid field '${index.sk}' (cannot start with underscore)`,
|
|
113
|
+
);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// Check if this index matches the primary key configuration
|
|
117
|
+
const isPrimaryKeyIndex =
|
|
118
|
+
index instanceof PrimaryKeyConfig &&
|
|
119
|
+
index.pk === this.primaryKey.pk &&
|
|
120
|
+
index.sk === this.primaryKey.sk;
|
|
121
|
+
|
|
122
|
+
if (!validIndexIds.includes(index.indexId) && !isPrimaryKeyIndex) {
|
|
123
|
+
throw new Error(`Invalid index ID ${index.indexId} in ${this.name}`);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// These will throw errors if the fields don't exist
|
|
127
|
+
const idxPkField = this._getField(index.pk);
|
|
128
|
+
const idxSkField = this._getField(index.sk);
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
// Validate unique constraints
|
|
132
|
+
const validConstraintIds = [
|
|
133
|
+
UNIQUE_CONSTRAINT_ID1,
|
|
134
|
+
UNIQUE_CONSTRAINT_ID2,
|
|
135
|
+
UNIQUE_CONSTRAINT_ID3,
|
|
136
|
+
];
|
|
137
|
+
|
|
138
|
+
Object.values(this.uniqueConstraints || {}).forEach((constraint) => {
|
|
139
|
+
if (!validConstraintIds.includes(constraint.constraintId)) {
|
|
140
|
+
throw new Error(
|
|
141
|
+
`Invalid constraint ID ${constraint.constraintId} in ${this.name}`,
|
|
142
|
+
);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
if (!this._getField(constraint.field)) {
|
|
146
|
+
throw new Error(
|
|
147
|
+
`Unique constraint field '${constraint.field}' not found in ${this.name} fields`,
|
|
148
|
+
);
|
|
149
|
+
}
|
|
150
|
+
});
|
|
151
|
+
},
|
|
152
|
+
};
|
|
153
|
+
|
|
154
|
+
module.exports = ValidationMethods;
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
class PrimaryKeyConfig {
|
|
2
|
+
constructor(pk, sk = "modelPrefix") {
|
|
3
|
+
this.pk = pk;
|
|
4
|
+
this.sk = sk;
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
getPkFieldName() {
|
|
8
|
+
return "_pk";
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
getSkFieldName() {
|
|
12
|
+
return "_sk";
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
class IndexConfig {
|
|
17
|
+
constructor(pk, sk, indexId) {
|
|
18
|
+
this.pk = pk;
|
|
19
|
+
this.sk = sk;
|
|
20
|
+
this.indexId = indexId;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
getIndexName() {
|
|
24
|
+
return this.indexId;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
getPkFieldName() {
|
|
28
|
+
return `_${this.indexId}_pk`;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
getSkFieldName() {
|
|
32
|
+
return `_${this.indexId}_sk`;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
class UniqueConstraintConfig {
|
|
37
|
+
constructor(field, constraintId) {
|
|
38
|
+
this.field = field;
|
|
39
|
+
this.constraintId = constraintId;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
module.exports = {
|
|
44
|
+
PrimaryKeyConfig,
|
|
45
|
+
IndexConfig,
|
|
46
|
+
UniqueConstraintConfig,
|
|
47
|
+
};
|