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
package/src/model.js
ADDED
|
@@ -0,0 +1,689 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @description
|
|
3
|
+
* This module contains the core functionality for models in Bao.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
const { RelatedFieldClass, StringField } = require("./fields");
|
|
7
|
+
const { ModelManager } = require("./model-manager");
|
|
8
|
+
const { defaultLogger: logger } = require("./utils/logger");
|
|
9
|
+
const { ObjectNotFound } = require("./object-not-found");
|
|
10
|
+
const ValidationMethods = require("./mixins/validation-mixin");
|
|
11
|
+
const UniqueConstraintMethods = require("./mixins/unique-constraint-mixin");
|
|
12
|
+
const QueryMethods = require("./mixins/query-mixin");
|
|
13
|
+
const MutationMethods = require("./mixins/mutation-mixin");
|
|
14
|
+
const {
|
|
15
|
+
BatchLoadingMethods,
|
|
16
|
+
BATCH_REQUESTS,
|
|
17
|
+
BATCH_REQUEST_TIMEOUT,
|
|
18
|
+
} = require("./mixins/batch-loading-mixin");
|
|
19
|
+
|
|
20
|
+
const {
|
|
21
|
+
PrimaryKeyConfig,
|
|
22
|
+
IndexConfig,
|
|
23
|
+
UniqueConstraintConfig,
|
|
24
|
+
} = require("./model-config");
|
|
25
|
+
|
|
26
|
+
const GID_SEPARATOR = "##__SK__##";
|
|
27
|
+
const { UNIQUE_CONSTRAINT_KEY, SYSTEM_FIELDS } = require("./constants");
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* @description
|
|
31
|
+
* Base model that implements core functionality for all models. Do not instantiate
|
|
32
|
+
* this class directly, instead use a subclass, usually that has been generated
|
|
33
|
+
* by the code generator.
|
|
34
|
+
*/
|
|
35
|
+
class BaoModel {
|
|
36
|
+
static _testId = null;
|
|
37
|
+
static table = null;
|
|
38
|
+
static documentClient = null;
|
|
39
|
+
|
|
40
|
+
// These should be overridden by child classes
|
|
41
|
+
static modelPrefix = null;
|
|
42
|
+
static fields = {};
|
|
43
|
+
static primaryKey = null;
|
|
44
|
+
static indexes = {};
|
|
45
|
+
static uniqueConstraints = {};
|
|
46
|
+
|
|
47
|
+
static defaultQueryLimit = 100;
|
|
48
|
+
|
|
49
|
+
static {
|
|
50
|
+
// Initialize methods
|
|
51
|
+
Object.assign(BaoModel, ValidationMethods);
|
|
52
|
+
Object.assign(BaoModel, UniqueConstraintMethods);
|
|
53
|
+
Object.assign(BaoModel, QueryMethods);
|
|
54
|
+
Object.assign(BaoModel, MutationMethods);
|
|
55
|
+
Object.assign(BaoModel, BatchLoadingMethods);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* @description
|
|
60
|
+
* ONLY use this for testing. It allows tests to run in isolation and
|
|
61
|
+
* prevent data from being shared between tests/tests to run in parallel.
|
|
62
|
+
* However, it should not be used outside of this context. For examples,
|
|
63
|
+
* showing how to use this, see the tests.
|
|
64
|
+
* @param {string} testId - The ID of the test.
|
|
65
|
+
*/
|
|
66
|
+
static setTestId(testId) {
|
|
67
|
+
this._testId = testId;
|
|
68
|
+
const manager = ModelManager.getInstance(testId);
|
|
69
|
+
this.documentClient = manager.documentClient;
|
|
70
|
+
this.table = manager.tableName;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
static get manager() {
|
|
74
|
+
return ModelManager.getInstance(this._testId);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
static _getField(fieldName) {
|
|
78
|
+
let fieldDef;
|
|
79
|
+
if (SYSTEM_FIELDS.includes(fieldName) || fieldName === "modelPrefix") {
|
|
80
|
+
fieldDef = StringField();
|
|
81
|
+
} else {
|
|
82
|
+
fieldDef = this.fields[fieldName];
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
if (!fieldDef) {
|
|
86
|
+
throw new Error(`Field ${fieldName} not found in ${this.name} fields`);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
return fieldDef;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
static _getPkValue(data) {
|
|
93
|
+
if (!data) {
|
|
94
|
+
throw new Error("Data object is required for static _getPkValue call");
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const pkValue =
|
|
98
|
+
this.primaryKey.pk === "modelPrefix"
|
|
99
|
+
? this.modelPrefix
|
|
100
|
+
: data[this.primaryKey.pk];
|
|
101
|
+
|
|
102
|
+
logger.debug("_getPkValue", pkValue);
|
|
103
|
+
|
|
104
|
+
return pkValue;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
static _getSkValue(data) {
|
|
108
|
+
if (!data) {
|
|
109
|
+
throw new Error("Data object is required for static _getSkValue call");
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
if (this.primaryKey.sk === "modelPrefix") {
|
|
113
|
+
return this.modelPrefix;
|
|
114
|
+
}
|
|
115
|
+
return data[this.primaryKey.sk];
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
_getPkValue() {
|
|
119
|
+
return this.constructor._getPkValue(this._dyData);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
_getSkValue() {
|
|
123
|
+
return this.constructor._getSkValue(this._dyData);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
static _formatGsiKey(modelPrefix, indexId, value) {
|
|
127
|
+
const testId = this.manager.getTestId();
|
|
128
|
+
const baseKey = `${modelPrefix}#${indexId}#${value}`;
|
|
129
|
+
return testId ? `[${testId}]#${baseKey}` : baseKey;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
static _formatPrimaryKey(modelPrefix, value) {
|
|
133
|
+
const testId = this.manager.getTestId();
|
|
134
|
+
const baseKey = `${modelPrefix}#${value}`;
|
|
135
|
+
return testId ? `[${testId}]#${baseKey}` : baseKey;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
static _formatUniqueConstraintKey(constraintId, modelPrefix, field, value) {
|
|
139
|
+
const testId = this.manager.getTestId();
|
|
140
|
+
const baseKey = `${UNIQUE_CONSTRAINT_KEY}#${constraintId}#${modelPrefix}#${field}:${value}`;
|
|
141
|
+
return testId ? `[${testId}]#${baseKey}` : baseKey;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
static _getDyKeyForPkSk(pkSk) {
|
|
145
|
+
if (this.primaryKey.sk === "modelPrefix") {
|
|
146
|
+
return {
|
|
147
|
+
_pk: this._formatPrimaryKey(this.modelPrefix, pkSk.pk),
|
|
148
|
+
_sk: this.modelPrefix,
|
|
149
|
+
};
|
|
150
|
+
} else if (this.primaryKey.pk === "modelPrefix") {
|
|
151
|
+
return {
|
|
152
|
+
_pk: this.modelPrefix,
|
|
153
|
+
_sk: pkSk.sk,
|
|
154
|
+
};
|
|
155
|
+
} else {
|
|
156
|
+
return {
|
|
157
|
+
_pk: this._formatPrimaryKey(this.modelPrefix, pkSk.pk),
|
|
158
|
+
_sk: pkSk.sk,
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* @description
|
|
165
|
+
* Create a new model instance.
|
|
166
|
+
* @param {Object} [jsData] - The initial data for the model.
|
|
167
|
+
*/
|
|
168
|
+
constructor(jsData = {}) {
|
|
169
|
+
this._dyData = {};
|
|
170
|
+
SYSTEM_FIELDS.forEach((key) => {
|
|
171
|
+
if (jsData[key] !== undefined) {
|
|
172
|
+
this._dyData[key] = jsData[key];
|
|
173
|
+
}
|
|
174
|
+
});
|
|
175
|
+
|
|
176
|
+
this._loadedDyData = {};
|
|
177
|
+
this._changes = new Set();
|
|
178
|
+
this._relatedObjects = {};
|
|
179
|
+
this._consumedCapacity = [];
|
|
180
|
+
|
|
181
|
+
// Initialize fields with data
|
|
182
|
+
Object.entries(this.constructor.fields).forEach(([fieldName, field]) => {
|
|
183
|
+
// Convert initial value to DynamoDB format
|
|
184
|
+
let value =
|
|
185
|
+
jsData[fieldName] === undefined
|
|
186
|
+
? field.getInitialValue()
|
|
187
|
+
: jsData[fieldName];
|
|
188
|
+
this._dyData[fieldName] = field.toDy(value);
|
|
189
|
+
|
|
190
|
+
// Define property getter/setter that always works with _dyData
|
|
191
|
+
Object.defineProperty(this, fieldName, {
|
|
192
|
+
get: () => field.fromDy(this._dyData[fieldName]),
|
|
193
|
+
set: (newValue) => {
|
|
194
|
+
const oldDyValue = this._dyData[fieldName];
|
|
195
|
+
const newDyValue = field.toDy(newValue);
|
|
196
|
+
if (newDyValue !== oldDyValue) {
|
|
197
|
+
this._dyData[fieldName] = newDyValue;
|
|
198
|
+
this._changes.add(fieldName);
|
|
199
|
+
if (field instanceof RelatedFieldClass) {
|
|
200
|
+
delete this._relatedObjects[fieldName];
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
},
|
|
204
|
+
});
|
|
205
|
+
});
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
static _createFromDyItem(dyItem) {
|
|
209
|
+
const newObj = new this();
|
|
210
|
+
newObj._dyData = dyItem;
|
|
211
|
+
newObj._resetChangeTracking();
|
|
212
|
+
|
|
213
|
+
logger.debug("_createFromDyItem", dyItem, newObj);
|
|
214
|
+
logger.debug("_createFromDyItem.name", newObj.name);
|
|
215
|
+
return newObj;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* @description
|
|
220
|
+
* Clear the related cache for a given field.
|
|
221
|
+
* @param {string} fieldName - The name of the field to clear.
|
|
222
|
+
*/
|
|
223
|
+
clearRelatedCache(fieldName) {
|
|
224
|
+
delete this._relatedObjects[fieldName];
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
// Returns the pk and sk values for a given object. These are encoded to work with
|
|
228
|
+
// dynamo string keys. No test prefix or model prefix is applied.
|
|
229
|
+
static _getPrimaryKeyValues(data) {
|
|
230
|
+
if (!data) {
|
|
231
|
+
throw new Error("Data object is required for _getPrimaryKeyValues call");
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
const pkField = this._getField(this.primaryKey.pk);
|
|
235
|
+
const skField = this._getField(this.primaryKey.sk);
|
|
236
|
+
|
|
237
|
+
if (skField === undefined && this.primaryKey.sk !== "modelPrefix") {
|
|
238
|
+
throw new Error(`SK field is required for getPkSk call`);
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
if (pkField === undefined && this.primaryKey.pk !== "modelPrefix") {
|
|
242
|
+
throw new Error(`PK field is required for getPkSk call`);
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
// If the field is set, use the GSI value, otherwise use the raw value
|
|
246
|
+
const pkValue = pkField
|
|
247
|
+
? pkField.toGsi(this._getPkValue(data))
|
|
248
|
+
: this._getPkValue(data);
|
|
249
|
+
const skValue = skField
|
|
250
|
+
? skField.toGsi(this._getSkValue(data))
|
|
251
|
+
: this._getSkValue(data);
|
|
252
|
+
|
|
253
|
+
if (
|
|
254
|
+
pkValue === undefined ||
|
|
255
|
+
skValue === undefined ||
|
|
256
|
+
pkValue === null ||
|
|
257
|
+
skValue === null
|
|
258
|
+
) {
|
|
259
|
+
throw new Error(`PK and SK must be defined to get a PkSk`);
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
let key = {
|
|
263
|
+
pk: pkValue,
|
|
264
|
+
sk: skValue,
|
|
265
|
+
};
|
|
266
|
+
|
|
267
|
+
logger.debug("_getPrimaryKeyValues", key);
|
|
268
|
+
|
|
269
|
+
return key;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/**
|
|
273
|
+
* @description
|
|
274
|
+
* Static version of {@link BaoModel#getPrimaryId}.
|
|
275
|
+
* @param {Object} data - The data object to get the primary ID for.
|
|
276
|
+
* @returns {string} The primary ID.
|
|
277
|
+
*/
|
|
278
|
+
static getPrimaryId(data) {
|
|
279
|
+
logger.debug("getPrimaryId", data);
|
|
280
|
+
const pkSk = this._getPrimaryKeyValues(data);
|
|
281
|
+
logger.debug("getPrimaryId", pkSk);
|
|
282
|
+
|
|
283
|
+
let primaryId;
|
|
284
|
+
if (this.primaryKey.pk === "modelPrefix") {
|
|
285
|
+
primaryId = pkSk.sk;
|
|
286
|
+
} else if (this.primaryKey.sk === "modelPrefix") {
|
|
287
|
+
primaryId = pkSk.pk;
|
|
288
|
+
} else {
|
|
289
|
+
primaryId = pkSk.pk + GID_SEPARATOR + pkSk.sk;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
return primaryId;
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/**
|
|
296
|
+
* @description
|
|
297
|
+
* Get the primary ID for a given object. This is a string that uniquely
|
|
298
|
+
* identifies the object in the database. When using {@link BaoModel.find},
|
|
299
|
+
* this is the id to use. Do not make assumptions about how this id
|
|
300
|
+
* is formatted since it will depend on the model key structure.
|
|
301
|
+
* @returns {string} The primary ID.
|
|
302
|
+
*/
|
|
303
|
+
getPrimaryId() {
|
|
304
|
+
return this.constructor.getPrimaryId(this._dyData);
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
static _parsePrimaryId(primaryId) {
|
|
308
|
+
if (!primaryId) {
|
|
309
|
+
throw new Error("Primary ID is required to parse");
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
if (primaryId.indexOf(GID_SEPARATOR) !== -1) {
|
|
313
|
+
const [pk, sk] = primaryId.split(GID_SEPARATOR);
|
|
314
|
+
return { pk, sk };
|
|
315
|
+
} else {
|
|
316
|
+
if (this.primaryKey.pk === "modelPrefix") {
|
|
317
|
+
return { pk: this.modelPrefix, sk: primaryId };
|
|
318
|
+
} else if (this.primaryKey.sk === "modelPrefix") {
|
|
319
|
+
return { pk: primaryId, sk: this.modelPrefix };
|
|
320
|
+
} else {
|
|
321
|
+
throw new Error(`Invalid primary ID: ${primaryId}`);
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
// Get all data - convert from Dynamo to JS format
|
|
327
|
+
_getAllData() {
|
|
328
|
+
const allData = {};
|
|
329
|
+
for (const [fieldName, field] of Object.entries(this.constructor.fields)) {
|
|
330
|
+
allData[fieldName] = field.fromDy(this._dyData[fieldName]);
|
|
331
|
+
}
|
|
332
|
+
return allData;
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
// Get only changed fields - convert from Dynamo to JS format
|
|
336
|
+
_getChanges() {
|
|
337
|
+
const changes = {};
|
|
338
|
+
logger.debug("_changes Set contains:", Array.from(this._changes));
|
|
339
|
+
for (const field of this._changes) {
|
|
340
|
+
const fieldDef = this.constructor._getField(field);
|
|
341
|
+
logger.debug("Field definition for", field, ":", {
|
|
342
|
+
type: fieldDef.constructor.name,
|
|
343
|
+
field: fieldDef,
|
|
344
|
+
});
|
|
345
|
+
const dyValue = this._dyData[field];
|
|
346
|
+
logger.debug("Converting value:", {
|
|
347
|
+
field,
|
|
348
|
+
dyValue,
|
|
349
|
+
fromDyExists: typeof fieldDef.fromDy === "function",
|
|
350
|
+
});
|
|
351
|
+
changes[field] = fieldDef.fromDy(dyValue);
|
|
352
|
+
}
|
|
353
|
+
return changes;
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
/**
|
|
357
|
+
* @description
|
|
358
|
+
* Returns true if any fields have been modified since the object was last
|
|
359
|
+
* loaded from the database.
|
|
360
|
+
* @returns {boolean} True if there are changes, false otherwise.
|
|
361
|
+
*/
|
|
362
|
+
hasChanges() {
|
|
363
|
+
return this._changes.size > 0;
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/**
|
|
367
|
+
* @description
|
|
368
|
+
* Returns true if the object has been loaded from the database.
|
|
369
|
+
* @returns {boolean} True if the object has been loaded, false otherwise.
|
|
370
|
+
*/
|
|
371
|
+
isLoaded() {
|
|
372
|
+
return Object.keys(this._loadedDyData).length > 0;
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
// Reset tracking after successful save
|
|
376
|
+
_resetChangeTracking() {
|
|
377
|
+
this._loadedDyData = { ...this._dyData };
|
|
378
|
+
this._changes.clear();
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
/**
|
|
382
|
+
* @description
|
|
383
|
+
* Save the current object to the database. This operation will diff the current
|
|
384
|
+
* state of the object with the state that has been loaded from dynamo to
|
|
385
|
+
* determine which changes need to be saved.
|
|
386
|
+
*
|
|
387
|
+
* @param {Object} [options] - Additional options for the save operation.
|
|
388
|
+
* @param {Object} [options.constraints={}] - Constraints to validate. Options are:
|
|
389
|
+
* @param {boolean} [options.constraints.mustExist=false] - Whether the item must exist.
|
|
390
|
+
* @param {boolean} [options.constraints.mustNotExist=false] - Whether the item must not exist.
|
|
391
|
+
* @param {string[]} [options.constraints.fieldMatches=[]] - An array of field names that must match
|
|
392
|
+
* the current item's loaded state. This is often used for optimistic locking in conjunction
|
|
393
|
+
* with a {@link BaoFields.VersionField} field.
|
|
394
|
+
* @returns {Promise<Object>} Returns a promise that resolves to the updated item.
|
|
395
|
+
*/
|
|
396
|
+
async save(options = {}) {
|
|
397
|
+
if (!this.hasChanges() && this.isLoaded()) {
|
|
398
|
+
logger.debug("save() - no changes to save");
|
|
399
|
+
return this; // No changes to save
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
let changes = null;
|
|
403
|
+
if (!this.isLoaded()) {
|
|
404
|
+
options.isNew = true;
|
|
405
|
+
changes = this._getAllData();
|
|
406
|
+
} else {
|
|
407
|
+
changes = this._getChanges();
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
logger.debug("save() - changes", changes);
|
|
411
|
+
const updatedObj = await this.constructor.update(
|
|
412
|
+
this.getPrimaryId(),
|
|
413
|
+
changes,
|
|
414
|
+
{ instanceObj: this, ...options },
|
|
415
|
+
);
|
|
416
|
+
|
|
417
|
+
logger.debug("save() - updatedObj", updatedObj);
|
|
418
|
+
this._dyData = updatedObj._dyData;
|
|
419
|
+
logger.debug("save() - this", this);
|
|
420
|
+
|
|
421
|
+
// Reset change tracking after successful save
|
|
422
|
+
this._resetChangeTracking();
|
|
423
|
+
|
|
424
|
+
return this;
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
/**
|
|
428
|
+
* @description
|
|
429
|
+
* Get or load a related field. If the field is already loaded, it will be
|
|
430
|
+
* returned without reloading. Otherwise, it will be loaded from the database
|
|
431
|
+
* and returned.
|
|
432
|
+
* @param {string} fieldName - The name of the field to get or load.
|
|
433
|
+
* @param {Object} [loaderContext] - Cache context for storing and retrieving items across requests.
|
|
434
|
+
* @returns {Promise<Object>} Returns a promise that resolves to the loaded item.
|
|
435
|
+
*/
|
|
436
|
+
async getOrLoadRelatedField(fieldName, loaderContext = null) {
|
|
437
|
+
if (this._relatedObjects[fieldName]) {
|
|
438
|
+
return this._relatedObjects[fieldName];
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
const field = this.constructor.fields[fieldName];
|
|
442
|
+
if (!field || !field.modelName) {
|
|
443
|
+
throw new Error(`Field ${fieldName} is not a valid relation field`);
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
const value = this[fieldName];
|
|
447
|
+
if (!value) return null;
|
|
448
|
+
|
|
449
|
+
const ModelClass = this.constructor.manager.getModel(field.modelName);
|
|
450
|
+
this._relatedObjects[fieldName] = await ModelClass.find(value, {
|
|
451
|
+
loaderContext,
|
|
452
|
+
});
|
|
453
|
+
return this._relatedObjects[fieldName];
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
/**
|
|
457
|
+
* @description
|
|
458
|
+
* Load objects for RelatedField's on the current model instance.
|
|
459
|
+
* @param {string[]} [fieldNames] - The names of the fields to load. If not provided, all related fields will be loaded.
|
|
460
|
+
* @param {Object} [loaderContext] - Cache context for storing and retrieving items across requests.
|
|
461
|
+
* @returns {Promise<Object>} Returns a promise that resolves to the loaded items and their consumed capacity
|
|
462
|
+
*/
|
|
463
|
+
async loadRelatedData(fieldNames = null, loaderContext = null) {
|
|
464
|
+
const promises = [];
|
|
465
|
+
|
|
466
|
+
for (const [fieldName, field] of Object.entries(this.constructor.fields)) {
|
|
467
|
+
if (fieldNames && !fieldNames.includes(fieldName)) {
|
|
468
|
+
continue;
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
if (field instanceof RelatedFieldClass && this[fieldName]) {
|
|
472
|
+
promises.push(
|
|
473
|
+
this._loadRelatedField(fieldName, field, loaderContext).then(
|
|
474
|
+
(instance) => {
|
|
475
|
+
this._relatedObjects[fieldName] = instance;
|
|
476
|
+
},
|
|
477
|
+
),
|
|
478
|
+
);
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
await Promise.all(promises);
|
|
483
|
+
return this;
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
async _loadRelatedField(fieldName, field, loaderContext = null) {
|
|
487
|
+
const value = this[fieldName];
|
|
488
|
+
if (!value) return null;
|
|
489
|
+
|
|
490
|
+
const ModelClass = this.constructor.manager.getModel(field.modelName);
|
|
491
|
+
|
|
492
|
+
if (value instanceof ModelClass) {
|
|
493
|
+
return value;
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
// Load the instance and track its capacity
|
|
497
|
+
const relatedInstance = await ModelClass.find(value, { loaderContext });
|
|
498
|
+
|
|
499
|
+
return relatedInstance;
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
/**
|
|
503
|
+
* @description
|
|
504
|
+
* Get a related field. If the field is not loaded, it will return null.
|
|
505
|
+
* @param {string} fieldName - The name of the field to get.
|
|
506
|
+
* @returns {Object} The related field.
|
|
507
|
+
*/
|
|
508
|
+
getRelated(fieldName) {
|
|
509
|
+
const field = this.constructor.fields[fieldName];
|
|
510
|
+
if (!(field instanceof RelatedFieldClass)) {
|
|
511
|
+
throw new Error(`Field ${fieldName} is not a RelatedField`);
|
|
512
|
+
}
|
|
513
|
+
return this._relatedObjects[fieldName];
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
/**
|
|
517
|
+
* @description
|
|
518
|
+
* Find an object by a unique constraint. Any unique constraint can also be used
|
|
519
|
+
* to find an object.
|
|
520
|
+
* @param {string} constraintName - The name of the unique constraint to use.
|
|
521
|
+
* @param {string} value - The value of the unique constraint.
|
|
522
|
+
* @param {Object} [loaderContext] - Cache context for storing and retrieving items across requests.
|
|
523
|
+
* @returns {Promise<Object>} Returns a promise that resolves to the found item.
|
|
524
|
+
*/
|
|
525
|
+
static async findByUniqueConstraint(
|
|
526
|
+
constraintName,
|
|
527
|
+
value,
|
|
528
|
+
loaderContext = null,
|
|
529
|
+
) {
|
|
530
|
+
const constraint = this.uniqueConstraints[constraintName];
|
|
531
|
+
if (!constraint) {
|
|
532
|
+
throw new Error(
|
|
533
|
+
`Unknown unique constraint '${constraintName}' in ${this.name}`,
|
|
534
|
+
);
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
if (!value) {
|
|
538
|
+
throw new Error(`${constraint.field} value is required`);
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
const key = this._formatUniqueConstraintKey(
|
|
542
|
+
constraint.constraintId,
|
|
543
|
+
this.modelPrefix,
|
|
544
|
+
constraint.field,
|
|
545
|
+
value,
|
|
546
|
+
);
|
|
547
|
+
|
|
548
|
+
const result = await this.documentClient.get({
|
|
549
|
+
TableName: this.table,
|
|
550
|
+
Key: {
|
|
551
|
+
_pk: key,
|
|
552
|
+
_sk: UNIQUE_CONSTRAINT_KEY,
|
|
553
|
+
},
|
|
554
|
+
ReturnConsumedCapacity: "TOTAL",
|
|
555
|
+
});
|
|
556
|
+
|
|
557
|
+
if (!result.Item) {
|
|
558
|
+
return new ObjectNotFound(result.ConsumedCapacity);
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
const item = await this.find(result.Item.relatedId, { loaderContext });
|
|
562
|
+
|
|
563
|
+
if (item) {
|
|
564
|
+
item._addConsumedCapacity(result.ConsumedCapacity);
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
return item;
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
/**
|
|
571
|
+
* @description
|
|
572
|
+
* Returns true if the object exists. This is particularly useful when checking
|
|
573
|
+
* if an object has been found, since ObjectNotFound will be returned
|
|
574
|
+
* rather than null if an object is not found (so capacity information
|
|
575
|
+
* will also be returned).
|
|
576
|
+
* @returns {boolean} True if the object exists, false otherwise.
|
|
577
|
+
*/
|
|
578
|
+
exists() {
|
|
579
|
+
return true;
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
_setConsumedCapacity(capacity, type = "read", fromContext = false) {
|
|
583
|
+
this.clearConsumedCapacity();
|
|
584
|
+
this._addConsumedCapacity(capacity, type, fromContext);
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
_addConsumedCapacity(capacity, type = "read", fromContext = false) {
|
|
588
|
+
if (type !== "read" && type !== "write" && type !== "total") {
|
|
589
|
+
throw new Error(`Invalid consumed capacity type: ${type}`);
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
if (!capacity) {
|
|
593
|
+
return;
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
if (Array.isArray(capacity)) {
|
|
597
|
+
capacity.forEach((item) =>
|
|
598
|
+
this._addConsumedCapacity(item, type, fromContext),
|
|
599
|
+
);
|
|
600
|
+
} else {
|
|
601
|
+
if (capacity.consumedCapacity) {
|
|
602
|
+
this._consumedCapacity.push({
|
|
603
|
+
consumedCapacity: capacity.consumedCapacity,
|
|
604
|
+
fromContext: capacity.fromContext || fromContext,
|
|
605
|
+
type: capacity.type || type,
|
|
606
|
+
});
|
|
607
|
+
} else {
|
|
608
|
+
this._consumedCapacity.push({
|
|
609
|
+
consumedCapacity: capacity,
|
|
610
|
+
fromContext: fromContext,
|
|
611
|
+
type: type,
|
|
612
|
+
});
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
/**
|
|
618
|
+
* Get the number of RCU/WCU consumed by a model instance. Additional capacity
|
|
619
|
+
* is added every time a new operation (finding, saving, loading related data)
|
|
620
|
+
* is performed on the instance. You can reset the consumed capacity by calling
|
|
621
|
+
* {@link BaoModel#clearConsumedCapacity}.
|
|
622
|
+
* @param {string} type - Either "read", "write", or "total".
|
|
623
|
+
* @param {boolean} [includeRelated=false] - Whether to include capacity from related objects.
|
|
624
|
+
* @returns {number} The numeric consumed capacity.
|
|
625
|
+
*/
|
|
626
|
+
getNumericConsumedCapacity(type, includeRelated = false) {
|
|
627
|
+
if (type !== "read" && type !== "write" && type !== "total") {
|
|
628
|
+
throw new Error(`Invalid consumed capacitytype: ${type}`);
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
let consumedCapacity = this._consumedCapacity;
|
|
632
|
+
if (!consumedCapacity) {
|
|
633
|
+
consumedCapacity = [];
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
let total = consumedCapacity.reduce((sum, capacity) => {
|
|
637
|
+
if (
|
|
638
|
+
!capacity.fromContext &&
|
|
639
|
+
(capacity.type === type || type === "total")
|
|
640
|
+
) {
|
|
641
|
+
return sum + (capacity.consumedCapacity?.CapacityUnits || 0);
|
|
642
|
+
}
|
|
643
|
+
return sum;
|
|
644
|
+
}, 0);
|
|
645
|
+
|
|
646
|
+
if (includeRelated) {
|
|
647
|
+
// Sum up capacity from any loaded related objects
|
|
648
|
+
for (const relatedObj of Object.values(this._relatedObjects)) {
|
|
649
|
+
if (relatedObj) {
|
|
650
|
+
const relatedCapacity = relatedObj.getNumericConsumedCapacity(
|
|
651
|
+
type,
|
|
652
|
+
true,
|
|
653
|
+
);
|
|
654
|
+
total += relatedCapacity;
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
return total;
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
/**
|
|
663
|
+
* @description
|
|
664
|
+
* Get the consumed capacity for the current model instance. Every entry
|
|
665
|
+
* in this array will represent a separate operation.
|
|
666
|
+
* @returns {Object[]} The consumed capacity.
|
|
667
|
+
*/
|
|
668
|
+
getConsumedCapacity() {
|
|
669
|
+
return this._consumedCapacity;
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
/**
|
|
673
|
+
* @description
|
|
674
|
+
* Clear the consumed capacity for the current model instance.
|
|
675
|
+
*/
|
|
676
|
+
clearConsumedCapacity() {
|
|
677
|
+
this._consumedCapacity = [];
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
module.exports = {
|
|
682
|
+
BaoModel,
|
|
683
|
+
PrimaryKeyConfig: (pk, sk) => new PrimaryKeyConfig(pk, sk),
|
|
684
|
+
IndexConfig: (pk, sk, indexId) => new IndexConfig(pk, sk, indexId),
|
|
685
|
+
UniqueConstraintConfig: (field, constraintId) =>
|
|
686
|
+
new UniqueConstraintConfig(field, constraintId),
|
|
687
|
+
BATCH_REQUEST_TIMEOUT,
|
|
688
|
+
BATCH_REQUESTS,
|
|
689
|
+
};
|