Skip to content

Commit

Permalink
Validate that removed fields are not required
Browse files Browse the repository at this point in the history
Fixes jeremydaly#255
Defining a table attribute with `required: true` should mean that values always exist for that field (barring extraneous factors like schema changes and writes that may not go through this library). Updates may or may not specify a new value, but that new value should not be null, and the field cannot be removed outright.

This fixes two cases of this bug:
1) You can remove a `required: true` value by passing $remove: attr or `$remove: [attr]`
2) You can remove a `required: true` value by passing `attr: ''` if `removeNullAttributes` is set.
  • Loading branch information
amccarthy1 committed May 9, 2022
1 parent a86b7a8 commit effc735
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/__tests__/entity.update.unit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -545,6 +545,22 @@ describe('update',()=>{
})).toThrow(`'test2' is a required field`)
})

it('fails when removing a required field', () => {
expect(() => TestEntity3.updateParams({
'pk': 'test-pk',
'test2': 'test-value',
'$remove': 'test'
})).toThrow(`'test' is required and cannot be removed`)
})

it('fails when setting a required field to a value that coerces to null', () => {
expect(() => TestEntity3.updateParams({
'pk': 'test-pk',
'test': '',
'test2': 'test-value',
})).toThrow(`'test' is required and cannot be removed`)
})

it('fails when using non-numeric fields for indexed list updates', () => {
expect(() => TestEntity.updateParams({
'pk': 'test-pk',
Expand Down
5 changes: 5 additions & 0 deletions src/classes/Entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -784,12 +784,17 @@ class Entity<
// Verify attribute is not a pk/sk
if (schema.attributes[attrs[i]].partitionKey === true || schema.attributes[attrs[i]].sortKey === true)
error(`'${attrs[i]}' is the ${schema.attributes[attrs[i]].partitionKey === true ? 'partitionKey' : 'sortKey' } and cannot be removed`)
// Verify attribute is not required
if (schema.attributes[attrs[i]].required)
error(`'${attrs[i]}' is required and cannot be removed`);
// Grab the attribute name and add to REMOVE and names
const attr = schema.attributes[attrs[i]].map || attrs[i]
REMOVE.push(`#${attr}`)
names[`#${attr}`] = attr
} // end for
} else if (this._table!._removeNulls === true && (data[field] === null || String(data[field]).trim() === '') && (!mapping.link || mapping.save)) {
if (schema.attributes[field].required)
error(`'${field}' is required and cannot be removed`);
REMOVE.push(`#${field}`)
names[`#${field}`] = field
} else if (
Expand Down

0 comments on commit effc735

Please sign in to comment.