Parcourir la source

perf(core): Add `reload: false` to .save() operations

By default, a TypeORM `.save()` operation will also immediately select the saved entity. In the case that the return value is not used, this is redundant and is switched off by passing the `{ reload: false }` option.
Michael Bromley il y a 6 ans
Parent
commit
3c33f33f94

+ 3 - 3
packages/core/src/data-import/providers/importer/fast-importer.service.ts

@@ -69,7 +69,7 @@ export class FastImporterService {
                         position: i,
                     }),
             );
-            await this.connection.getRepository(ProductAsset).save(productAssets);
+            await this.connection.getRepository(ProductAsset).save(productAssets, { reload: false });
         }
         return product.id;
     }
@@ -137,7 +137,7 @@ export class FastImporterService {
                         position: i,
                     }),
             );
-            await this.connection.getRepository(ProductVariantAsset).save(variantAssets);
+            await this.connection.getRepository(ProductVariantAsset).save(variantAssets, { reload: false });
         }
         if (input.stockOnHand != null && input.stockOnHand !== 0) {
             await this.stockMovementService.adjustProductVariantStock(
@@ -151,7 +151,7 @@ export class FastImporterService {
             channelId: this.defaultChannel.id,
         });
         variantPrice.variant = createdVariant;
-        await this.connection.getRepository(ProductVariantPrice).save(variantPrice);
+        await this.connection.getRepository(ProductVariantPrice).save(variantPrice, { reload: false });
         return createdVariant.id;
     }
 }

+ 3 - 3
packages/core/src/service/services/administrator.service.ts

@@ -71,14 +71,14 @@ export class AdministratorService {
             throw new EntityNotFoundError('Administrator', input.id);
         }
         let updatedAdministrator = patchEntity(administrator, input);
-        await this.connection.manager.save(administrator);
+        await this.connection.manager.save(administrator, { reload: false });
 
         if (input.password) {
             administrator.user.passwordHash = await this.passwordCipher.hash(input.password);
         }
         if (input.roleIds) {
             administrator.user.roles = [];
-            await this.connection.manager.save(administrator.user);
+            await this.connection.manager.save(administrator.user, { reload: false });
             for (const roleId of input.roleIds) {
                 updatedAdministrator = await this.assignRole(administrator.id, roleId);
             }
@@ -99,7 +99,7 @@ export class AdministratorService {
             throw new EntityNotFoundError('Role', roleId);
         }
         administrator.user.roles.push(role);
-        await this.connection.manager.save(administrator.user);
+        await this.connection.manager.save(administrator.user, { reload: false });
         return administrator;
     }
 

+ 5 - 5
packages/core/src/service/services/channel.service.ts

@@ -65,7 +65,7 @@ export class ChannelService {
             const channel = await getEntityOrThrow(this.connection, Channel, id);
             entity.channels.push(channel);
         }
-        await this.connection.getRepository(entityType).save(entity as any);
+        await this.connection.getRepository(entityType).save(entity as any, { reload: false });
         return entity;
     }
 
@@ -83,7 +83,7 @@ export class ChannelService {
         for (const id of channelIds) {
             entity.channels = entity.channels.filter(c => !idsAreEqual(c.id, id));
         }
-        await this.connection.getRepository(entityType).save(entity as any);
+        await this.connection.getRepository(entityType).save(entity as any, { reload: false });
         return entity;
     }
 
@@ -163,7 +163,7 @@ export class ChannelService {
                 input.defaultShippingZoneId,
             );
         }
-        await this.connection.getRepository(Channel).save(updatedChannel);
+        await this.connection.getRepository(Channel).save(updatedChannel, { reload: false });
         await this.updateAllChannels();
         return assertFound(this.findOne(channel.id));
     }
@@ -199,10 +199,10 @@ export class ChannelService {
                 currencyCode: CurrencyCode.USD,
                 token: defaultChannelToken,
             });
