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/src/fields.js ADDED
@@ -0,0 +1,781 @@
1
+ /**
2
+ * @namespace BaoFields
3
+ * @description
4
+ * This module contains the built-in fields for Bao.
5
+ */
6
+ const { ulid, decodeTime } = require("ulid");
7
+ const { defaultLogger: logger } = require("./utils/logger");
8
+
9
+ /**
10
+ * @class BaoBaseField
11
+ * @memberof BaoFields
12
+ * @description
13
+ * Base class for all fields. Do not instantiate this class directly.
14
+ */
15
+ class BaoBaseField {
16
+ constructor(options = {}) {
17
+ this.options = options;
18
+ this.required = options.required || false;
19
+ this.defaultValue = options.defaultValue;
20
+ }
21
+
22
+ /**
23
+ * @memberof BaoFields.BaoBaseField
24
+ * @description
25
+ * Get the initial JS value for the field.
26
+ * @returns {any} The initial value for the field.
27
+ */
28
+ getInitialValue() {
29
+ if (this.defaultValue) {
30
+ return typeof this.defaultValue === "function"
31
+ ? this.defaultValue()
32
+ : this.defaultValue;
33
+ }
34
+ return undefined;
35
+ }
36
+
37
+ /**
38
+ * @memberof BaoFields.BaoBaseField
39
+ * @description
40
+ * Validate the JS field value.
41
+ * @param {any} value - The value to validate.
42
+ * @returns {boolean} True if the value is valid, otherwise false.
43
+ */
44
+ validate(value) {
45
+ if (this.required && (value === null || value === undefined)) {
46
+ throw new Error("Field is required");
47
+ }
48
+ return true;
49
+ }
50
+
51
+ /**
52
+ * @memberof BaoFields.BaoBaseField
53
+ * @description
54
+ * Convert the field value from the JS representation to DynamoDB representation.
55
+ * @param {any} value - The value to convert.
56
+ * @returns {any} The converted value.
57
+ */
58
+ toDy(value) {
59
+ return value;
60
+ }
61
+
62
+ /**
63
+ * @memberof BaoFields.BaoBaseField
64
+ * @description
65
+ * Convert the field value from the DynamoDB representation to the JS representation.
66
+ * @param {any} value - The value to convert.
67
+ * @returns {any} The converted value.
68
+ */
69
+ fromDy(value) {
70
+ return value;
71
+ }
72
+
73
+ /**
74
+ * @memberof BaoFields.BaoBaseField
75
+ * @description
76
+ * Convert the field value from the JS representation the index format used by DynamoDB.
77
+ * This must be a string representation of the value. Pay special attention to
78
+ * how this value sorts since it will be used for sort keys.
79
+ * @param {any} value - The value to convert.
80
+ * @returns {any} The converted value.
81
+ */
82
+ toGsi(value) {
83
+ return String(value);
84
+ }
85
+
86
+ /**
87
+ * @memberof BaoFields.BaoBaseField
88
+ * @description
89
+ * Convert the field value from the index format used by DynamoDB to the JS representation.
90
+ * @param {any} value - The value to convert.
91
+ * @returns {any} The converted value.
92
+ */
93
+ fromGsi(value) {
94
+ return this.fromDy(value);
95
+ }
96
+
97
+ /**
98
+ * @memberof BaoFields.BaoBaseField
99
+ * @description
100
+ * Get the DynamoDB update expression for the field. You usually don't need to override this.
101
+ * By default, it will return a SET expression, unless the value is null. If the value is null,
102
+ * it will remove the attribute from the item .
103
+ *
104
+ * @param {string} fieldName - The name of the field.
105
+ * @param {any} value - The value to update.
106
+ * @returns {Object} The update expression.
107
+ */
108
+ getUpdateExpression(fieldName, value) {
109
+ if (value === undefined) return null;
110
+
111
+ const attributeName = `#${fieldName}`;
112
+ const attributeValue = `:${fieldName}`;
113
+
114
+ if (value === null) {
115
+ return {
116
+ type: "REMOVE",
117
+ expression: `${attributeName}`,
118
+ attrNameKey: attributeName,
119
+ attrValueKey: attributeValue,
120
+ fieldName: fieldName,
121
+ fieldValue: null,
122
+ };
123
+ }
124
+
125
+ return {
126
+ type: "SET",
127
+ expression: `${attributeName} = ${attributeValue}`,
128
+ attrNameKey: attributeName,
129
+ attrValueKey: attributeValue,
130
+ fieldName: fieldName,
131
+ fieldValue: value,
132
+ };
133
+ }
134
+
135
+ /**
136
+ * @memberof BaoFields.BaoBaseField
137
+ * @description
138
+ * Update the field value before saving. An example of where you might override this
139
+ * is a modified date field that you want to update to the current date/time before
140
+ * saving.
141
+ * @param {any} value - The value to update.
142
+ * @param {BaoModel} currentObject - The current model instance.
143
+ * @returns {any} The updated value.
144
+ */
145
+ updateBeforeSave(value, currentObject) {
146
+ // Default implementation does nothing
147
+ return value;
148
+ }
149
+ }
150
+
151
+ /**
152
+ * @class StringField
153
+ * @memberof BaoFields
154
+ * @description
155
+ * A field that stores a string value.
156
+ */
157
+ class StringField extends BaoBaseField {
158
+ // String fields are pass-through since DynamoDB handles them natively
159
+ }
160
+
161
+ /**
162
+ * @class DateTimeField
163
+ * @memberof BaoFields
164
+ * @description
165
+ * A field that stores a date/time value.
166
+ */
167
+ class DateTimeField extends BaoBaseField {
168
+ validate(value) {
169
+ if (this.required && value === undefined) {
170
+ throw new Error("Field is required");
171
+ }
172
+ if (
173
+ value !== undefined &&
174
+ !(value instanceof Date) &&
175
+ typeof value !== "number" &&
176
+ typeof value !== "string"
177
+ ) {
178
+ throw new Error(
179
+ "DateTimeField value must be a Date object, timestamp number, or ISO string",
180
+ );
181
+ }
182
+ }
183
+
184
+ toDy(value) {
185
+ if (!value) return null;
186
+
187
+ try {
188
+ // Convert any input to timestamp
189
+ if (value instanceof Date) {
190
+ return value.getTime();
191
+ }
192
+ if (typeof value === "string") {
193
+ return new Date(value).getTime();
194
+ }
195
+ if (typeof value === "number") {
196
+ return value;
197
+ }
198
+ return null;
199
+ } catch (error) {
200
+ console.warn("Error converting date value:", error);
201
+ return null;
202
+ }
203
+ }
204
+
205
+ fromDy(value) {
206
+ if (!value) return null;
207
+ try {
208
+ return new Date(Number(value));
209
+ } catch (error) {
210
+ console.warn("Error parsing date value:", error);
211
+ return null;
212
+ }
213
+ }
214
+
215
+ toGsi(value) {
216
+ if (!value) return "0";
217
+ try {
218
+ // Convert to timestamp string with padding for correct sorting
219
+ const timestamp = this.toDy(value);
220
+ if (!timestamp) return "0";
221
+ const result = timestamp.toString().padStart(20, "0");
222
+ // logger.log('Converting to GSI:', { value, timestamp, result });
223
+ return result;
224
+ } catch (error) {
225
+ console.warn("Error converting date for GSI:", error);
226
+ return "0";
227
+ }
228
+ }
229
+ }
230
+
231
+ /**
232
+ * @class IntegerField
233
+ * @memberof BaoFields
234
+ * @description
235
+ * A field that stores an integer value.
236
+ */
237
+ class IntegerField extends BaoBaseField {
238
+ getInitialValue() {
239
+ return this.options.defaultValue !== undefined
240
+ ? this.options.defaultValue
241
+ : null;
242
+ }
243
+
244
+ toDy(value) {
245
+ if (value === undefined || value === null) {
246
+ return this.getInitialValue();
247
+ }
248
+ return Number(value);
249
+ }
250
+
251
+ fromDy(value) {
252
+ if (value === undefined || value === null) {
253
+ return this.getInitialValue();
254
+ }
255
+ return parseInt(value, 10);
256
+ }
257
+
258
+ toGsi(value) {
259
+ // Pad with zeros for proper string sorting
260
+ return value != null ? value.toString().padStart(20, "0") : "";
261
+ }
262
+ }
263
+
264
+ /**
265
+ * @class FloatField
266
+ * @memberof BaoFields
267
+ * @description
268
+ * A field that stores a floating point number value.
269
+ */
270
+ class FloatField extends BaoBaseField {
271
+ getInitialValue() {
272
+ return this.options.defaultValue !== undefined
273
+ ? this.options.defaultValue
274
+ : null;
275
+ }
276
+
277
+ toDy(value) {
278
+ if (value === undefined || value === null) {
279
+ return this.getInitialValue();
280
+ }
281
+ const num = Number(value);
282
+ if (this.options.precision !== undefined && !isNaN(num)) {
283
+ return Number(num.toFixed(this.options.precision));
284
+ }
285
+ return num;
286
+ }
287
+
288
+ fromDy(value) {
289
+ if (value === undefined || value === null) {
290
+ return this.getInitialValue();
291
+ }
292
+ return parseFloat(value);
293
+ }
294
+
295
+ toGsi(value) {
296
+ // Scientific notation with padding for consistent sorting
297
+ return value != null ? value.toExponential(20) : "";
298
+ }
299
+ }
300
+
301
+ /**
302
+ * @class CreateDateField
303
+ * @memberof BaoFields
304
+ * @description
305
+ * A field that stores a date/time value based on when the object was created.
306
+ */
307
+ class CreateDateField extends DateTimeField {
308
+ constructor(options = {}) {
309
+ super({
310
+ ...options,
311
+ required: true,
312
+ });
313
+ }
314
+
315
+ getInitialValue() {
316
+ return new Date();
317
+ }
318
+
319
+ toDy(value) {
320
+ if (!value) {
321
+ return Date.now();
322
+ }
323
+ return value instanceof Date ? value.getTime() : value;
324
+ }
325
+ }
326
+
327
+ /**
328
+ * @class ModifiedDateField
329
+ * @memberof BaoFields
330
+ * @description
331
+ * A field that stores a date/time value based on when the object was last modified.
332
+ */
333
+ class ModifiedDateField extends DateTimeField {
334
+ constructor(options = {}) {
335
+ super({
336
+ ...options,
337
+ required: true,
338
+ });
339
+ }
340
+
341
+ getInitialValue() {
342
+ return new Date();
343
+ }
344
+
345
+ toDy(value) {
346
+ return Date.now();
347
+ }
348
+
349
+ updateBeforeSave(value, currentObject) {
350
+ // Always update modified date before save
351
+ return Date.now();
352
+ }
353
+ }
354
+
355
+ /**
356
+ * @class UlidField
357
+ * @memberof BaoFields
358
+ * @description
359
+ * A field that stores a {@link https://github.com/ulid/spec ULID} value.
360
+ */
361
+ class UlidField extends BaoBaseField {
362
+ constructor(options = {}) {
363
+ super({
364
+ ...options,
365
+ required: true,
366
+ });
367
+ this.autoAssign = options.autoAssign || false;
368
+ }
369
+
370
+ getInitialValue() {
371
+ if (this.autoAssign) {
372
+ return ulid();
373
+ }
374
+ return super.getInitialValue();
375
+ }
376
+
377
+ validate(value) {
378
+ if (!value && !this.autoAssign) {
379
+ throw new Error("ULID is required");
380
+ }
381
+
382
+ if (value) {
383
+ // Check if it's a valid ULID format
384
+ // ULIDs are 26 characters, uppercase alphanumeric
385
+ if (!/^[0-9A-Z]{26}$/.test(value)) {
386
+ throw new Error("Invalid ULID format");
387
+ }
388
+
389
+ try {
390
+ // Attempt to decode the timestamp to verify it's valid
391
+ decodeTime(value);
392
+ } catch (error) {
393
+ throw new Error("Invalid ULID: could not decode timestamp");
394
+ }
395
+ }
396
+ return true;
397
+ }
398
+
399
+ // toDy now only handles conversion, not generation
400
+ toDy(value) {
401
+ return value;
402
+ }
403
+
404
+ toGsi(value) {
405
+ return value || "";
406
+ }
407
+ }
408
+
409
+ /**
410
+ * @class RelatedField
411
+ * @memberof BaoFields
412
+ * @description
413
+ * A field that points to another object in the database. This field makes
414
+ * it easy to load related objects.
415
+ */
416
+ class RelatedField extends BaoBaseField {
417
+ constructor(modelName, options = {}) {
418
+ super(options);
419
+ this.modelName = modelName;
420
+ }
421
+
422
+ validate(value) {
423
+ if (this.required && !value) {
424
+ throw new Error("Field is required");
425
+ }
426
+ // Allow both string IDs and model instances
427
+ if (
428
+ value &&
429
+ typeof value !== "string" &&
430
+ (!value.getPrimaryId || typeof value.getPrimaryId !== "function")
431
+ ) {
432
+ throw new Error(
433
+ "Related field value must be a string ID or model instance",
434
+ );
435
+ }
436
+ return true;
437
+ }
438
+
439
+ toDy(value) {
440
+ if (!value) return null;
441
+ // If we're given a model instance, get its ID
442
+ if (typeof value === "object" && value.getPrimaryId) {
443
+ return value.getPrimaryId();
444
+ }
445
+ return value;
446
+ }
447
+
448
+ fromDy(value) {
449
+ return value;
450
+ }
451
+
452
+ toGsi(value) {
453
+ return this.toDy(value) || "";
454
+ }
455
+ }
456
+
457
+ /**
458
+ * @class CounterField
459
+ * @memberof BaoFields
460
+ * @description
461
+ * A field that stores an integer value that can be incremented or decremented atomically.
462
+ */
463
+ class CounterField extends BaoBaseField {
464
+ constructor(options = {}) {
465
+ super(options);
466
+ this.defaultValue = options.defaultValue || 0;
467
+ }
468
+
469
+ validate(value) {
470
+ super.validate(value);
471
+ if (value !== undefined) {
472
+ // Accept increment/decrement operations (e.g., '+1', '-5')
473
+ if (typeof value === "string" && /^[+-]\d+$/.test(value)) {
474
+ return true;
475
+ }
476
+ // Accept regular integer values
477
+ if (!Number.isInteger(value)) {
478
+ throw new Error("CounterField value must be an integer");
479
+ }
480
+ }
481
+ return true;
482
+ }
483
+
484
+ getInitialValue() {
485
+ return this.defaultValue;
486
+ }
487
+
488
+ toDy(value) {
489
+ if (
490
+ typeof value === "string" &&
491
+ (value.startsWith("+") || value.startsWith("-"))
492
+ ) {
493
+ return value;
494
+ }
495
+ return super.toDy(value);
496
+ }
497
+
498
+ fromDy(value) {
499
+ if (value === undefined || value === null) {
500
+ return this.getInitialValue();
501
+ }
502
+ return parseInt(value, 10);
503
+ }
504
+
505
+ getUpdateExpression(fieldName, value) {
506
+ if (value === undefined) return null;
507
+
508
+ const attributeName = `#${fieldName}`;
509
+ const attributeValue = `:${fieldName}`;
510
+
511
+ let expObj = {
512
+ attrNameKey: attributeName,
513
+ attrValueKey: attributeValue,
514
+ type: "SET",
515
+ expression: `${attributeName} = ${attributeValue}`,
516
+ fieldName: fieldName,
517
+ fieldValue: value,
518
+ };
519
+
520
+ logger.log("CounterField - getUpdateExpression", fieldName, value);
521
+
522
+ if (value === null) {
523
+ expObj = {
524
+ ...expObj,
525
+ type: "REMOVE",
526
+ expression: `${attributeName}`,
527
+ fieldValue: null,
528
+ };
529
+ }
530
+
531
+ // If the value is relative (has + or - prefix), use ADD
532
+ if (
533
+ typeof value === "string" &&
534
+ (value.startsWith("+") || value.startsWith("-"))
535
+ ) {
536
+ const numericValue = parseInt(value, 10);
537
+
538
+ // Return just the expression part without the ADD keyword
539
+ expObj = {
540
+ ...expObj,
541
+ type: "ADD",
542
+ expression: `${attributeName} ${attributeValue}`,
543
+ fieldValue: numericValue,
544
+ };
545
+ }
546
+
547
+ return expObj;
548
+ }
549
+
550
+ toGsi(value) {
551
+ return value != null ? value.toString().padStart(20, "0") : "";
552
+ }
553
+ }
554
+
555
+ /**
556
+ * @class BinaryField
557
+ * @memberof BaoFields
558
+ * @description
559
+ * A field that stores a binary value.
560
+ */
561
+ class BinaryField extends BaoBaseField {
562
+ getInitialValue() {
563
+ if (this.defaultValue) {
564
+ return typeof this.defaultValue === "function"
565
+ ? this.defaultValue()
566
+ : this.defaultValue;
567
+ }
568
+ return null;
569
+ }
570
+
571
+ validate(value) {
572
+ super.validate(value);
573
+ if (
574
+ value !== undefined &&
575
+ value !== null &&
576
+ !(value instanceof Buffer) &&
577
+ !(value instanceof Uint8Array)
578
+ ) {
579
+ throw new Error("BinaryField value must be a Buffer or Uint8Array");
580
+ }
581
+ return true;
582
+ }
583
+
584
+ toDy(value) {
585
+ if (!value) return null;
586
+
587
+ return value;
588
+ }
589
+
590
+ fromDy(value) {
591
+ if (!value) return null;
592
+ return value;
593
+ }
594
+
595
+ toGsi(value) {
596
+ throw new Error("BinaryField does not support GSI conversion");
597
+ }
598
+ }
599
+
600
+ /**
601
+ * @class VersionField
602
+ * @memberof BaoFields
603
+ * @description
604
+ * A field that stores a ULID value that is used to track the version of the object.
605
+ * You can use this field to implement optimistic locking by using the version field
606
+ * as a condition in your update operation.
607
+ */
608
+ class VersionField extends BaoBaseField {
609
+ constructor(options = {}) {
610
+ super({
611
+ ...options,
612
+ required: true,
613
+ });
614
+ this.defaultValue = options.defaultValue || ulid;
615
+ }
616
+
617
+ validate(value) {
618
+ super.validate(value);
619
+ if (value !== undefined) {
620
+ // Verify it's a valid ULID string
621
+ if (typeof value !== "string" || value.length !== 26) {
622
+ throw new Error("VersionField value must be a valid ULID");
623
+ }
624
+ }
625
+ return true;
626
+ }
627
+
628
+ getInitialValue() {
629
+ return typeof this.defaultValue === "function"
630
+ ? this.defaultValue()
631
+ : this.defaultValue;
632
+ }
633
+
634
+ updateBeforeSave(value) {
635
+ return ulid();
636
+ }
637
+
638
+ fromDy(value) {
639
+ return value || this.getInitialValue();
640
+ }
641
+
642
+ toDy(value) {
643
+ return value || this.getInitialValue();
644
+ }
645
+ }
646
+
647
+ /**
648
+ * @class BooleanField
649
+ * @memberof BaoFields
650
+ * @description
651
+ * A field that stores a boolean value.
652
+ */
653
+ class BooleanField extends BaoBaseField {
654
+ validate(value) {
655
+ super.validate(value);
656
+ if (value !== undefined && value !== null && typeof value !== "boolean") {
657
+ throw new Error("BooleanField value must be a boolean");
658
+ }
659
+ return true;
660
+ }
661
+
662
+ getInitialValue() {
663
+ return this.defaultValue !== undefined ? this.defaultValue : null;
664
+ }
665
+
666
+ toDy(value) {
667
+ if (value === undefined || value === null) {
668
+ return this.getInitialValue();
669
+ }
670
+ return Boolean(value);
671
+ }
672
+
673
+ fromDy(value) {
674
+ if (value === undefined || value === null) {
675
+ return this.getInitialValue();
676
+ }
677
+ return Boolean(value);
678
+ }
679
+
680
+ toGsi(value) {
681
+ if (value === undefined || value === null) {
682
+ return "";
683
+ }
684
+ // Convert to '0' or '1' for consistent string sorting
685
+ return value ? "1" : "0";
686
+ }
687
+ }
688
+
689
+ /**
690
+ * @class TtlField
691
+ * @memberof BaoFields
692
+ * @description
693
+ * A field that stores a Unix timestamp in seconds that indicates when the object should be deleted.
694
+ * DynamoDB will automatically delete the item at the specified time. This
695
+ * field must be named "ttl" for DynamoDB to automatically delete the item.
696
+ */
697
+ class TtlField extends DateTimeField {
698
+ validate(value) {
699
+ if (value === null || value === undefined) {
700
+ return true; // Allow null/undefined for field removal
701
+ }
702
+ return super.validate(value); // Use parent validation for dates
703
+ }
704
+
705
+ toDy(value) {
706
+ logger.log("TTL toDy", value);
707
+ if (value === undefined) return undefined; // Skip field
708
+ if (value === null) return null; // Remove field
709
+
710
+ // Convert any valid date input to Unix timestamp in seconds
711
+ let date;
712
+ if (value instanceof Date) {
713
+ date = value;
714
+ } else {
715
+ date = new Date(value);
716
+ if (isNaN(date.getTime())) {
717
+ throw new Error("Invalid date value provided for TTL field");
718
+ }
719
+ }
720
+
721
+ const timestamp = Math.floor(date.getTime() / 1000);
722
+ return timestamp;
723
+ }
724
+
725
+ fromDy(value) {
726
+ logger.log("TTL fromDy", value);
727
+ if (value === undefined || value === null) {
728
+ return null; // Convert both undefined and null to null
729
+ }
730
+ return new Date(value * 1000);
731
+ }
732
+ }
733
+
734
+ // Factory functions for creating field instances
735
+ const createStringField = (options) => new StringField(options);
736
+ const createDateTimeField = (options) => new DateTimeField(options);
737
+ const createCreateDateField = (options) => new CreateDateField(options);
738
+ const createModifiedDateField = (options) => new ModifiedDateField(options);
739
+ const createUlidField = (options) => new UlidField(options);
740
+ const createRelatedField = (modelName, options) =>
741
+ new RelatedField(modelName, options);
742
+ const createIntegerField = (options) => new IntegerField(options);
743
+ const createFloatField = (options) => new FloatField(options);
744
+ const createCounterField = (options) => new CounterField(options);
745
+ const createBinaryField = (options) => new BinaryField(options);
746
+ const createVersionField = (options) => new VersionField(options);
747
+ const createBooleanField = (options) => new BooleanField(options);
748
+ const createTtlField = (options) => new TtlField(options);
749
+
750
+ // Export both the factory functions and the classes
751
+ module.exports = {
752
+ // Factory functions
753
+ StringField: createStringField,
754
+ DateTimeField: createDateTimeField,
755
+ CreateDateField: createCreateDateField,
756
+ ModifiedDateField: createModifiedDateField,
757
+ UlidField: createUlidField,
758
+ RelatedField: createRelatedField,
759
+ IntegerField: createIntegerField,
760
+ FloatField: createFloatField,
761
+ CounterField: createCounterField,
762
+ BinaryField: createBinaryField,
763
+ VersionField: createVersionField,
764
+ BooleanField: createBooleanField,
765
+ TtlField: createTtlField,
766
+
767
+ // Classes (for instanceof checks)
768
+ StringFieldClass: StringField,
769
+ DateTimeFieldClass: DateTimeField,
770
+ CreateDateFieldClass: CreateDateField,
771
+ ModifiedDateFieldClass: ModifiedDateField,
772
+ UlidFieldClass: UlidField,
773
+ RelatedFieldClass: RelatedField,
774
+ IntegerFieldClass: IntegerField,
775
+ FloatFieldClass: FloatField,
776
+ CounterFieldClass: CounterField,
777
+ BinaryFieldClass: BinaryField,
778
+ VersionFieldClass: VersionField,
779
+ BooleanFieldClass: BooleanField,
780
+ TtlFieldClass: TtlField,
781
+ };