Browse Source

refactor(server): Pull out repeated logic into getEntityOrThrow() method

Michael Bromley 7 years ago
parent
commit
137c1e3d30

+ 23 - 0
server/src/service/helpers/get-entity-or-throw.ts

@@ -0,0 +1,23 @@
+import { ID, Type } from 'shared/shared-types';
+import { Connection } from 'typeorm';
+
+import { VendureEntity } from '../../entity/base/base.entity';
+import { I18nError } from '../../i18n/i18n-error';
+
+/**
+ * Attempts to find an entity of the given type and id, and throws an error if not found.
+ */
+export async function getEntityOrThrow<T extends VendureEntity>(
+    connection: Connection,
+    entityType: Type<T>,
+    id: ID,
+): Promise<T> {
+    const entity = await connection.getRepository(entityType).findOne(id);
+    if (!entity) {
+        throw new I18nError(`error.entity-with-id-not-found`, {
+            entityName: entityType.name,
+            id,
+        });
+    }
+    return entity;
+}

+ 17 - 15
server/src/service/providers/channel.service.ts

@@ -13,6 +13,7 @@ import { ConfigService } from '../../config/config.service';
 import { Channel } from '../../entity/channel/channel.entity';
 import { Zone } from '../../entity/zone/zone.entity';
 import { I18nError } from '../../i18n/i18n-error';
+import { getEntityOrThrow } from '../helpers/get-entity-or-throw';
 import { patchEntity } from '../helpers/patch-entity';
 
 @Injectable()
@@ -74,10 +75,14 @@ export class ChannelService {
     async create(input: CreateChannelInput): Promise<Channel> {
         const channel = new Channel(input);
         if (input.defaultTaxZoneId) {
-            channel.defaultTaxZone = await this.getZoneOrThrow(input.defaultTaxZoneId);
+            channel.defaultTaxZone = await getEntityOrThrow(this.connection, Zone, input.defaultTaxZoneId);
         }
         if (input.defaultShippingZoneId) {
-            channel.defaultShippingZone = await this.getZoneOrThrow(input.defaultShippingZoneId);
+            channel.defaultShippingZone = await getEntityOrThrow(
+                this.connection,
+                Zone,
+                input.defaultShippingZoneId,
+            );
         }
         const newChannel = await this.connection.getRepository(Channel).save(channel);
         this.allChannels.push(channel);
@@ -94,10 +99,18 @@ export class ChannelService {
         }
         const updatedChannel = patchEntity(channel, input);
         if (input.defaultTaxZoneId) {
-            updatedChannel.defaultTaxZone = await this.getZoneOrThrow(input.defaultTaxZoneId);
+            updatedChannel.defaultTaxZone = await getEntityOrThrow(
+                this.connection,
+                Zone,
+                input.defaultTaxZoneId,
+            );
         }
         if (input.defaultShippingZoneId) {
-            updatedChannel.defaultShippingZone = await this.getZoneOrThrow(input.defaultShippingZoneId);
+            updatedChannel.defaultShippingZone = await getEntityOrThrow(
+                this.connection,
+                Zone,
+                input.defaultShippingZoneId,
+            );
         }
         await this.connection.getRepository(Channel).save(updatedChannel);
         return assertFound(this.findOne(channel.id));
@@ -127,15 +140,4 @@ export class ChannelService {
             await this.connection.manager.save(defaultChannel);
         }
     }
-
-    private async getZoneOrThrow(id: ID): Promise<Zone> {
-        const zone = await this.connection.getRepository(Zone).findOne(id);
-        if (!zone) {
-            throw new I18nError(`error.entity-with-id-not-found`, {
-                entityName: 'Zone',
-                id,
-            });
-        }
-        return zone;
-    }
 }

+ 4 - 12
server/src/service/providers/customer-group.service.ts

@@ -13,7 +13,7 @@ import { Connection } from 'typeorm';
 import { assertFound } from '../../common/utils';
 import { CustomerGroup } from '../../entity/customer-group/customer-group.entity';
 import { Customer } from '../../entity/customer/customer.entity';
-import { I18nError } from '../../i18n/i18n-error';
+import { getEntityOrThrow } from '../helpers/get-entity-or-throw';
 import { patchEntity } from '../helpers/patch-entity';
 
 @Injectable()
