Browse Source

perf(core): Optimize setting active order on session

We were previously _always_ setting the active order which involves a relatively
expensive lookup & save on the session table.
Michael Bromley 1 year ago
parent
commit
c591432583

+ 7 - 2
packages/core/src/service/helpers/active-order/active-order.service.ts

@@ -2,6 +2,7 @@ import { Injectable } from '@nestjs/common';
 
 import { RequestContext } from '../../../api/common/request-context';
 import { InternalServerError, UserInputError } from '../../../common/error/errors';
+import { idsAreEqual } from '../../../common/utils';
 import { ConfigService } from '../../../config/config.service';
 import { TransactionalConnection } from '../../../connection/transactional-connection';
 import { Order } from '../../../entity/order/order.entity';
@@ -90,7 +91,7 @@ export class ActiveOrderService {
         input: { [strategyName: string]: Record<string, any> | undefined } | undefined,
         createIfNotExists = false,
     ): Promise<Order | undefined> {
-        let order: any;
+        let order: Order | undefined;
         if (!order) {
             const { activeOrderStrategy } = this.configService.orderOptions;
             const strategyArray = Array.isArray(activeOrderStrategy)
@@ -119,7 +120,11 @@ export class ActiveOrderService {
             }
 
             if (order && ctx.session) {
-                await this.sessionService.setActiveOrder(ctx, ctx.session, order);
+                const orderAlreadyAssignedToSession =
+                    ctx.session.activeOrderId && idsAreEqual(ctx.session.activeOrderId, order.id);
+                if (!orderAlreadyAssignedToSession) {
+                    await this.sessionService.setActiveOrder(ctx, ctx.session, order);
+                }
             }
         }
         return order || undefined;