Skip to content

Commit

Permalink
fix(core): Allow nullable fields to be unset via GraphQL API
Browse files Browse the repository at this point in the history
  • Loading branch information
michaelbromley committed Oct 10, 2019
1 parent 95bf868 commit d9f5c41
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 5 deletions.
19 changes: 17 additions & 2 deletions packages/core/src/service/helpers/utils/patch-entity.spec.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,36 @@
import { patchEntity } from './patch-entity';

describe('patchEntity()', () => {
it('updates non-null values', () => {
it('updates non-undefined values', () => {
const entity: any = {
foo: 'foo',
bar: 'bar',
baz: 'baz',
};

const result = patchEntity(entity, { bar: 'bar2', baz: null });
const result = patchEntity(entity, { bar: 'bar2', baz: undefined });
expect(result).toEqual({
foo: 'foo',
bar: 'bar2',
baz: 'baz',
});
});

it('updates null values', () => {
const entity: any = {
foo: 'foo',
bar: 'bar',
baz: 'baz',
};

const result = patchEntity(entity, { bar: null });
expect(result).toEqual({
foo: 'foo',
bar: null,
baz: 'baz',
});
});

it('does not update id field', () => {
const entity: any = {
id: 123,
Expand Down
5 changes: 3 additions & 2 deletions packages/core/src/service/helpers/utils/patch-entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,15 @@ export type InputPatch<T> = { [K in keyof T]?: T[K] | null };

/**
* Updates only the specified properties from an Input object as long as the value is not
* null or undefined.
* undefined. Null values can be passed, however, which will set the corresponding entity
* field to "null". So case must be taken that this is only done on nullable fields.
*/
export function patchEntity<T extends VendureEntity, I extends InputPatch<T>>(entity: T, input: I): T {
for (const key of Object.keys(entity)) {
const value = input[key as keyof T];
if (key === 'customFields') {
patchEntity((entity as any)[key], value as any);
} else if (value != null && key !== 'id') {
} else if (value !== undefined && key !== 'id') {
entity[key as keyof T] = value as any;
}
}
Expand Down
4 changes: 3 additions & 1 deletion packages/core/src/service/services/role.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,9 @@ export class RoleService {
const updatedRole = patchEntity(role, {
code: input.code,
description: input.description,
permissions: input.permissions ? unique([Permission.Authenticated, ...input.permissions]) : null,
permissions: input.permissions
? unique([Permission.Authenticated, ...input.permissions])
: undefined,
});
await this.connection.manager.save(updatedRole);
return assertFound(this.findOne(role.id));
Expand Down

0 comments on commit d9f5c41

Please sign in to comment.