Skip to content

Commit f0ae165

Browse files
authored
fix(ent/update): resolve unexpected behavior with mapped fields (dynamodb-toolbox#527)
1 parent 00b8943 commit f0ae165

File tree

2 files changed

+39
-1
lines changed

2 files changed

+39
-1
lines changed

src/__tests__/entity.update.unit.test.ts

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,24 @@ const TestEntity3 = new Entity({
9090
table: TestTable3
9191
} as const)
9292

93+
const TestTable4 = new Table({
94+
name: 'test-table4',
95+
partitionKey: 'pk',
96+
entityField: false,
97+
DocumentClient
98+
})
99+
100+
const TestEntity4 = new Entity({
101+
name: 'TestEntity4',
102+
autoExecute: false,
103+
attributes: {
104+
email: { type: 'string', partitionKey: true },
105+
test_number_default_with_map: { type: 'number', map: 'test_mapped_number', default: 0, onUpdate: false },
106+
},
107+
timestamps: false,
108+
table: TestTable4
109+
} as const)
110+
93111
const TestEntityGSI = new Entity({
94112
name: 'TestEntityGSI',
95113
autoExecute: false,
@@ -204,6 +222,26 @@ describe('update', () => {
204222
)
205223
})
206224

225+
it('allows overriding default field values that use mapping', () => {
226+
const {
227+
UpdateExpression,
228+
ExpressionAttributeNames,
229+
ExpressionAttributeValues
230+
} = TestEntity4.updateParams({
231+
email: 'test-pk',
232+
test_number_default_with_map: 111
233+
})
234+
235+
expect(ExpressionAttributeNames?.['#test_mapped_number']).toBe('test_mapped_number')
236+
expect(ExpressionAttributeValues?.[':test_mapped_number']).toBe(111)
237+
238+
expect(UpdateExpression).toBe(
239+
'SET #test_mapped_number = :test_mapped_number'
240+
)
241+
242+
})
243+
244+
207245
it('fails when removing fields with default values', () => {
208246
expect(() =>
209247
TestEntity.updateParams({ email: 'test-pk', sort: 'test-sk', $remove: 'test_string' })

src/classes/Entity/Entity.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1178,7 +1178,7 @@ class Entity<Name extends string = string,
11781178
// Push the update to SET
11791179
SET.push(
11801180
// @ts-ignore
1181-
mapping.default !== undefined && item[field] === undefined && !mapping.onUpdate
1181+
mapping.default !== undefined && item[mapping.alias || field] === undefined && !mapping.onUpdate
11821182
? `#${field} = if_not_exists(#${field},:${field})`
11831183
: `#${field} = :${field}`,
11841184
)

0 commit comments

Comments
 (0)