-            await this.connection.manager.save(newDefaultChannel);
+            await this.connection.manager.save(newDefaultChannel, { reload: false });
         } else if (defaultChannelToken && defaultChannel.token !== defaultChannelToken) {
             defaultChannel.token = defaultChannelToken;
-            await this.connection.manager.save(defaultChannel);
+            await this.connection.manager.save(defaultChannel, { reload: false });
         }
     }
 

+ 4 - 4
packages/core/src/service/services/customer-group.service.ts

@@ -1,8 +1,8 @@
 import { Injectable } from '@nestjs/common';
 import { InjectConnection } from '@nestjs/typeorm';
 import {
-    MutationAddCustomersToGroupArgs,
     CreateCustomerGroupInput,
+    MutationAddCustomersToGroupArgs,
     MutationRemoveCustomersFromGroupArgs,
     UpdateCustomerGroupInput,
 } from '@vendure/common/lib/generated-types';
@@ -40,7 +40,7 @@ export class CustomerGroupService {
     async update(input: UpdateCustomerGroupInput): Promise<CustomerGroup> {
         const customerGroup = await getEntityOrThrow(this.connection, CustomerGroup, input.id);
         const updatedCustomerGroup = patchEntity(customerGroup, input);
-        await this.connection.getRepository(CustomerGroup).save(updatedCustomerGroup);
+        await this.connection.getRepository(CustomerGroup).save(updatedCustomerGroup, { reload: false });
         return assertFound(this.findOne(customerGroup.id));
     }
 
@@ -49,7 +49,7 @@ export class CustomerGroupService {
         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);
+        await this.connection.getRepository(CustomerGroup).save(customerGroup, { reload: false });
         return customerGroup;
     }
 
@@ -58,7 +58,7 @@ export class CustomerGroupService {
         customerGroup.customers = customerGroup.customers.filter(
             customer => !input.customerIds.includes(customer.id as string),
         );
-        await this.connection.getRepository(CustomerGroup).save(customerGroup);
+        await this.connection.getRepository(CustomerGroup).save(customerGroup, { reload: false });
         return customerGroup;
     }
 

+ 8 - 8
packages/core/src/service/services/customer.service.ts

@@ -135,7 +135,7 @@ export class CustomerService {
             user = await this.userService.setVerificationToken(user);
         }
         customer.user = user;
-        await this.connection.getRepository(Customer).save(customer);
+        await this.connection.getRepository(Customer).save(customer, { reload: false });
         if (!user.verified) {
             this.eventBus.publish(new AccountRegistrationEvent(ctx, user));
         }
@@ -202,8 +202,8 @@ export class CustomerService {
             const oldIdentifier = user.identifier;
             user.identifier = newEmailAddress;
             customer.emailAddress = newEmailAddress;
-            await this.connection.getRepository(User).save(user);
-            await this.connection.getRepository(Customer).save(customer);
+            await this.connection.getRepository(User).save(user, { reload: false });
+            await this.connection.getRepository(Customer).save(customer, { reload: false });
             this.eventBus.publish(new IdentifierChangeEvent(ctx, user, oldIdentifier));
             return true;
         }
@@ -220,14 +220,14 @@ export class CustomerService {
         }
         this.eventBus.publish(new IdentifierChangeEvent(ctx, user, oldIdentifier));
         customer.emailAddress = user.identifier;
-        await this.connection.getRepository(Customer).save(customer);
+        await this.connection.getRepository(Customer).save(customer, { reload: false });
         return true;
     }
 
     async update(input: UpdateCustomerInput): Promise<Customer> {
         const customer = await getEntityOrThrow(this.connection, Customer, input.id);
         const updatedCustomer = patchEntity(customer, input);
-        await this.connection.getRepository(Customer).save(customer);
+        await this.connection.getRepository(Customer).save(customer, { reload: false });
         return assertFound(this.findOne(customer.id));
     }
 
@@ -270,7 +270,7 @@ export class CustomerService {
         });
         const createdAddress = await this.connection.manager.getRepository(Address).save(address);
         customer.addresses.push(createdAddress);
