sensedeep / dynamodb-onetable

DynamoDB access and management for one table designs with NodeJS
https://doc.onetable.io/
MIT License
689 stars 109 forks source link

Not setting undefined values on read to required default values #531

Closed mobsense closed 4 months ago

mobsense commented 4 months ago

Looks like if you revise your schema and add a default value, then read old items that don't have that field defined .... the default values are not applied.

Currently default values are only being applied on create.

This quick patch addresses this:

diff --git a/src/Model.js b/src/Model.js
index ed1ce2c..68889ee 100644
--- a/src/Model.js
+++ b/src/Model.js
@@ -1134,7 +1134,7 @@ export class Model {
                 value = this.decrypt(value)
             }
             if (field.default !== undefined && value === undefined) {
-                value = field.default
+                rec[name] = field.default
             } else if (value === undefined) {

We'll test this out on production systems to ensure it doesn't break anything else.

mobsense commented 4 months ago

Here is a more complete patch that passes all unit tests:

This handles requests that use params.fields.

diff --git a/src/Model.js b/src/Model.js
index ed1ce2c..4f44ff2 100644
--- a/src/Model.js
+++ b/src/Model.js
@@ -1123,18 +1123,17 @@ export class Model {
                     let [att, sep, index] = field.encode
                     value = (raw[att] || '').split(sep)[index]
                 }
-                if (value === undefined) {
-                    continue
-                }
             }
-            if (sub) {
+            if (sub && value) {
                 value = value[sub]
             }
             if (field.crypt && params.decrypt !== false) {
                 value = this.decrypt(value)
             }
             if (field.default !== undefined && value === undefined) {
-                value = field.default
+                if (!params.fields || params.fields.indexOf(name) >= 0) {
+                    rec[name] = field.default
+                }
             } else if (value === undefined) {