@@ -38,7 +38,7 @@ export class CustomerGroupService {
     }
 
     async update(input: UpdateCustomerGroupInput): Promise<CustomerGroup> {
-        const customerGroup = await this.getCustomerGroupOrThrow(input.id);
+        const customerGroup = await getEntityOrThrow(this.connection, CustomerGroup, input.id);
         const updatedCustomerGroup = patchEntity(customerGroup, input);
         await this.connection.getRepository(CustomerGroup).save(updatedCustomerGroup);
         return assertFound(this.findOne(customerGroup.id));
@@ -46,7 +46,7 @@ export class CustomerGroupService {
 
     async addCustomersToGroup(input: AddCustomersToGroupMutationArgs): Promise<CustomerGroup> {
         const countries = await this.getCustomersFromIds(input.customerIds);
-        const customerGroup = await this.getCustomerGroupOrThrow(input.customerGroupId);
+        const customerGroup = await getEntityOrThrow(this.connection, CustomerGroup, input.customerGroupId);
         const customers = unique(customerGroup.customers.concat(countries), 'id');
         customerGroup.customers = customers;
         await this.connection.getRepository(CustomerGroup).save(customerGroup);
@@ -54,7 +54,7 @@ export class CustomerGroupService {
     }
 
     async removeCustomersFromGroup(input: RemoveCustomersFromGroupMutationArgs): Promise<CustomerGroup> {
-        const customerGroup = await this.getCustomerGroupOrThrow(input.customerGroupId);
+        const customerGroup = await getEntityOrThrow(this.connection, CustomerGroup, input.customerGroupId);
         customerGroup.customers = customerGroup.customers.filter(
             customer => !input.customerIds.includes(customer.id as string),
         );
@@ -62,14 +62,6 @@ export class CustomerGroupService {
         return customerGroup;
     }
 
-    private async getCustomerGroupOrThrow(id: ID): Promise<CustomerGroup> {
-        const customerGroup = await this.findOne(id);
-        if (!customerGroup) {
-            throw new I18nError(`error.entity-with-id-not-found`, { entityName: 'CustomerGroup', id });
-        }
-        return customerGroup;
-    }
-
     private getCustomersFromIds(ids: ID[]): Promise<Customer[]> {
         return this.connection.getRepository(Customer).findByIds(ids);
     }

+ 18 - 39
server/src/service/providers/tax-rate.service.ts

@@ -11,9 +11,12 @@ import { TaxRate } from '../../entity/tax-rate/tax-rate.entity';
 import { Zone } from '../../entity/zone/zone.entity';
 import { I18nError } from '../../i18n/i18n-error';
 import { buildListQuery } from '../helpers/build-list-query';
+import { getEntityOrThrow } from '../helpers/get-entity-or-throw';
 import { patchEntity } from '../helpers/patch-entity';
 
 export class TaxRateService {
+    private activeTaxRates: TaxRate[] = [];
+
     constructor(@InjectConnection() private connection: Connection) {}
 
     findAll(options?: ListQueryOptions<TaxRate>): Promise<PaginatedList<TaxRate>> {
@@ -30,12 +33,17 @@ export class TaxRateService {
             relations: ['category', 'zone', 'customerGroup'],
         });
     }
+
     async create(input: CreateTaxRateInput): Promise<TaxRate> {
         const taxRate = new TaxRate(input);
-        taxRate.category = await this.getTaxCategoryOrThrow(input.categoryId);
-        taxRate.zone = await this.getZoneOrThrow(input.zoneId);
+        taxRate.category = await getEntityOrThrow(this.connection, TaxCategory, input.categoryId);
+        taxRate.zone = await getEntityOrThrow(this.connection, Zone, input.zoneId);
         if (input.customerGroupId) {
-            taxRate.customerGroup = await this.getCustomerGroupOrThrow(input.customerGroupId);
+            taxRate.customerGroup = await getEntityOrThrow(
+                this.connection,
+                CustomerGroup,
+                input.customerGroupId,
+            );
         }
         const newTaxRate = await this.connection.getRepository(TaxRate).save(taxRate);
         return assertFound(this.findOne(newTaxRate.id));
@@ -51,48 +59,19 @@ export class TaxRateService {
         }
         const updatedTaxRate = patchEntity(taxRate, input);
         if (input.categoryId) {
-            updatedTaxRate.category = await this.getTaxCategoryOrThrow(input.categoryId);
+            updatedTaxRate.category = await getEntityOrThrow(this.connection, TaxCategory, input.categoryId);
         }
         if (input.zoneId) {
-            updatedTaxRate.category = await this.getZoneOrThrow(input.zoneId);
+            updatedTaxRate.category = await getEntityOrThrow(this.connection, Zone, input.zoneId);
         }
         if (input.customerGroupId) {
-            updatedTaxRate.customerGroup = await this.getCustomerGroupOrThrow(input.customerGroupId);
+            updatedTaxRate.customerGroup = await getEntityOrThrow(
+                this.connection,
+                CustomerGroup,
+                input.customerGroupId,
+            );
         }
         await this.connection.getRepository(TaxRate).save(updatedTaxRate);
         return assertFound(this.findOne(taxRate.id));
     }
-
-    private async getTaxCategoryOrThrow(id: ID): Promise<TaxCategory> {
-        const taxCategory = await this.connection.getRepository(TaxCategory).findOne(id);
-        if (!taxCategory) {
-            throw new I18nError(`error.entity-with-id-not-found`, {
-                entityName: 'TaxCategory',
-                id,
-            });
-        }
-        return taxCategory;
-    }
-
-    private async getZoneOrThrow(id: ID): Promise<Zone> {
-        const zone = await this.connection.getRepository(Zone).findOne(id);
-        if (!zone) {
-            throw new I18nError(`error.entity-with-id-not-found`, {
-                entityName: 'Zone',
-                id,
-            });
-        }
-        return zone;
-    }
-
-    private async getCustomerGroupOrThrow(id: ID): Promise<CustomerGroup> {
-        const group = await this.connection.getRepository(CustomerGroup).findOne(id);
-        if (!group) {
-            throw new I18nError(`error.entity-with-id-not-found`, {
-                entityName: 'CustomerGroup',
-                id,
-            });
-        }
-        return group;
-    }
 }

+ 4 - 12
server/src/service/providers/zone.service.ts

@@ -13,7 +13,7 @@ import { Connection } from 'typeorm';
 import { assertFound } from '../../common/utils';
 import { Country } from '../../entity/country/country.entity';
 import { Zone } from '../../entity/zone/zone.entity';
-import { I18nError } from '../../i18n/i18n-error';
+import { getEntityOrThrow } from '../helpers/get-entity-or-throw';
 import { patchEntity } from '../helpers/patch-entity';
 
 @Injectable()
@@ -42,7 +42,7 @@ export class ZoneService {
     }
 
     async update(input: UpdateZoneInput): Promise<Zone> {
-        const zone = await this.getZoneOrThrow(input.id);
+        const zone = await getEntityOrThrow(this.connection, Zone, input.id);
         const updatedZone = patchEntity(zone, input);
         await this.connection.getRepository(Zone).save(updatedZone);
         return assertFound(this.findOne(zone.id));
@@ -50,7 +50,7 @@ export class ZoneService {
 
     async addMembersToZone(input: AddMembersToZoneMutationArgs): Promise<Zone> {
         const countries = await this.getCountriesFromIds(input.memberIds);
-        const zone = await this.getZoneOrThrow(input.zoneId);
+        const zone = await getEntityOrThrow(this.connection, Zone, input.zoneId);
         const members = unique(zone.members.concat(countries), 'id');
         zone.members = members;
         await this.connection.getRepository(Zone).save(zone);
@@ -58,20 +58,12 @@ export class ZoneService {
     }
 
     async removeMembersFromZone(input: RemoveMembersFromZoneMutationArgs): Promise<Zone> {
-        const zone = await this.getZoneOrThrow(input.zoneId);
+        const zone = await getEntityOrThrow(this.connection, Zone, input.zoneId);
         zone.members = zone.members.filter(country => !input.memberIds.includes(country.id as string));
         await this.connection.getRepository(Zone).save(zone);
         return zone;
     }
 
-    private async getZoneOrThrow(id: ID): Promise<Zone> {
-        const zone = await this.findOne(id);
-        if (!zone) {
-            throw new I18nError(`error.entity-with-id-not-found`, { entityName: 'Zone', id });
-        }
-        return zone;
-    }
-
     private getCountriesFromIds(ids: ID[]): Promise<Country[]> {
         return this.connection.getRepository(Country).findByIds(ids);
     }