-        await this.connection.manager.save(customer);
+        await this.connection.manager.save(customer, { reload: false });
         await this.enforceSingleDefaultAddress(createdAddress.id, input);
         return createdAddress;
     }
@@ -285,7 +285,7 @@ export class CustomerService {
             address.country = translateDeep(address.country, ctx.languageCode);
         }
         const updatedAddress = patchEntity(address, input);
-        await this.connection.getRepository(Address).save(updatedAddress);
+        await this.connection.getRepository(Address).save(updatedAddress, { reload: false });
         await this.enforceSingleDefaultAddress(input.id, input);
         return updatedAddress;
     }
@@ -353,7 +353,7 @@ export class CustomerService {
                 if (addressToDelete.defaultBillingAddress) {
                     otherAddresses[0].defaultBillingAddress = true;
                 }
-                await this.connection.getRepository(Address).save(otherAddresses[0]);
+                await this.connection.getRepository(Address).save(otherAddresses[0], { reload: false });
             }
         }
     }

+ 1 - 1
packages/core/src/service/services/global-settings.service.ts

@@ -22,7 +22,7 @@ export class GlobalSettingsService {
             const settings = new GlobalSettings({
                 availableLanguages: [DEFAULT_LANGUAGE_CODE],
             });
-            await this.connection.getRepository(GlobalSettings).save(settings);
+            await this.connection.getRepository(GlobalSettings).save(settings, { reload: false });
         }
     }
 

+ 7 - 7
packages/core/src/service/services/order.service.ts

@@ -236,7 +236,7 @@ export class OrderService {
             const newLine = this.createOrderLineFromVariant(productVariant, customFields);
             orderLine = await this.connection.getRepository(OrderLine).save(newLine);
             order.lines.push(orderLine);
-            await this.connection.getRepository(Order).save(order);
+            await this.connection.getRepository(Order).save(order, { reload: false });
         }
         return this.adjustOrderLine(ctx, order, orderLine.id, orderLine.quantity + quantity);
     }
@@ -371,7 +371,7 @@ export class OrderService {
             throw new UserInputError(`error.shipping-method-unavailable`);
         }
         order.shippingMethod = selectedMethod.method;
-        await this.connection.getRepository(Order).save(order);
+        await this.connection.getRepository(Order).save(order, { reload: false });
         await this.applyPriceAdjustments(ctx, order);
         return this.connection.getRepository(Order).save(order);
     }
