Browse Source

fix(core): Allow nullable fields to be unset via GraphQL API

Michael Bromley 6 years ago
parent
commit
d9f5c413f3

+ 17 - 2
packages/core/src/service/helpers/utils/patch-entity.spec.ts

@@ -1,14 +1,14 @@
 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',
@@ -16,6 +16,21 @@ describe('patchEntity()', () => {
         });
     });
 
+    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,

+ 3 - 2
packages/core/src/service/helpers/utils/patch-entity.ts

@@ -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;
         }
     }

+ 3 - 1
packages/core/src/service/services/role.service.ts

@@ -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));