Skip to content

Commit

Permalink
perf(core): Add reload: false to .save() operations
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
michaelbromley committed Dec 13, 2019
1 parent e3c9bb6 commit 3c33f33
Show file tree
Hide file tree
Showing 18 changed files with 58 additions and 56 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down Expand Up @@ -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(
Expand All @@ -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;
}
}
6 changes: 3 additions & 3 deletions packages/core/src/service/services/administrator.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand All @@ -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;
}

Expand Down
10 changes: 5 additions & 5 deletions packages/core/src/service/services/channel.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

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

Expand Down Expand Up @@ -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));
}
Expand Down Expand Up @@ -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 });
}
}

Expand Down
8 changes: 4 additions & 4 deletions packages/core/src/service/services/customer-group.service.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -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));
}

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

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

Expand Down
16 changes: 8 additions & 8 deletions packages/core/src/service/services/customer.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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));
}
Expand Down Expand Up @@ -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;
}
Expand All @@ -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));
}

Expand Down Expand Up @@ -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;
}
Expand All @@ -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;
}
Expand Down Expand Up @@ -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 });
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 });
}
}

Expand Down
14 changes: 7 additions & 7 deletions packages/core/src/service/services/order.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down Expand Up @@ -371,15 +371,15 @@ 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);
}

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

Expand All @@ -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);
Expand Down Expand Up @@ -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');
}
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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;
}
Expand Down
8 changes: 4 additions & 4 deletions packages/core/src/service/services/payment-method.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -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);
Expand All @@ -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);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
6 changes: 3 additions & 3 deletions packages/core/src/service/services/product.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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));
}

Expand All @@ -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));
}

Expand Down
4 changes: 2 additions & 2 deletions packages/core/src/service/services/promotion.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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));
}
Expand Down
4 changes: 2 additions & 2 deletions packages/core/src/service/services/role.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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));
}

Expand Down Expand Up @@ -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(
Expand Down
4 changes: 2 additions & 2 deletions packages/core/src/service/services/shipping-method.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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));
}
Expand All @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Loading

0 comments on commit 3c33f33

Please sign in to comment.