@@ -379,7 +379,7 @@ export class OrderService {
     async transitionToState(ctx: RequestContext, orderId: ID, state: OrderState): Promise<Order> {
         const order = await this.getOrderOrThrow(ctx, orderId);
         await this.orderStateMachine.transition(ctx, order, state);
-        await this.connection.getRepository(Order).save(order);
+        await this.connection.getRepository(Order).save(order, { reload: false });
         return order;
     }
 
@@ -397,7 +397,7 @@ export class OrderService {
 
         const existingPayments = await this.getOrderPayments(orderId);
         order.payments = [...existingPayments, payment];
-        await this.connection.getRepository(Order).save(order);
+        await this.connection.getRepository(Order).save(order, { reload: false });
 
         if (payment.state === 'Error') {
             throw new InternalServerError(payment.errorMessage);
@@ -425,7 +425,7 @@ export class OrderService {
         if (settlePaymentResult.success) {
             await this.paymentStateMachine.transition(ctx, payment.order, payment, 'Settled');
             payment.metadata = { ...payment.metadata, ...settlePaymentResult.metadata };
-            await this.connection.getRepository(Payment).save(payment);
+            await this.connection.getRepository(Payment).save(payment, { reload: false });
             if (payment.amount === payment.order.total) {
                 await this.transitionToState(ctx, payment.order.id, 'PaymentSettled');
             }
@@ -652,7 +652,7 @@ export class OrderService {
             throw new IllegalOperationError(`error.order-already-has-customer`);
         }
         order.customer = customer;
-        await this.connection.getRepository(Order).save(order);
+        await this.connection.getRepository(Order).save(order, { reload: false });
         // Check that any applied couponCodes are still valid now that
         // we know the Customer.
         if (order.couponCodes) {
@@ -712,7 +712,7 @@ export class OrderService {
         const customer = await this.customerService.findOneByUserId(user.id);
         if (order && customer) {
             order.customer = customer;
-            await this.connection.getRepository(Order).save(order);
+            await this.connection.getRepository(Order).save(order, { reload: false });
         }
         return order;
     }

+ 4 - 4
packages/core/src/service/services/payment-method.service.ts

@@ -82,7 +82,7 @@ export class PaymentMethodService {
             .getRepository(Payment)
             .save(new Payment({ ...result, state: 'Created' }));
         await this.paymentStateMachine.transition(ctx, order, payment, result.state);
-        await this.connection.getRepository(Payment).save(payment);
+        await this.connection.getRepository(Payment).save(payment, { reload: false });
         return payment;
     }
 
@@ -127,7 +127,7 @@ export class PaymentMethodService {
         refund = await this.connection.getRepository(Refund).save(refund);
         if (createRefundResult) {
             await this.refundStateMachine.transition(ctx, order, refund, createRefundResult.state);
-            await this.connection.getRepository(Refund).save(refund);
+            await this.connection.getRepository(Refund).save(refund, { reload: false });
         }
         return refund;
     }
@@ -173,7 +173,7 @@ export class PaymentMethodService {
                 continue;
             }
             paymentMethod.configArgs = this.buildConfigArgsArray(handler, paymentMethod.configArgs);
-            await this.connection.getRepository(PaymentMethod).save(paymentMethod);
+            await this.connection.getRepository(PaymentMethod).save(paymentMethod, { reload: false });
         }
         for (const handler of toCreate) {
             let paymentMethod = existingPaymentMethods.find(pm => pm.code === handler.code);
@@ -186,7 +186,7 @@ export class PaymentMethodService {
                 });
             }
             paymentMethod.configArgs = this.buildConfigArgsArray(handler, paymentMethod.configArgs);
-            await this.connection.getRepository(PaymentMethod).save(paymentMethod);
+            await this.connection.getRepository(PaymentMethod).save(paymentMethod, { reload: false });
         }
         await this.connection.getRepository(PaymentMethod).remove(toRemove);
     }

+ 1 - 1
packages/core/src/service/services/product-variant.service.ts

@@ -315,7 +315,7 @@ export class ProductVariantService {
     async softDelete(ctx: RequestContext, id: ID): Promise<DeletionResponse> {
         const variant = await getEntityOrThrow(this.connection, ProductVariant, id);
         variant.deletedAt = new Date();
-        await this.connection.getRepository(ProductVariant).save(variant);
+        await this.connection.getRepository(ProductVariant).save(variant, { reload: false });
         this.eventBus.publish(new ProductVariantEvent(ctx, [variant], 'deleted'));
         return {
             result: DeletionResult.DELETED,

+ 3 - 3
packages/core/src/service/services/product.service.ts

@@ -163,7 +163,7 @@ export class ProductService {
     async softDelete(ctx: RequestContext, productId: ID): Promise<DeletionResponse> {
         const product = await getEntityOrThrow(this.connection, Product, productId, ctx.channelId);
         product.deletedAt = new Date();
-        await this.connection.getRepository(Product).save(product);
+        await this.connection.getRepository(Product).save(product, { reload: false });
         this.eventBus.publish(new ProductEvent(ctx, product, 'deleted'));
         return {
             result: DeletionResult.DELETED,
@@ -242,7 +242,7 @@ export class ProductService {
             product.optionGroups = [optionGroup];
         }
 
-        await this.connection.manager.save(product);
+        await this.connection.manager.save(product, { reload: false });
         return assertFound(this.findOne(ctx, productId));
     }
 
@@ -264,7 +264,7 @@ export class ProductService {
         }
         product.optionGroups = product.optionGroups.filter(g => g.id !== optionGroupId);
 
-        await this.connection.manager.save(product);
+        await this.connection.manager.save(product, { reload: false });
         return assertFound(this.findOne(ctx, productId));
     }
 

+ 2 - 2
packages/core/src/service/services/promotion.service.ts

@@ -127,8 +127,8 @@ export class PromotionService {
             updatedPromotion.actions = input.actions.map(a => this.parseOperationArgs('action', a));
         }
         this.validatePromotionConditions(updatedPromotion);
-        (promotion.priorityScore = this.calculatePriorityScore(input)),
-            await this.connection.manager.save(updatedPromotion);
+        promotion.priorityScore = this.calculatePriorityScore(input);
+        await this.connection.manager.save(updatedPromotion, { reload: false });
         await this.updatePromotions();
         return assertFound(this.findOne(ctx, updatedPromotion.id));
     }

+ 2 - 2
packages/core/src/service/services/role.service.ts

@@ -150,7 +150,7 @@ export class RoleService {
         if (input.channelIds && ctx.activeUserId) {
             updatedRole.channels = await this.getPermittedChannels(input.channelIds, ctx.activeUserId);
         }
-        await this.connection.manager.save(updatedRole);
+        await this.connection.manager.save(updatedRole, { reload: false });
         return assertFound(this.findOne(role.id));
     }
 
@@ -219,7 +219,7 @@ export class RoleService {
             );
             if (!hasAllPermissions) {
                 superAdminRole.permissions = allPermissions;
-                await this.connection.getRepository(Role).save(superAdminRole);
+                await this.connection.getRepository(Role).save(superAdminRole, { reload: false });
             }
         } catch (err) {
             await this.createRoleForChannels(

+ 2 - 2
packages/core/src/service/services/shipping-method.service.ts

@@ -94,7 +94,7 @@ export class ShippingMethodService {
                 input.calculator,
             );
         }
-        await this.connection.manager.save(updatedShippingMethod);
+        await this.connection.manager.save(updatedShippingMethod, { reload: false });
         await this.updateActiveShippingMethods();
         return assertFound(this.findOne(ctx, shippingMethod.id));
     }
@@ -104,7 +104,7 @@ export class ShippingMethodService {
             where: { deletedAt: null },
         });
         shippingMethod.deletedAt = new Date();
-        await this.connection.getRepository(ShippingMethod).save(shippingMethod);
+        await this.connection.getRepository(ShippingMethod).save(shippingMethod, { reload: false });
         await this.updateActiveShippingMethods();
         return {
             result: DeletionResult.DELETED,

+ 1 - 1
packages/core/src/service/services/stock-movement.service.ts

@@ -80,7 +80,7 @@ export class StockMovementService {
 
             if (productVariant.trackInventory === true) {
                 productVariant.stockOnHand -= line.quantity;
-                await this.connection.getRepository(ProductVariant).save(productVariant);
+                await this.connection.getRepository(ProductVariant).save(productVariant, { reload: false });
             }
         }
         return this.connection.getRepository(Sale).save(sales);

+ 1 - 1
packages/core/src/service/services/tax-category.service.ts

@@ -33,7 +33,7 @@ export class TaxCategoryService {
             throw new EntityNotFoundError('TaxCategory', input.id);
         }
         const updatedTaxCategory = patchEntity(taxCategory, input);
-        await this.connection.getRepository(TaxCategory).save(updatedTaxCategory);
+        await this.connection.getRepository(TaxCategory).save(updatedTaxCategory, { reload: false });
         return assertFound(this.findOne(taxCategory.id));
     }
 }

+ 1 - 1
packages/core/src/service/services/tax-rate.service.ts

@@ -96,7 +96,7 @@ export class TaxRateService {
                 input.customerGroupId,
             );
         }
-        await this.connection.getRepository(TaxRate).save(updatedTaxRate);
+        await this.connection.getRepository(TaxRate).save(updatedTaxRate, { reload: false });
         await this.updateActiveTaxRates();
         await this.workerService.send(new TaxRateUpdatedMessage(updatedTaxRate.id)).toPromise();
         this.eventBus.publish(new TaxRateModificationEvent(ctx, updatedTaxRate));

+ 6 - 4
packages/core/src/service/services/user.service.ts

@@ -117,7 +117,7 @@ export class UserService {
         }
     }
 
