Skip to content

Commit

Permalink
allow explicit undefined in entity.update
Browse files Browse the repository at this point in the history
  • Loading branch information
a-type committed Apr 11, 2024
1 parent 234a4f8 commit 938cfb2
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 1 deletion.
5 changes: 5 additions & 0 deletions .changeset/forty-tomatoes-rush.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@verdant-web/store': patch
---

Allow explicit undefined values in Entity.update. Ignore them by default.
23 changes: 23 additions & 0 deletions packages/store/src/entities/Entity.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -215,4 +215,27 @@ describe('Entity', () => {
});
});
});

describe('changes', () => {
it('can apply partial updates including undefineds', () => {
const { entity, initialize } = createTestEntity();

initialize({
id: 'hi',
string: 'world',
number: 1,
nullable: null,
nonNullable: { first: { inner: 'foo' } },
map: {},
list: [20, { inner: 'yay' }],
});

entity.update({
string: 'new world',
number: undefined,
});

expect(entity.get('string')).toBe('new world');
});
});
});
10 changes: 9 additions & 1 deletion packages/store/src/entities/Entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -786,7 +786,12 @@ export class Entity<
{
merge = true,
replaceSubObjects = false,
}: { replaceSubObjects?: boolean; merge?: boolean } = {},
preserveUndefined = false,
}: {
replaceSubObjects?: boolean;
merge?: boolean;
preserveUndefined?: boolean;
} = {},
): void => {
if (!merge && this.schema.type !== 'any' && this.schema.type !== 'map') {
throw new Error(
Expand All @@ -799,6 +804,9 @@ export class Entity<
if (this.readonlyKeys.includes(key as any)) {
throw new Error(`Cannot set readonly key ${key.toString()}`);
}
// ignore undefined values unless overridden
if (field === undefined && !preserveUndefined) continue;

const fieldSchema = getChildFieldSchema(this.schema, key);
if (fieldSchema) {
traverseCollectionFieldsAndApplyDefaults(field, fieldSchema);
Expand Down

0 comments on commit 938cfb2

Please sign in to comment.