-    async changeIdentifierByToken(token: string): Promise<{ user: User; oldIdentifier: string; }> {
+    async changeIdentifierByToken(token: string): Promise<{ user: User; oldIdentifier: string }> {
         const user = await this.connection.getRepository(User).findOne({
             where: { identifierChangeToken: token },
         });
@@ -135,12 +135,14 @@ export class UserService {
         user.identifier = pendingIdentifier;
         user.identifierChangeToken = null;
         user.pendingIdentifier = null;
-        await this.connection.getRepository(User).save(user);
+        await this.connection.getRepository(User).save(user, { reload: false });
         return { user, oldIdentifier };
     }
 
     async updatePassword(userId: ID, currentPassword: string, newPassword: string): Promise<boolean> {
-        const user = await this.connection.getRepository(User).findOne(userId, { select: ['id', 'passwordHash'] });
+        const user = await this.connection
+            .getRepository(User)
+            .findOne(userId, { select: ['id', 'passwordHash'] });
         if (!user) {
             throw new InternalServerError(`error.no-active-user-id`);
         }
@@ -149,7 +151,7 @@ export class UserService {
             throw new UnauthorizedError();
         }
         user.passwordHash = await this.passwordCipher.hash(newPassword);
-        await this.connection.getRepository(User).save(user);
+        await this.connection.getRepository(User).save(user, { reload: false });
         return true;
     }
 

+ 4 - 4
packages/core/src/service/services/zone.service.ts

@@ -1,10 +1,10 @@
 import { Injectable, OnModuleInit } from '@nestjs/common';
 import { InjectConnection } from '@nestjs/typeorm';
 import {
-    MutationAddMembersToZoneArgs,
     CreateZoneInput,
     DeletionResponse,
     DeletionResult,
+    MutationAddMembersToZoneArgs,
     MutationRemoveMembersFromZoneArgs,
     UpdateZoneInput,
 } from '@vendure/common/lib/generated-types';
@@ -67,7 +67,7 @@ export class ZoneService implements OnModuleInit {
     async update(ctx: RequestContext, input: UpdateZoneInput): Promise<Zone> {
         const zone = await getEntityOrThrow(this.connection, Zone, input.id);
         const updatedZone = patchEntity(zone, input);
-        await this.connection.getRepository(Zone).save(updatedZone);
+        await this.connection.getRepository(Zone).save(updatedZone, { reload: false });
         await this.updateZonesCache();
         return assertFound(this.findOne(ctx, zone.id));
     }
@@ -103,7 +103,7 @@ export class ZoneService implements OnModuleInit {
         const zone = await getEntityOrThrow(this.connection, Zone, input.zoneId, { relations: ['members'] });
         const members = unique(zone.members.concat(countries), 'id');
         zone.members = members;
-        await this.connection.getRepository(Zone).save(zone);
+        await this.connection.getRepository(Zone).save(zone, { reload: false });
         await this.updateZonesCache();
         return assertFound(this.findOne(ctx, zone.id));
     }
@@ -114,7 +114,7 @@ export class ZoneService implements OnModuleInit {
     ): Promise<Zone> {
         const zone = await getEntityOrThrow(this.connection, Zone, input.zoneId, { relations: ['members'] });
         zone.members = zone.members.filter(country => !input.memberIds.includes(country.id as string));
-        await this.connection.getRepository(Zone).save(zone);
+        await this.connection.getRepository(Zone).save(zone, { reload: false });
         await this.updateZonesCache();
         return assertFound(this.findOne(ctx, zone.id));
     }