diff --git a/.changeset/wise-tomatoes-fold.md b/.changeset/wise-tomatoes-fold.md new file mode 100644 index 0000000000..10ff885713 --- /dev/null +++ b/.changeset/wise-tomatoes-fold.md @@ -0,0 +1,5 @@ +--- +"@medusajs/medusa": patch +--- + +feat(medusa): Update transaction base service to expose an activeManager_ getter diff --git a/packages/inventory/src/services/inventory-item.ts b/packages/inventory/src/services/inventory-item.ts index ae86af0cd7..803b3006c0 100644 --- a/packages/inventory/src/services/inventory-item.ts +++ b/packages/inventory/src/services/inventory-item.ts @@ -26,18 +26,11 @@ export default class InventoryItemService extends TransactionBaseService { } protected readonly eventBusService_: IEventBusService - protected manager_: EntityManager - protected transactionManager_: EntityManager | undefined - constructor({ eventBusService, manager }: InjectedDependencies) { + constructor({ eventBusService }: InjectedDependencies) { super(arguments[0]) this.eventBusService_ = eventBusService - this.manager_ = manager - } - - private getManager(): EntityManager { - return this.transactionManager_ ?? this.manager_ } /** @@ -49,7 +42,7 @@ export default class InventoryItemService extends TransactionBaseService { selector: FilterableInventoryItemProps = {}, config: FindConfig = { relations: [], skip: 0, take: 10 } ): Promise { - const queryBuilder = getListQuery(this.getManager(), selector, config) + const queryBuilder = getListQuery(this.activeManager_, selector, config) return await queryBuilder.getMany() } @@ -62,7 +55,7 @@ export default class InventoryItemService extends TransactionBaseService { selector: FilterableInventoryItemProps = {}, config: FindConfig = { relations: [], skip: 0, take: 10 } ): Promise<[InventoryItemDTO[], number]> { - const queryBuilder = getListQuery(this.getManager(), selector, config) + const queryBuilder = getListQuery(this.activeManager_, selector, config) return await queryBuilder.getManyAndCount() } @@ -84,7 +77,7 @@ export default class InventoryItemService extends TransactionBaseService { ) } - const manager = this.getManager() + const manager = this.activeManager_ const itemRepository = manager.getRepository(InventoryItem) const query = buildQuery({ id: inventoryItemId }, config) as FindManyOptions diff --git a/packages/inventory/src/services/inventory-level.ts b/packages/inventory/src/services/inventory-level.ts index f67fac13ff..aad5d60a00 100644 --- a/packages/inventory/src/services/inventory-level.ts +++ b/packages/inventory/src/services/inventory-level.ts @@ -23,20 +23,12 @@ export default class InventoryLevelService extends TransactionBaseService { DELETED: "inventory-level.deleted", } - protected manager_: EntityManager - protected transactionManager_: EntityManager | undefined - protected readonly eventBusService_: IEventBusService - constructor({ eventBusService, manager }: InjectedDependencies) { + constructor({ eventBusService }: InjectedDependencies) { super(arguments[0]) this.eventBusService_ = eventBusService - this.manager_ = manager - } - - private getManager(): EntityManager { - return this.transactionManager_ ?? this.manager_ } /** @@ -49,7 +41,7 @@ export default class InventoryLevelService extends TransactionBaseService { selector: FilterableInventoryLevelProps = {}, config: FindConfig = { relations: [], skip: 0, take: 10 } ): Promise { - const manager = this.getManager() + const manager = this.activeManager_ const levelRepository = manager.getRepository(InventoryLevel) const query = buildQuery(selector, config) as FindManyOptions @@ -66,7 +58,7 @@ export default class InventoryLevelService extends TransactionBaseService { selector: FilterableInventoryLevelProps = {}, config: FindConfig = { relations: [], skip: 0, take: 10 } ): Promise<[InventoryLevel[], number]> { - const manager = this.getManager() + const manager = this.activeManager_ const levelRepository = manager.getRepository(InventoryLevel) const query = buildQuery(selector, config) as FindManyOptions @@ -91,7 +83,7 @@ export default class InventoryLevelService extends TransactionBaseService { ) } - const manager = this.getManager() + const manager = this.activeManager_ const levelRepository = manager.getRepository(InventoryLevel) const query = buildQuery({ id: inventoryLevelId }, config) as FindManyOptions @@ -229,7 +221,7 @@ export default class InventoryLevelService extends TransactionBaseService { locationIds = [locationIds] } - const manager = this.getManager() + const manager = this.activeManager_ const levelRepository = manager.getRepository(InventoryLevel) const result = await levelRepository @@ -256,7 +248,7 @@ export default class InventoryLevelService extends TransactionBaseService { locationIds = [locationIds] } - const manager = this.getManager() + const manager = this.activeManager_ const levelRepository = manager.getRepository(InventoryLevel) const result = await levelRepository @@ -283,7 +275,7 @@ export default class InventoryLevelService extends TransactionBaseService { locationIds = [locationIds] } - const manager = this.getManager() + const manager = this.activeManager_ const levelRepository = manager.getRepository(InventoryLevel) const result = await levelRepository diff --git a/packages/inventory/src/services/inventory.ts b/packages/inventory/src/services/inventory.ts index 6f49d46f47..f4d2116adf 100644 --- a/packages/inventory/src/services/inventory.ts +++ b/packages/inventory/src/services/inventory.ts @@ -36,8 +36,6 @@ export default class InventoryService implements IInventoryService { protected readonly eventBusService_: IEventBusService - protected manager_: EntityManager - protected transactionManager_: EntityManager | undefined protected readonly inventoryItemService_: InventoryItemService protected readonly reservationItemService_: ReservationItemService protected readonly inventoryLevelService_: InventoryLevelService @@ -58,8 +56,6 @@ export default class InventoryService } this.eventBusService_ = eventBusService - this.manager_ = manager - this.inventoryItemService_ = new InventoryItemService({ eventBusService, manager, @@ -75,10 +71,6 @@ export default class InventoryService }) } - private getManager(): EntityManager { - return this.transactionManager_ ?? this.manager_ - } - /** * Lists inventory items that match the given selector * @param selector - the selector to filter inventory items by @@ -90,7 +82,7 @@ export default class InventoryService config: FindConfig = { relations: [], skip: 0, take: 10 } ): Promise<[InventoryItemDTO[], number]> { return await this.inventoryItemService_ - .withTransaction(this.getManager()) + .withTransaction(this.activeManager_) .listAndCount(selector, config) } @@ -105,7 +97,7 @@ export default class InventoryService config: FindConfig = { relations: [], skip: 0, take: 10 } ): Promise<[InventoryLevelDTO[], number]> { return await this.inventoryLevelService_ - .withTransaction(this.getManager()) + .withTransaction(this.activeManager_) .listAndCount(selector, config) } @@ -124,7 +116,7 @@ export default class InventoryService } ): Promise<[ReservationItemDTO[], number]> { return await this.reservationItemService_ - .withTransaction(this.getManager()) + .withTransaction(this.activeManager_) .listAndCount(selector, config) } @@ -139,7 +131,7 @@ export default class InventoryService config?: FindConfig ): Promise { const inventoryItem = await this.inventoryItemService_ - .withTransaction(this.getManager()) + .withTransaction(this.activeManager_) .retrieve(inventoryItemId, config) return { ...inventoryItem } } @@ -155,7 +147,7 @@ export default class InventoryService locationId: string ): Promise { const [inventoryLevel] = await this.inventoryLevelService_ - .withTransaction(this.getManager()) + .withTransaction(this.activeManager_) .list( { inventory_item_id: inventoryItemId, location_id: locationId }, { take: 1 } @@ -179,7 +171,7 @@ export default class InventoryService ): Promise { // Verify that the item is stocked at the location const [inventoryLevel] = await this.inventoryLevelService_ - .withTransaction(this.getManager()) + .withTransaction(this.activeManager_) .list( { inventory_item_id: input.inventory_item_id, @@ -196,7 +188,7 @@ export default class InventoryService } const reservationItem = await this.reservationItemService_ - .withTransaction(this.getManager()) + .withTransaction(this.activeManager_) .create(input) return { ...reservationItem } @@ -211,7 +203,7 @@ export default class InventoryService input: CreateInventoryItemInput ): Promise { const inventoryItem = await this.inventoryItemService_ - .withTransaction(this.getManager()) + .withTransaction(this.activeManager_) .create(input) return { ...inventoryItem } } @@ -225,7 +217,7 @@ export default class InventoryService input: CreateInventoryLevelInput ): Promise { return await this.inventoryLevelService_ - .withTransaction(this.getManager()) + .withTransaction(this.activeManager_) .create(input) } @@ -240,7 +232,7 @@ export default class InventoryService input: Partial ): Promise { const inventoryItem = await this.inventoryItemService_ - .withTransaction(this.getManager()) + .withTransaction(this.activeManager_) .update(inventoryItemId, input) return { ...inventoryItem } } @@ -251,7 +243,7 @@ export default class InventoryService */ async deleteInventoryItem(inventoryItemId: string): Promise { return await this.inventoryItemService_ - .withTransaction(this.getManager()) + .withTransaction(this.activeManager_) .delete(inventoryItemId) } @@ -265,7 +257,7 @@ export default class InventoryService locationId: string ): Promise { const [inventoryLevel] = await this.inventoryLevelService_ - .withTransaction(this.getManager()) + .withTransaction(this.activeManager_) .list( { inventory_item_id: inventoryItemId, location_id: locationId }, { take: 1 } @@ -276,7 +268,7 @@ export default class InventoryService } return await this.inventoryLevelService_ - .withTransaction(this.getManager()) + .withTransaction(this.activeManager_) .delete(inventoryLevel.id) } @@ -293,7 +285,7 @@ export default class InventoryService input: UpdateInventoryLevelInput ): Promise { const [inventoryLevel] = await this.inventoryLevelService_ - .withTransaction(this.getManager()) + .withTransaction(this.activeManager_) .list( { inventory_item_id: inventoryItemId, location_id: locationId }, { take: 1 } @@ -307,7 +299,7 @@ export default class InventoryService } return await this.inventoryLevelService_ - .withTransaction(this.getManager()) + .withTransaction(this.activeManager_) .update(inventoryLevel.id, input) } @@ -322,7 +314,7 @@ export default class InventoryService input: UpdateReservationItemInput ): Promise { return await this.reservationItemService_ - .withTransaction(this.getManager()) + .withTransaction(this.activeManager_) .update(reservationItemId, input) } @@ -332,7 +324,7 @@ export default class InventoryService */ async deleteReservationItemsByLineItem(lineItemId: string): Promise { return await this.reservationItemService_ - .withTransaction(this.getManager()) + .withTransaction(this.activeManager_) .deleteByLineItem(lineItemId) } @@ -342,7 +334,7 @@ export default class InventoryService */ async deleteReservationItem(reservationItemId: string): Promise { return await this.reservationItemService_ - .withTransaction(this.getManager()) + .withTransaction(this.activeManager_) .delete(reservationItemId) } @@ -360,7 +352,7 @@ export default class InventoryService adjustment: number ): Promise { const [inventoryLevel] = await this.inventoryLevelService_ - .withTransaction(this.getManager()) + .withTransaction(this.activeManager_) .list( { inventory_item_id: inventoryItemId, location_id: locationId }, { take: 1 } @@ -373,7 +365,7 @@ export default class InventoryService } const updatedInventoryLevel = await this.inventoryLevelService_ - .withTransaction(this.getManager()) + .withTransaction(this.activeManager_) .update(inventoryLevel.id, { stocked_quantity: inventoryLevel.stocked_quantity + adjustment, }) @@ -394,13 +386,13 @@ export default class InventoryService ): Promise { // Throws if item does not exist await this.inventoryItemService_ - .withTransaction(this.getManager()) + .withTransaction(this.activeManager_) .retrieve(inventoryItemId, { select: ["id"], }) const availableQuantity = await this.inventoryLevelService_ - .withTransaction(this.getManager()) + .withTransaction(this.activeManager_) .getAvailableQuantity(inventoryItemId, locationIds) return availableQuantity @@ -419,13 +411,13 @@ export default class InventoryService ): Promise { // Throws if item does not exist await this.inventoryItemService_ - .withTransaction(this.getManager()) + .withTransaction(this.activeManager_) .retrieve(inventoryItemId, { select: ["id"], }) const stockedQuantity = await this.inventoryLevelService_ - .withTransaction(this.getManager()) + .withTransaction(this.activeManager_) .getStockedQuantity(inventoryItemId, locationIds) return stockedQuantity @@ -444,13 +436,13 @@ export default class InventoryService ): Promise { // Throws if item does not exist await this.inventoryItemService_ - .withTransaction(this.getManager()) + .withTransaction(this.activeManager_) .retrieve(inventoryItemId, { select: ["id"], }) const reservedQuantity = await this.inventoryLevelService_ - .withTransaction(this.getManager()) + .withTransaction(this.activeManager_) .getReservedQuantity(inventoryItemId, locationIds) return reservedQuantity diff --git a/packages/inventory/src/services/reservation-item.ts b/packages/inventory/src/services/reservation-item.ts index 80b2f6471a..d1f5d3279e 100644 --- a/packages/inventory/src/services/reservation-item.ts +++ b/packages/inventory/src/services/reservation-item.ts @@ -1,17 +1,16 @@ import { EntityManager, FindManyOptions } from "typeorm" import { isDefined, MedusaError } from "medusa-core-utils" import { - FindConfig, buildQuery, - IEventBusService, - FilterableReservationItemProps, CreateReservationItemInput, + FilterableReservationItemProps, + FindConfig, + IEventBusService, TransactionBaseService, UpdateReservationItemInput, } from "@medusajs/medusa" import { ReservationItem } from "../models" -import { CONNECTION_NAME } from "../config" import { InventoryLevelService } from "." type InjectedDependencies = { @@ -28,27 +27,19 @@ export default class ReservationItemService extends TransactionBaseService { DELETED_BY_LINE_ITEM: "reservation-item.deleted-by-line-item", } - protected manager_: EntityManager - protected transactionManager_: EntityManager | undefined protected readonly eventBusService_: IEventBusService protected readonly inventoryLevelService_: InventoryLevelService constructor({ eventBusService, - manager, inventoryLevelService, }: InjectedDependencies) { super(arguments[0]) - this.manager_ = manager this.eventBusService_ = eventBusService this.inventoryLevelService_ = inventoryLevelService } - private getManager(): EntityManager { - return this.transactionManager_ ?? this.manager_ - } - /** * Lists reservation items that match the provided filter. * @param selector - Filters to apply to the reservation items. @@ -59,7 +50,7 @@ export default class ReservationItemService extends TransactionBaseService { selector: FilterableReservationItemProps = {}, config: FindConfig = { relations: [], skip: 0, take: 10 } ): Promise { - const manager = this.getManager() + const manager = this.activeManager_ const itemRepository = manager.getRepository(ReservationItem) const query = buildQuery(selector, config) as FindManyOptions @@ -76,7 +67,7 @@ export default class ReservationItemService extends TransactionBaseService { selector: FilterableReservationItemProps = {}, config: FindConfig = { relations: [], skip: 0, take: 10 } ): Promise<[ReservationItem[], number]> { - const manager = this.getManager() + const manager = this.activeManager_ const itemRepository = manager.getRepository(ReservationItem) const query = buildQuery(selector, config) as FindManyOptions @@ -101,7 +92,7 @@ export default class ReservationItemService extends TransactionBaseService { ) } - const manager = this.getManager() + const manager = this.activeManager_ const reservationItemRepository = manager.getRepository(ReservationItem) const query = buildQuery({ id: reservationItemId }, config) as FindManyOptions diff --git a/packages/medusa/src/interfaces/__tests__/transaction-base-service.spec.ts b/packages/medusa/src/interfaces/__tests__/transaction-base-service.spec.ts index 44815a73fa..0fdffc9fd3 100644 --- a/packages/medusa/src/interfaces/__tests__/transaction-base-service.spec.ts +++ b/packages/medusa/src/interfaces/__tests__/transaction-base-service.spec.ts @@ -1,13 +1,9 @@ -import { EntityManager } from "typeorm" import { MockManager } from "medusa-test-utils" import { TransactionBaseService } from "../transaction-base-service" describe("TransactionBaseService", () => { it("should cloned the child class withTransaction", () => { class Child extends TransactionBaseService { - protected manager_!: EntityManager - protected transactionManager_!: EntityManager - constructor(protected readonly container) { super(container); this.container = container diff --git a/packages/medusa/src/interfaces/transaction-base-service.ts b/packages/medusa/src/interfaces/transaction-base-service.ts index aadccd649b..87158f0dc0 100644 --- a/packages/medusa/src/interfaces/transaction-base-service.ts +++ b/packages/medusa/src/interfaces/transaction-base-service.ts @@ -2,14 +2,20 @@ import { EntityManager } from "typeorm" import { IsolationLevel } from "typeorm/driver/types/IsolationLevel" export abstract class TransactionBaseService { - protected abstract manager_: EntityManager - protected abstract transactionManager_: EntityManager | undefined + protected manager_: EntityManager + protected transactionManager_: EntityManager | undefined + + protected get activeManager_(): EntityManager { + return this.transactionManager_ ?? this.manager_ + } protected constructor( protected readonly __container__: any, protected readonly __configModule__?: Record, protected readonly __moduleDeclaration__?: Record - ) {} + ) { + this.manager_ = __container__.manager + } withTransaction(transactionManager?: EntityManager): this { if (!transactionManager) { diff --git a/packages/medusa/src/loaders/__tests__/plugins.spec.ts b/packages/medusa/src/loaders/__tests__/plugins.spec.ts index 1f35edc23b..1faf3d4a2b 100644 --- a/packages/medusa/src/loaders/__tests__/plugins.spec.ts +++ b/packages/medusa/src/loaders/__tests__/plugins.spec.ts @@ -1,16 +1,17 @@ import { - createContainer, - asValue, - Resolver, - ClassOrFunctionReturning, asFunction, + asValue, AwilixContainer, + ClassOrFunctionReturning, + createContainer, + Resolver, } from "awilix" import { mkdirSync, rmSync, writeFileSync } from "fs" import { resolve } from "path" import Logger from "../logger" import { registerServices, registerStrategies } from "../plugins" import { MedusaContainer } from "../../types/global" +import { Connection, EntityManager } from "typeorm"; // ***** TEMPLATES ***** const buildServiceTemplate = (name: string): string => { @@ -135,6 +136,8 @@ describe("plugins loader", () => { }.bind(container) container.register("logger", asValue(Logger)) + container.register("manager", asValue(new EntityManager({} as Connection))) + const pluginsDetails = { resolve: resolve(__dirname, "__pluginsLoaderTest__"), name: `project-plugin`, diff --git a/packages/medusa/src/services/__tests__/product-category.ts b/packages/medusa/src/services/__tests__/product-category.ts index 3d4b8e8ea2..8631a4daa0 100644 --- a/packages/medusa/src/services/__tests__/product-category.ts +++ b/packages/medusa/src/services/__tests__/product-category.ts @@ -1,14 +1,10 @@ -import { - IdMap, - MockRepository, - MockManager as manager -} from "medusa-test-utils" +import { IdMap, MockManager as manager } from "medusa-test-utils" import ProductCategoryService from "../product-category" import { EventBusService } from "../" import { + invalidProdCategoryId, productCategoryRepositoryMock as productCategoryRepository, validProdCategoryId, - invalidProdCategoryId, validProdCategoryIdWithChildren, } from "../../repositories/__mocks__/product-category" import { EventBusServiceMock as eventBusService } from "../__mocks__/event-bus" diff --git a/packages/medusa/src/services/analytics-config.ts b/packages/medusa/src/services/analytics-config.ts index 3784c8f60e..7662771e31 100644 --- a/packages/medusa/src/services/analytics-config.ts +++ b/packages/medusa/src/services/analytics-config.ts @@ -15,24 +15,18 @@ type InjectedDependencies = { } class AnalyticsConfigService extends TransactionBaseService { - protected manager_: EntityManager - protected transactionManager_: EntityManager | undefined - protected readonly analyticsConfigRepository_: typeof AnalyticsRepository protected readonly userService_: UserService - constructor({ analyticsConfigRepository, manager }: InjectedDependencies) { + constructor({ analyticsConfigRepository }: InjectedDependencies) { // eslint-disable-next-line prefer-rest-params super(arguments[0]) - this.manager_ = manager this.analyticsConfigRepository_ = analyticsConfigRepository } async retrieve(userId: string): Promise { - const manager = this.manager_ - - const analyticsRepo = manager.withRepository( + const analyticsRepo = this.activeManager_.withRepository( this.analyticsConfigRepository_ ) @@ -57,8 +51,7 @@ class AnalyticsConfigService extends TransactionBaseService { userId: string, data: CreateAnalyticsConfig ): Promise { - const manager = this.transactionManager_ || this.manager_ - const analyticsRepo = manager.withRepository( + const analyticsRepo = this.activeManager_.withRepository( this.analyticsConfigRepository_ ) @@ -73,9 +66,7 @@ class AnalyticsConfigService extends TransactionBaseService { userId: string, update: UpdateAnalyticsConfig ): Promise { - const manager = this.transactionManager_ || this.manager_ - - const analyticsRepo = manager.withRepository( + const analyticsRepo = this.activeManager_.withRepository( this.analyticsConfigRepository_ ) @@ -101,8 +92,7 @@ class AnalyticsConfigService extends TransactionBaseService { * Deletes an analytics config. */ async delete(userId: string): Promise { - const manager = this.transactionManager_ || this.manager_ - const analyticsRepo = manager.withRepository( + const analyticsRepo = this.activeManager_.withRepository( this.analyticsConfigRepository_ ) diff --git a/packages/medusa/src/services/auth.ts b/packages/medusa/src/services/auth.ts index f980c7dafb..28388a2a74 100644 --- a/packages/medusa/src/services/auth.ts +++ b/packages/medusa/src/services/auth.ts @@ -16,15 +16,13 @@ type InjectedDependencies = { * Can authenticate a user based on email password combination */ class AuthService extends TransactionBaseService { - protected manager_: EntityManager - protected transactionManager_: EntityManager | undefined protected readonly userService_: UserService protected readonly customerService_: CustomerService - constructor({ manager, userService, customerService }: InjectedDependencies) { + constructor({ userService, customerService }: InjectedDependencies) { + // eslint-disable-next-line prefer-rest-params super(arguments[0]) - this.manager_ = manager this.userService_ = userService this.customerService_ = customerService } diff --git a/packages/medusa/src/services/batch-job.ts b/packages/medusa/src/services/batch-job.ts index ada355b786..e36b3de043 100644 --- a/packages/medusa/src/services/batch-job.ts +++ b/packages/medusa/src/services/batch-job.ts @@ -35,9 +35,6 @@ class BatchJobService extends TransactionBaseService { FAILED: "batch.failed", } - protected manager_: EntityManager - protected transactionManager_: EntityManager | undefined - protected readonly batchJobRepository_: typeof BatchJobRepository protected readonly eventBus_: EventBusService protected readonly strategyResolver_: StrategyResolverService @@ -91,7 +88,6 @@ class BatchJobService extends TransactionBaseService { ]) constructor({ - manager, batchJobRepository, eventBusService, strategyResolverService, @@ -99,7 +95,6 @@ class BatchJobService extends TransactionBaseService { // eslint-disable-next-line prefer-rest-params super(arguments[0]) - this.manager_ = manager this.batchJobRepository_ = batchJobRepository this.eventBus_ = eventBusService this.strategyResolver_ = strategyResolverService @@ -116,8 +111,9 @@ class BatchJobService extends TransactionBaseService { ) } - const manager = this.manager_ - const batchJobRepo = manager.withRepository(this.batchJobRepository_) + const batchJobRepo = this.activeManager_.withRepository( + this.batchJobRepository_ + ) const query = buildQuery({ id: batchJobId }, config) const batchJob = await batchJobRepo.findOne(query) @@ -136,8 +132,9 @@ class BatchJobService extends TransactionBaseService { selector: FilterableBatchJobProps = {}, config: FindConfig = { skip: 0, take: 20 } ): Promise<[BatchJob[], number]> { - const manager = this.manager_ - const batchJobRepo = manager.withRepository(this.batchJobRepository_) + const batchJobRepo = this.activeManager_.withRepository( + this.batchJobRepository_ + ) const query = buildQuery(selector, config) return await batchJobRepo.findAndCount(query) @@ -203,7 +200,6 @@ class BatchJobService extends TransactionBaseService { batchJobOrId: BatchJob | string, status: BatchJobStatus ): Promise { - const transactionManager = this.transactionManager_ ?? this.manager_ let batchJob: BatchJob = batchJobOrId as BatchJob if (typeof batchJobOrId === "string") { batchJob = await this.retrieve(batchJobOrId) @@ -221,13 +217,13 @@ class BatchJobService extends TransactionBaseService { batchJob[entityColumnName] = new Date() - const batchJobRepo = transactionManager.withRepository( + const batchJobRepo = this.activeManager_.withRepository( this.batchJobRepository_ ) batchJob = await batchJobRepo.save(batchJob) batchJob.loadStatus() - await this.eventBus_.withTransaction(transactionManager).emit(eventType, { + await this.eventBus_.withTransaction(this.activeManager_).emit(eventType, { id: batchJob.id, }) diff --git a/packages/medusa/src/services/cart.ts b/packages/medusa/src/services/cart.ts index a2deffc4a5..01d9bfca2b 100644 --- a/packages/medusa/src/services/cart.ts +++ b/packages/medusa/src/services/cart.ts @@ -104,9 +104,6 @@ class CartService extends TransactionBaseService { UPDATED: "cart.updated", } - protected manager_: EntityManager - protected transactionManager_: EntityManager | undefined - protected readonly shippingMethodRepository_: typeof ShippingMethodRepository protected readonly cartRepository_: typeof CartRepository protected readonly addressRepository_: typeof AddressRepository @@ -135,7 +132,6 @@ class CartService extends TransactionBaseService { protected readonly productVariantInventoryService_: ProductVariantInventoryService constructor({ - manager, cartRepository, shippingMethodRepository, lineItemRepository, @@ -165,7 +161,6 @@ class CartService extends TransactionBaseService { // eslint-disable-next-line prefer-rest-params super(arguments[0]) - this.manager_ = manager this.shippingMethodRepository_ = shippingMethodRepository this.cartRepository_ = cartRepository this.lineItemRepository_ = lineItemRepository @@ -202,8 +197,7 @@ class CartService extends TransactionBaseService { selector: FilterableCartProps, config: FindConfig = {} ): Promise { - const manager = this.manager_ - const cartRepo = manager.withRepository(this.cartRepository_) + const cartRepo = this.activeManager_.withRepository(this.cartRepository_) const query = buildQuery(selector, config) return await cartRepo.find(query) @@ -234,8 +228,8 @@ class CartService extends TransactionBaseService { return await this.retrieveLegacy(cartId, options, totalsConfig) } - const manager = this.manager_ - const cartRepo = manager.withRepository(this.cartRepository_) + const cartRepo = this.activeManager_.withRepository(this.cartRepository_) + const query = buildQuery({ id: cartId }, options) if ((options.select || []).length === 0) { @@ -266,8 +260,7 @@ class CartService extends TransactionBaseService { options: FindConfig = {}, totalsConfig: TotalsConfig = {} ): Promise { - const manager = this.manager_ - const cartRepo = manager.withRepository(this.cartRepository_) + const cartRepo = this.activeManager_.withRepository(this.cartRepository_) const { select, relations, totalsToSelect } = this.transformQueryForTotals_(options) @@ -454,11 +447,11 @@ class CartService extends TransactionBaseService { let salesChannel: SalesChannel if (isDefined(salesChannelId)) { salesChannel = await this.salesChannelService_ - .withTransaction(this.manager_) + .withTransaction(this.activeManager_) .retrieve(salesChannelId) } else { salesChannel = ( - await this.storeService_.withTransaction(this.manager_).retrieve({ + await this.storeService_.withTransaction(this.activeManager_).retrieve({ relations: ["default_sales_channel"], }) ).default_sales_channel @@ -527,7 +520,7 @@ class CartService extends TransactionBaseService { "items.variant.product", "discounts", "discounts.rule", - "region" + "region", ], }) @@ -595,12 +588,12 @@ class CartService extends TransactionBaseService { const lineItemVariant = lineItem.variant?.product_id ? lineItem.variant : await this.productVariantService_ - .withTransaction(this.manager_) + .withTransaction(this.activeManager_) .retrieve(lineItem.variant_id, { select: ["id", "product_id"] }) return !!( await this.productService_ - .withTransaction(this.manager_) + .withTransaction(this.activeManager_) .filterProductsBySalesChannel( [lineItemVariant.product_id], sales_channel_id @@ -722,7 +715,14 @@ class CartService extends TransactionBaseService { }) cart = await this.retrieve(cart.id, { - relations: ["items", "items.variant", "items.variant.product", "discounts", "discounts.rule", "region"], + relations: [ + "items", + "items.variant", + "items.variant.product", + "discounts", + "discounts.rule", + "region", + ], }) await this.refreshAdjustments_(cart) @@ -901,7 +901,7 @@ class CartService extends TransactionBaseService { "items.variant.product", "discounts", "discounts.rule", - "region" + "region", ], }) @@ -980,7 +980,7 @@ class CartService extends TransactionBaseService { "items.variant.product", "discounts", "discounts.rule", - "region" + "region", ], }) @@ -1009,10 +1009,8 @@ class CartService extends TransactionBaseService { cart: Cart, shouldAdd: boolean ): Promise { - const transactionManager = this.transactionManager_ ?? this.manager_ - if (cart.shipping_methods?.length) { - const shippingMethodRepository = transactionManager.withRepository( + const shippingMethodRepository = this.activeManager_.withRepository( this.shippingMethodRepository_ ) @@ -1233,7 +1231,7 @@ class CartService extends TransactionBaseService { const productIds = cart.items.map((item) => item.variant.product_id) const productsToKeep = await this.productService_ - .withTransaction(this.manager_) + .withTransaction(this.activeManager_) .filterProductsBySalesChannel(productIds, newSalesChannelId, { select: ["id"], take: productIds.length, @@ -1266,7 +1264,7 @@ class CartService extends TransactionBaseService { customerId: string ): Promise { const customer = await this.customerService_ - .withTransaction(this.transactionManager_) + .withTransaction(this.activeManager_) .retrieve(customerId) cart.customer = customer @@ -1284,15 +1282,16 @@ class CartService extends TransactionBaseService { ): Promise { const validatedEmail = validateEmail(email) - let customer = await this.customerService_ - .withTransaction(this.transactionManager_) + const customerServiceTx = this.customerService_.withTransaction( + this.activeManager_ + ) + + let customer = await customerServiceTx .retrieveUnregisteredByEmail(validatedEmail) .catch(() => undefined) if (!customer) { - customer = await this.customerService_ - .withTransaction(this.transactionManager_) - .create({ email: validatedEmail }) + customer = await customerServiceTx.create({ email: validatedEmail }) } return customer @@ -1394,7 +1393,7 @@ class CartService extends TransactionBaseService { protected async applyGiftCard_(cart: Cart, code: string): Promise { const giftCard = await this.giftCardService_ - .withTransaction(this.transactionManager_) + .withTransaction(this.activeManager_) .retrieveByCode(code) if (giftCard.is_disabled) { @@ -1618,7 +1617,12 @@ class CartService extends TransactionBaseService { ) const cart = await this.retrieveWithTotals(cartId, { - relations: ["payment_sessions", "items", "items.variant", "items.variant.product"], + relations: [ + "payment_sessions", + "items", + "items.variant", + "items.variant.product", + ], }) // If cart total is 0, we don't perform anything payment related @@ -2213,20 +2217,19 @@ class CartService extends TransactionBaseService { regionId?: string, customer_id?: string ): Promise { - const transactionManager = this.transactionManager_ ?? this.manager_ - // If the cart contains items, we update the price of the items // to match the updated region or customer id (keeping the old // value if it exists) if (cart.items?.length) { const region = await this.regionService_ - .withTransaction(this.transactionManager_) + .withTransaction(this.activeManager_) .retrieve(regionId || cart.region_id, { relations: ["countries"], }) - const lineItemServiceTx = - this.lineItemService_.withTransaction(transactionManager) + const lineItemServiceTx = this.lineItemService_.withTransaction( + this.activeManager_ + ) cart.items = ( await Promise.all( @@ -2236,7 +2239,7 @@ class CartService extends TransactionBaseService { } const availablePrice = await this.priceSelectionStrategy_ - .withTransaction(transactionManager) + .withTransaction(this.activeManager_) .calculateVariantPrice(item.variant_id, { region_id: region.id, currency_code: region.currency_code, @@ -2281,8 +2284,6 @@ class CartService extends TransactionBaseService { regionId: string, countryCode: string | null ): Promise { - const transactionManager = this.transactionManager_ ?? this.manager_ - if (cart.completed_at || cart.payment_authorized_at) { throw new MedusaError( MedusaError.Types.NOT_ALLOWED, @@ -2291,14 +2292,14 @@ class CartService extends TransactionBaseService { } const region = await this.regionService_ - .withTransaction(transactionManager) + .withTransaction(this.activeManager_) .retrieve(regionId, { relations: ["countries"], }) cart.region = region cart.region_id = region.id - const addrRepo = transactionManager.withRepository(this.addressRepository_) + const addrRepo = this.activeManager_.withRepository(this.addressRepository_) /* * When changing the region you are changing the set of countries that your * cart can be shipped to so we need to make sure that the current shipping @@ -2372,7 +2373,7 @@ class CartService extends TransactionBaseService { // new shipping method if (cart.shipping_methods && cart.shipping_methods.length) { await this.shippingOptionService_ - .withTransaction(transactionManager) + .withTransaction(this.activeManager_) .deleteShippingMethods(cart.shipping_methods) } @@ -2390,7 +2391,7 @@ class CartService extends TransactionBaseService { cart.gift_cards = [] if (cart.payment_sessions && cart.payment_sessions.length) { - const paymentSessionRepo = transactionManager.withRepository( + const paymentSessionRepo = this.activeManager_.withRepository( this.paymentSessionRepository_ ) await paymentSessionRepo.delete({ @@ -2547,8 +2548,9 @@ class CartService extends TransactionBaseService { cart: Cart, totalsConfig: TotalsConfig = {} ): Promise> { - const manager = this.transactionManager_ ?? this.manager_ - const newTotalsServiceTx = this.newTotalsService_.withTransaction(manager) + const newTotalsServiceTx = this.newTotalsService_.withTransaction( + this.activeManager_ + ) const calculationContext = await this.totalsService_.getCalculationContext( cart @@ -2559,7 +2561,7 @@ class CartService extends TransactionBaseService { if (includeTax) { const taxLinesMaps = await this.taxProviderService_ - .withTransaction(manager) + .withTransaction(this.activeManager_) .getTaxLinesMap(cartItems, calculationContext) cartItems.forEach((item) => { @@ -2638,24 +2640,21 @@ class CartService extends TransactionBaseService { } protected async refreshAdjustments_(cart: Cart): Promise { - const transactionManager = this.transactionManager_ ?? this.manager_ - const nonReturnLineIDs = cart.items .filter((item) => !item.is_return) .map((i) => i.id) + const lineItemAdjustmentServiceTx = + this.lineItemAdjustmentService_.withTransaction(this.activeManager_) + // delete all old non return line item adjustments - await this.lineItemAdjustmentService_ - .withTransaction(transactionManager) - .delete({ - item_id: nonReturnLineIDs, - discount_id: Not(IsNull()), - }) + await lineItemAdjustmentServiceTx.delete({ + item_id: nonReturnLineIDs, + discount_id: Not(IsNull()), + }) // potentially create/update line item adjustments - await this.lineItemAdjustmentService_ - .withTransaction(transactionManager) - .createAdjustments(cart) + await lineItemAdjustmentServiceTx.createAdjustments(cart) } protected transformQueryForTotals_( diff --git a/packages/medusa/src/services/claim-item.ts b/packages/medusa/src/services/claim-item.ts index c9ec3c98e7..3f2c424825 100644 --- a/packages/medusa/src/services/claim-item.ts +++ b/packages/medusa/src/services/claim-item.ts @@ -1,5 +1,4 @@ import { isDefined, MedusaError } from "medusa-core-utils" -import { EntityManager } from "typeorm" import { TransactionBaseService } from "../interfaces" import { ClaimImage, ClaimItem, ClaimTag } from "../models" import { ClaimImageRepository } from "../repositories/claim-image" @@ -24,11 +23,7 @@ class ClaimItemService extends TransactionBaseService { protected readonly claimTagRepository_: typeof ClaimTagRepository protected readonly claimImageRepository_: typeof ClaimImageRepository - protected manager_: EntityManager - protected transactionManager_: EntityManager | undefined - constructor({ - manager, claimItemRepository, claimTagRepository, claimImageRepository, @@ -38,7 +33,6 @@ class ClaimItemService extends TransactionBaseService { // eslint-disable-next-line prefer-rest-params super(arguments[0]) - this.manager_ = manager this.claimItemRepository_ = claimItemRepository this.claimTagRepository_ = claimTagRepository this.claimImageRepository_ = claimImageRepository @@ -216,7 +210,7 @@ class ClaimItemService extends TransactionBaseService { order: { created_at: "DESC" }, } ): Promise { - const ciRepo = this.manager_.withRepository(this.claimItemRepository_) + const ciRepo = this.activeManager_.withRepository(this.claimItemRepository_) const query = buildQuery(selector, config) return ciRepo.find(query) } @@ -238,7 +232,7 @@ class ClaimItemService extends TransactionBaseService { ) } - const claimItemRepo = this.manager_.withRepository( + const claimItemRepo = this.activeManager_.withRepository( this.claimItemRepository_ ) const query = buildQuery({ id: claimItemId }, config) diff --git a/packages/medusa/src/services/claim.ts b/packages/medusa/src/services/claim.ts index d847e6b8f2..15f9f8b401 100644 --- a/packages/medusa/src/services/claim.ts +++ b/packages/medusa/src/services/claim.ts @@ -65,9 +65,6 @@ export default class ClaimService extends TransactionBaseService { REFUND_PROCESSED: "claim.refund_processed", } - protected manager_: EntityManager - protected transactionManager_: EntityManager | undefined - protected readonly addressRepository_: typeof AddressRepository protected readonly claimRepository_: typeof ClaimRepository protected readonly shippingMethodRepository_: typeof ShippingMethodRepository @@ -87,7 +84,6 @@ export default class ClaimService extends TransactionBaseService { protected readonly productVariantInventoryService_: ProductVariantInventoryService constructor({ - manager, addressRepository, claimRepository, shippingMethodRepository, @@ -108,8 +104,6 @@ export default class ClaimService extends TransactionBaseService { // eslint-disable-next-line prefer-rest-params super(arguments[0]) - this.manager_ = manager - this.addressRepository_ = addressRepository this.claimRepository_ = claimRepository this.shippingMethodRepository_ = shippingMethodRepository @@ -875,8 +869,7 @@ export default class ClaimService extends TransactionBaseService { order: { created_at: "DESC" }, } ): Promise { - const manager = this.manager_ - const claimRepo = manager.withRepository(this.claimRepository_) + const claimRepo = this.activeManager_.withRepository(this.claimRepository_) const query = buildQuery(selector, config) return await claimRepo.find(query) } @@ -898,8 +891,7 @@ export default class ClaimService extends TransactionBaseService { ) } - const manager = this.manager_ - const claimRepo = manager.withRepository(this.claimRepository_) + const claimRepo = this.activeManager_.withRepository(this.claimRepository_) const query = buildQuery({ id: claimId }, config) const claim = await claimRepo.findOne(query) diff --git a/packages/medusa/src/services/currency.ts b/packages/medusa/src/services/currency.ts index afa16b9b19..b24d2b5755 100644 --- a/packages/medusa/src/services/currency.ts +++ b/packages/medusa/src/services/currency.ts @@ -22,21 +22,18 @@ export default class CurrencyService extends TransactionBaseService { UPDATED: "currency.updated", } - protected manager_: EntityManager - protected transactionManager_: EntityManager | undefined - protected readonly currencyRepository_: typeof CurrencyRepository protected readonly eventBusService_: EventBusService protected readonly featureFlagRouter_: FlagRouter constructor({ - manager, currencyRepository, eventBusService, featureFlagRouter, }: InjectedDependencies) { + // eslint-disable-next-line prefer-rest-params super(arguments[0]) - this.manager_ = manager + this.currencyRepository_ = currencyRepository this.eventBusService_ = eventBusService this.featureFlagRouter_ = featureFlagRouter @@ -48,7 +45,7 @@ export default class CurrencyService extends TransactionBaseService { * @return The currency */ async retrieveByCode(code: string): Promise { - const currencyRepo = this.manager_.withRepository( + const currencyRepo = this.activeManager_.withRepository( this.currencyRepository_ ) @@ -85,7 +82,7 @@ export default class CurrencyService extends TransactionBaseService { take: 20, } ): Promise<[Currency[], number]> { - const productRepo = this.manager_.withRepository( + const productRepo = this.activeManager_.withRepository( this.currencyRepository_ ) diff --git a/packages/medusa/src/services/custom-shipping-option.ts b/packages/medusa/src/services/custom-shipping-option.ts index 75d97bfbcb..10eea7baa4 100644 --- a/packages/medusa/src/services/custom-shipping-option.ts +++ b/packages/medusa/src/services/custom-shipping-option.ts @@ -12,19 +12,13 @@ type InjectedDependencies = { customShippingOptionRepository: typeof CustomShippingOptionRepository } class CustomShippingOptionService extends TransactionBaseService { - protected manager_: EntityManager - protected transactionManager_: EntityManager | undefined // eslint-disable-next-line max-len protected customShippingOptionRepository_: typeof CustomShippingOptionRepository - constructor({ - manager, - customShippingOptionRepository, - }: InjectedDependencies) { + constructor({ customShippingOptionRepository }: InjectedDependencies) { // eslint-disable-next-line prefer-rest-params super(arguments[0]) - this.manager_ = manager this.customShippingOptionRepository_ = customShippingOptionRepository } @@ -38,8 +32,7 @@ class CustomShippingOptionService extends TransactionBaseService { id: string, config: FindConfig = {} ): Promise { - const manager = this.manager_ - const customShippingOptionRepo = manager.withRepository( + const customShippingOptionRepo = this.activeManager_.withRepository( this.customShippingOptionRepository_ ) @@ -70,8 +63,7 @@ class CustomShippingOptionService extends TransactionBaseService { relations: [], } ): Promise { - const manager = this.manager_ - const customShippingOptionRepo = manager.withRepository( + const customShippingOptionRepo = this.activeManager_.withRepository( this.customShippingOptionRepository_ ) @@ -91,8 +83,7 @@ class CustomShippingOptionService extends TransactionBaseService { ): Promise { const { cart_id, shipping_option_id, price, metadata } = data - const manager = this.manager_ - const customShippingOptionRepo = manager.withRepository( + const customShippingOptionRepo = this.activeManager_.withRepository( this.customShippingOptionRepository_ ) diff --git a/packages/medusa/src/services/customer-group.ts b/packages/medusa/src/services/customer-group.ts index b293861e6f..33669a48b1 100644 --- a/packages/medusa/src/services/customer-group.ts +++ b/packages/medusa/src/services/customer-group.ts @@ -18,21 +18,16 @@ type CustomerGroupConstructorProps = { } class CustomerGroupService extends TransactionBaseService { - protected manager_: EntityManager - protected transactionManager_: EntityManager | undefined - protected readonly customerGroupRepository_: typeof CustomerGroupRepository protected readonly customerService_: CustomerService constructor({ - manager, customerGroupRepository, customerService, }: CustomerGroupConstructorProps) { // eslint-disable-next-line prefer-rest-params super(arguments[0]) - this.manager_ = manager this.customerGroupRepository_ = customerGroupRepository this.customerService_ = customerService } @@ -45,7 +40,9 @@ class CustomerGroupService extends TransactionBaseService { ) } - const cgRepo = this.manager_.withRepository(this.customerGroupRepository_) + const cgRepo = this.activeManager_.withRepository( + this.customerGroupRepository_ + ) const query = buildQuery({ id: customerGroupId }, config) @@ -201,7 +198,7 @@ class CustomerGroupService extends TransactionBaseService { } = {}, config: FindConfig ): Promise<[CustomerGroup[], number]> { - const cgRepo: typeof CustomerGroupRepository = this.manager_.withRepository( + const cgRepo = this.activeManager_.withRepository( this.customerGroupRepository_ ) @@ -240,7 +237,7 @@ class CustomerGroupService extends TransactionBaseService { id: string, customerIds: string[] | string ): Promise { - const cgRepo: typeof CustomerGroupRepository = this.manager_.withRepository( + const cgRepo = this.activeManager_.withRepository( this.customerGroupRepository_ ) let ids: string[] diff --git a/packages/medusa/src/services/customer.ts b/packages/medusa/src/services/customer.ts index b60f579d87..d10eafbe9f 100644 --- a/packages/medusa/src/services/customer.ts +++ b/packages/medusa/src/services/customer.ts @@ -37,9 +37,6 @@ class CustomerService extends TransactionBaseService { protected readonly addressRepository_: typeof AddressRepository protected readonly eventBusService_: EventBusService - protected readonly manager_: EntityManager - protected readonly transactionManager_: EntityManager | undefined - static Events = { PASSWORD_RESET: "customer.password_reset", CREATED: "customer.created", @@ -47,7 +44,6 @@ class CustomerService extends TransactionBaseService { } constructor({ - manager, customerRepository, eventBusService, addressRepository, @@ -55,8 +51,6 @@ class CustomerService extends TransactionBaseService { // eslint-disable-next-line prefer-rest-params super(arguments[0]) - this.manager_ = manager - this.customerRepository_ = customerRepository this.eventBusService_ = eventBusService this.addressRepository_ = addressRepository @@ -118,8 +112,9 @@ class CustomerService extends TransactionBaseService { selector: Selector & { q?: string; groups?: string[] } = {}, config: FindConfig = { relations: [], skip: 0, take: 50 } ): Promise { - const manager = this.manager_ - const customerRepo = manager.withRepository(this.customerRepository_) + const customerRepo = this.activeManager_.withRepository( + this.customerRepository_ + ) let q if ("q" in selector) { @@ -154,8 +149,9 @@ class CustomerService extends TransactionBaseService { order: { created_at: "DESC" }, } ): Promise<[Customer[], number]> { - const manager = this.manager_ - const customerRepo = manager.withRepository(this.customerRepository_) + const customerRepo = this.activeManager_.withRepository( + this.customerRepository_ + ) let q if ("q" in selector) { @@ -180,8 +176,9 @@ class CustomerService extends TransactionBaseService { * @return {Promise} the result of the count operation */ async count(): Promise { - const manager = this.manager_ - const customerRepo = manager.withRepository(this.customerRepository_) + const customerRepo = this.activeManager_.withRepository( + this.customerRepository_ + ) return await customerRepo.count({}) } @@ -189,9 +186,9 @@ class CustomerService extends TransactionBaseService { selector: Selector, config: FindConfig = {} ): Promise { - const manager = this.transactionManager_ ?? this.manager_ - - const customerRepo = manager.withRepository(this.customerRepository_) + const customerRepo = this.activeManager_.withRepository( + this.customerRepository_ + ) const query = buildQuery(selector, config) const customer = await customerRepo.findOne(query) diff --git a/packages/medusa/src/services/discount-condition.ts b/packages/medusa/src/services/discount-condition.ts index ccf2ea546c..b6607f7e72 100644 --- a/packages/medusa/src/services/discount-condition.ts +++ b/packages/medusa/src/services/discount-condition.ts @@ -31,17 +31,13 @@ class DiscountConditionService extends TransactionBaseService { protected readonly discountConditionRepository_: typeof DiscountConditionRepository protected readonly eventBus_: EventBusService - protected manager_: EntityManager - protected transactionManager_: EntityManager | undefined - constructor({ - manager, discountConditionRepository, eventBusService, }: InjectedDependencies) { + // eslint-disable-next-line prefer-rest-params super(arguments[0]) - this.manager_ = manager this.discountConditionRepository_ = discountConditionRepository this.eventBus_ = eventBusService } @@ -57,8 +53,7 @@ class DiscountConditionService extends TransactionBaseService { ) } - const manager = this.manager_ - const conditionRepo = manager.withRepository( + const conditionRepo = this.activeManager_.withRepository( this.discountConditionRepository_ ) diff --git a/packages/medusa/src/services/discount.ts b/packages/medusa/src/services/discount.ts index 529784b9b2..58a311b20a 100644 --- a/packages/medusa/src/services/discount.ts +++ b/packages/medusa/src/services/discount.ts @@ -48,9 +48,6 @@ import { CalculationContextData } from "../types/totals" * @implements {BaseService} */ class DiscountService extends TransactionBaseService { - protected manager_: EntityManager - protected transactionManager_: EntityManager | undefined - protected readonly discountRepository_: typeof DiscountRepository protected readonly customerService_: CustomerService protected readonly discountRuleRepository_: typeof DiscountRuleRepository @@ -66,7 +63,6 @@ class DiscountService extends TransactionBaseService { protected readonly featureFlagRouter_: FlagRouter constructor({ - manager, discountRepository, discountRuleRepository, giftCardRepository, @@ -83,7 +79,6 @@ class DiscountService extends TransactionBaseService { // eslint-disable-next-line prefer-rest-params super(arguments[0]) - this.manager_ = manager this.discountRepository_ = discountRepository this.discountRuleRepository_ = discountRuleRepository this.giftCardRepository_ = giftCardRepository @@ -125,8 +120,9 @@ class DiscountService extends TransactionBaseService { selector: FilterableDiscountProps = {}, config: FindConfig = { relations: [], skip: 0, take: 10 } ): Promise { - const manager = this.manager_ - const discountRepo = manager.withRepository(this.discountRepository_) + const discountRepo = this.activeManager_.withRepository( + this.discountRepository_ + ) const query = buildQuery(selector as Selector, config) return await discountRepo.find(query) @@ -145,8 +141,9 @@ class DiscountService extends TransactionBaseService { order: { created_at: "DESC" }, } ): Promise<[Discount[], number]> { - const manager = this.manager_ - const discountRepo = manager.withRepository(this.discountRepository_) + const discountRepo = this.activeManager_.withRepository( + this.discountRepository_ + ) let q if ("q" in selector) { @@ -249,8 +246,9 @@ class DiscountService extends TransactionBaseService { ) } - const manager = this.manager_ - const discountRepo = manager.withRepository(this.discountRepository_) + const discountRepo = this.activeManager_.withRepository( + this.discountRepository_ + ) const query = buildQuery({ id: discountId }, config) const discount = await discountRepo.findOne(query) @@ -275,8 +273,9 @@ class DiscountService extends TransactionBaseService { discountCode: string, config: FindConfig = {} ): Promise { - const manager = this.manager_ - const discountRepo = manager.withRepository(this.discountRepository_) + const discountRepo = this.activeManager_.withRepository( + this.discountRepository_ + ) const normalizedCode = discountCode.toUpperCase().trim() @@ -303,8 +302,9 @@ class DiscountService extends TransactionBaseService { discountCodes: string[], config: FindConfig = {} ): Promise { - const manager = this.manager_ - const discountRepo = manager.withRepository(this.discountRepository_) + const discountRepo = this.activeManager_.withRepository( + this.discountRepository_ + ) const normalizedCodes = discountCodes.map((code) => code.toUpperCase().trim() diff --git a/packages/medusa/src/services/draft-order.ts b/packages/medusa/src/services/draft-order.ts index 530d554197..2374cb3e6a 100644 --- a/packages/medusa/src/services/draft-order.ts +++ b/packages/medusa/src/services/draft-order.ts @@ -46,9 +46,6 @@ class DraftOrderService extends TransactionBaseService { UPDATED: "draft_order.updated", } - protected manager_: EntityManager - protected transactionManager_: EntityManager | undefined - protected readonly draftOrderRepository_: typeof DraftOrderRepository protected readonly paymentRepository_: typeof PaymentRepository protected readonly orderRepository_: typeof OrderRepository @@ -60,7 +57,6 @@ class DraftOrderService extends TransactionBaseService { protected readonly customShippingOptionService_: CustomShippingOptionService constructor({ - manager, draftOrderRepository, paymentRepository, orderRepository, @@ -74,7 +70,6 @@ class DraftOrderService extends TransactionBaseService { // eslint-disable-next-line prefer-rest-params super(arguments[0]) - this.manager_ = manager this.draftOrderRepository_ = draftOrderRepository this.paymentRepository_ = paymentRepository this.orderRepository_ = orderRepository @@ -103,8 +98,9 @@ class DraftOrderService extends TransactionBaseService { ) } - const manager = this.manager_ - const draftOrderRepo = manager.withRepository(this.draftOrderRepository_) + const draftOrderRepo = this.activeManager_.withRepository( + this.draftOrderRepository_ + ) const query = buildQuery({ id: draftOrderId }, config) const draftOrder = await draftOrderRepo.findOne(query) @@ -128,8 +124,9 @@ class DraftOrderService extends TransactionBaseService { cartId: string, config: FindConfig = {} ): Promise { - const manager = this.manager_ - const draftOrderRepo = manager.withRepository(this.draftOrderRepository_) + const draftOrderRepo = this.activeManager_.withRepository( + this.draftOrderRepository_ + ) const query = buildQuery({ cart_id: cartId }, config) const draftOrder = await draftOrderRepo.findOne(query) @@ -180,8 +177,7 @@ class DraftOrderService extends TransactionBaseService { order: { created_at: "DESC" }, } ): Promise<[DraftOrder[], number]> { - const manager = this.manager_ - const draftOrderRepository = manager.withRepository( + const draftOrderRepository = this.activeManager_.withRepository( this.draftOrderRepository_ ) @@ -239,8 +235,9 @@ class DraftOrderService extends TransactionBaseService { order: { created_at: "DESC" }, } ): Promise { - const manager = this.manager_ - const draftOrderRepo = manager.withRepository(this.draftOrderRepository_) + const draftOrderRepo = this.activeManager_.withRepository( + this.draftOrderRepository_ + ) const query = buildQuery(selector, config) diff --git a/packages/medusa/src/services/fulfillment-provider.ts b/packages/medusa/src/services/fulfillment-provider.ts index 4d456f630d..afd7b20805 100644 --- a/packages/medusa/src/services/fulfillment-provider.ts +++ b/packages/medusa/src/services/fulfillment-provider.ts @@ -37,9 +37,6 @@ type CalculateOptionPriceInput = { * Helps retrive fulfillment providers */ class FulfillmentProviderService extends TransactionBaseService { - protected manager_: EntityManager - protected transactionManager_: EntityManager | undefined - protected readonly container_: FulfillmentProviderContainer // eslint-disable-next-line max-len protected readonly fulfillmentProviderRepository_: typeof FulfillmentProviderRepository @@ -47,10 +44,9 @@ class FulfillmentProviderService extends TransactionBaseService { constructor(container: FulfillmentProviderContainer) { super(container) - const { manager, fulfillmentProviderRepository } = container + const { fulfillmentProviderRepository } = container this.container_ = container - this.manager_ = manager this.fulfillmentProviderRepository_ = fulfillmentProviderRepository } @@ -69,7 +65,7 @@ class FulfillmentProviderService extends TransactionBaseService { } async list(): Promise { - const fpRepo = this.manager_.withRepository( + const fpRepo = this.activeManager_.withRepository( this.fulfillmentProviderRepository_ ) diff --git a/packages/medusa/src/services/fulfillment.ts b/packages/medusa/src/services/fulfillment.ts index 65b94930c4..964b59aa02 100644 --- a/packages/medusa/src/services/fulfillment.ts +++ b/packages/medusa/src/services/fulfillment.ts @@ -34,9 +34,6 @@ type InjectedDependencies = { * Handles Fulfillments */ class FulfillmentService extends TransactionBaseService { - protected manager_: EntityManager - protected transactionManager_: EntityManager | undefined - protected readonly totalsService_: TotalsService protected readonly lineItemService_: LineItemService protected readonly shippingProfileService_: ShippingProfileService @@ -48,7 +45,6 @@ class FulfillmentService extends TransactionBaseService { protected readonly productVariantInventoryService_: ProductVariantInventoryService constructor({ - manager, totalsService, fulfillmentRepository, trackingLinkRepository, @@ -61,8 +57,6 @@ class FulfillmentService extends TransactionBaseService { // eslint-disable-next-line prefer-rest-params super(arguments[0]) - this.manager_ = manager - this.lineItemRepository_ = lineItemRepository this.totalsService_ = totalsService this.fulfillmentRepository_ = fulfillmentRepository @@ -141,8 +135,9 @@ class FulfillmentService extends TransactionBaseService { item: LineItem | undefined, quantity: number ): LineItem | null { - const manager = this.transactionManager_ ?? this.manager_ - const lineItemRepo = manager.withRepository(this.lineItemRepository_) + const lineItemRepo = this.activeManager_.withRepository( + this.lineItemRepository_ + ) if (!item) { // This will in most cases be called by a webhook so to ensure that @@ -180,8 +175,7 @@ class FulfillmentService extends TransactionBaseService { ) } - const manager = this.manager_ - const fulfillmentRepository = manager.withRepository( + const fulfillmentRepository = this.activeManager_.withRepository( this.fulfillmentRepository_ ) diff --git a/packages/medusa/src/services/gift-card.ts b/packages/medusa/src/services/gift-card.ts index 17508eb747..25094ccc82 100644 --- a/packages/medusa/src/services/gift-card.ts +++ b/packages/medusa/src/services/gift-card.ts @@ -32,15 +32,11 @@ class GiftCardService extends TransactionBaseService { protected readonly regionService_: RegionService protected readonly eventBus_: EventBusService - protected manager_: EntityManager - protected transactionManager_: EntityManager | undefined - static Events = { CREATED: "gift_card.created", } constructor({ - manager, giftCardRepository, giftCardTransactionRepository, regionService, @@ -49,8 +45,6 @@ class GiftCardService extends TransactionBaseService { // eslint-disable-next-line prefer-rest-params super(arguments[0]) - this.manager_ = manager - this.giftCardRepository_ = giftCardRepository this.giftCardTransactionRepo_ = giftCardTransactionRepository this.regionService_ = regionService @@ -81,8 +75,9 @@ class GiftCardService extends TransactionBaseService { selector: QuerySelector = {}, config: FindConfig = { relations: [], skip: 0, take: 10 } ): Promise<[GiftCard[], number]> { - const manager = this.manager_ - const giftCardRepo = manager.withRepository(this.giftCardRepository_) + const giftCardRepo = this.activeManager_.withRepository( + this.giftCardRepository_ + ) let q: string | undefined if (isDefined(selector.q)) { @@ -111,8 +106,9 @@ class GiftCardService extends TransactionBaseService { async createTransaction( data: CreateGiftCardTransactionInput ): Promise { - const manager = this.manager_ - const gctRepo = manager.withRepository(this.giftCardTransactionRepo_) + const gctRepo = this.activeManager_.withRepository( + this.giftCardTransactionRepo_ + ) const created = gctRepo.create(data) const saved = await gctRepo.save(created) return saved.id @@ -187,8 +183,9 @@ class GiftCardService extends TransactionBaseService { selector: Selector, config: FindConfig = {} ): Promise { - const manager = this.manager_ - const giftCardRepo = manager.withRepository(this.giftCardRepository_) + const giftCardRepo = this.activeManager_.withRepository( + this.giftCardRepository_ + ) const query = buildQuery(selector, config) query.relationLoadStrategy = "query" @@ -296,8 +293,9 @@ class GiftCardService extends TransactionBaseService { * @return the result of the delete operation */ async delete(giftCardId: string): Promise { - const manager = this.manager_ - const giftCardRepo = manager.withRepository(this.giftCardRepository_) + const giftCardRepo = this.activeManager_.withRepository( + this.giftCardRepository_ + ) const giftCard = await giftCardRepo.findOne({ where: { id: giftCardId } }) diff --git a/packages/medusa/src/services/idempotency-key.ts b/packages/medusa/src/services/idempotency-key.ts index 1c2a369604..4906269908 100644 --- a/packages/medusa/src/services/idempotency-key.ts +++ b/packages/medusa/src/services/idempotency-key.ts @@ -17,16 +17,12 @@ type InjectedDependencies = { } class IdempotencyKeyService extends TransactionBaseService { - protected manager_: EntityManager - protected transactionManager_: EntityManager | undefined - protected readonly idempotencyKeyRepository_: typeof IdempotencyKeyRepository - constructor({ manager, idempotencyKeyRepository }: InjectedDependencies) { + constructor({ idempotencyKeyRepository }: InjectedDependencies) { // eslint-disable-next-line prefer-rest-params super(arguments[0]) - this.manager_ = manager this.idempotencyKeyRepository_ = idempotencyKeyRepository } @@ -90,7 +86,7 @@ class IdempotencyKeyService extends TransactionBaseService { ) } - const idempotencyKeyRepo = this.manager_.withRepository( + const idempotencyKeyRepo = this.activeManager_.withRepository( this.idempotencyKeyRepository_ ) diff --git a/packages/medusa/src/services/invite.ts b/packages/medusa/src/services/invite.ts index f963ea7e04..0e1d0a23df 100644 --- a/packages/medusa/src/services/invite.ts +++ b/packages/medusa/src/services/invite.ts @@ -27,9 +27,6 @@ class InviteService extends TransactionBaseService { CREATED: "invite.created", } - protected manager_: EntityManager - protected transactionManager_: EntityManager | undefined - protected readonly userService_: UserService protected readonly userRepo_: typeof UserRepository protected readonly inviteRepository_: typeof InviteRepository @@ -39,7 +36,6 @@ class InviteService extends TransactionBaseService { constructor( { - manager, userService, userRepository, inviteRepository, @@ -48,23 +44,13 @@ class InviteService extends TransactionBaseService { configModule: ConfigModule ) { // @ts-ignore + // eslint-disable-next-line prefer-rest-params super(...arguments) this.configModule_ = configModule - - /** @private @constant {EntityManager} */ - this.manager_ = manager - - /** @private @constant {UserService} */ this.userService_ = userService - - /** @private @constant {UserRepository} */ this.userRepo_ = userRepository - - /** @private @constant {InviteRepository} */ this.inviteRepository_ = inviteRepository - - /** @private @const {EventBus} */ this.eventBus_ = eventBusService } @@ -80,7 +66,7 @@ class InviteService extends TransactionBaseService { } async list(selector, config = {}): Promise { - const inviteRepo = this.manager_.withRepository(InviteRepository) + const inviteRepo = this.activeManager_.withRepository(InviteRepository) const query = buildQuery(selector, config) @@ -101,9 +87,9 @@ class InviteService extends TransactionBaseService { ): Promise { return await this.atomicPhase_(async (manager) => { const inviteRepository = - this.manager_.withRepository(InviteRepository) + this.activeManager_.withRepository(InviteRepository) - const userRepo = this.manager_.withRepository(UserRepository) + const userRepo = this.activeManager_.withRepository(UserRepository) const userEntity = await userRepo.findOne({ where: { email: user }, @@ -251,7 +237,7 @@ class InviteService extends TransactionBaseService { } async resend(id): Promise { - const inviteRepo = this.manager_.withRepository(InviteRepository) + const inviteRepo = this.activeManager_.withRepository(InviteRepository) const invite = await inviteRepo.findOne({ where: { id } }) @@ -274,7 +260,7 @@ class InviteService extends TransactionBaseService { await inviteRepo.save(invite) await this.eventBus_ - .withTransaction(this.manager_) + .withTransaction(this.activeManager_) .emit(InviteService.Events.CREATED, { id: invite.id, token: invite.token, diff --git a/packages/medusa/src/services/line-item-adjustment.ts b/packages/medusa/src/services/line-item-adjustment.ts index 08d9f4816c..6f370714dd 100644 --- a/packages/medusa/src/services/line-item-adjustment.ts +++ b/packages/medusa/src/services/line-item-adjustment.ts @@ -30,21 +30,16 @@ type GeneratedAdjustment = { * Provides layer to manipulate line item adjustments. */ class LineItemAdjustmentService extends TransactionBaseService { - protected readonly manager_: EntityManager - protected transactionManager_: EntityManager | undefined - private readonly lineItemAdjustmentRepo_: typeof LineItemAdjustmentRepository private readonly discountService: DiscountService constructor({ - manager, lineItemAdjustmentRepository, discountService, }: LineItemAdjustmentServiceProps) { // eslint-disable-next-line prefer-rest-params super(arguments[0]) - this.manager_ = manager this.lineItemAdjustmentRepo_ = lineItemAdjustmentRepository this.discountService = discountService } @@ -66,7 +61,7 @@ class LineItemAdjustmentService extends TransactionBaseService { ) } - const lineItemAdjustmentRepo = this.manager_.withRepository( + const lineItemAdjustmentRepo = this.activeManager_.withRepository( this.lineItemAdjustmentRepo_ ) @@ -142,7 +137,7 @@ class LineItemAdjustmentService extends TransactionBaseService { selector: FilterableLineItemAdjustmentProps = {}, config: FindConfig = { skip: 0, take: 20 } ): Promise { - const lineItemAdjustmentRepo = this.manager_.withRepository( + const lineItemAdjustmentRepo = this.activeManager_.withRepository( this.lineItemAdjustmentRepo_ ) diff --git a/packages/medusa/src/services/line-item.ts b/packages/medusa/src/services/line-item.ts index 9785a1a86f..e2c5fa6435 100644 --- a/packages/medusa/src/services/line-item.ts +++ b/packages/medusa/src/services/line-item.ts @@ -42,9 +42,6 @@ type InjectedDependencies = { } class LineItemService extends TransactionBaseService { - protected manager_: EntityManager - protected transactionManager_: EntityManager | undefined - protected readonly lineItemRepository_: typeof LineItemRepository protected readonly itemTaxLineRepo_: typeof LineItemTaxLineRepository protected readonly cartRepository_: typeof CartRepository @@ -57,7 +54,6 @@ class LineItemService extends TransactionBaseService { protected readonly taxProviderService_: TaxProviderService constructor({ - manager, lineItemRepository, lineItemTaxLineRepository, productVariantService, @@ -72,7 +68,6 @@ class LineItemService extends TransactionBaseService { // eslint-disable-next-line prefer-rest-params super(arguments[0]) - this.manager_ = manager this.lineItemRepository_ = lineItemRepository this.itemTaxLineRepo_ = lineItemTaxLineRepository this.productVariantService_ = productVariantService @@ -93,8 +88,9 @@ class LineItemService extends TransactionBaseService { order: { created_at: "DESC" }, } ): Promise { - const manager = this.manager_ - const lineItemRepo = manager.withRepository(this.lineItemRepository_) + const lineItemRepo = this.activeManager_.withRepository( + this.lineItemRepository_ + ) const query = buildQuery(selector, config) return await lineItemRepo.find(query) } @@ -106,8 +102,9 @@ class LineItemService extends TransactionBaseService { * @return the line item */ async retrieve(id: string, config = {}): Promise { - const manager = this.manager_ - const lineItemRepository = manager.withRepository(this.lineItemRepository_) + const lineItemRepository = this.activeManager_.withRepository( + this.lineItemRepository_ + ) const query = buildQuery({ id }, config) @@ -311,8 +308,6 @@ class LineItemService extends TransactionBaseService { variantPricing: ProductVariantPricing } ): Promise { - const transactionManager = this.transactionManager_ ?? this.manager_ - let unit_price = Number(context.unit_price) < 0 ? 0 : context.unit_price let unitPriceIncludesTax = false let shouldMerge = false @@ -348,7 +343,7 @@ class LineItemService extends TransactionBaseService { rawLineItem.order_edit_id = context.order_edit_id || null - const lineItemRepo = transactionManager.withRepository( + const lineItemRepo = this.activeManager_.withRepository( this.lineItemRepository_ ) @@ -477,7 +472,9 @@ class LineItemService extends TransactionBaseService { * @return a new line item tax line */ public createTaxLine(args: DeepPartial): LineItemTaxLine { - const itemTaxLineRepo = this.manager_.withRepository(this.itemTaxLineRepo_) + const itemTaxLineRepo = this.activeManager_.withRepository( + this.itemTaxLineRepo_ + ) return itemTaxLineRepo.create(args) } diff --git a/packages/medusa/src/services/new-totals.ts b/packages/medusa/src/services/new-totals.ts index ccc7b3d782..d509b29058 100644 --- a/packages/medusa/src/services/new-totals.ts +++ b/packages/medusa/src/services/new-totals.ts @@ -58,15 +58,11 @@ type InjectedDependencies = { } export default class NewTotalsService extends TransactionBaseService { - protected readonly manager_: EntityManager - protected readonly transactionManager_: EntityManager | undefined - protected readonly taxProviderService_: TaxProviderService protected readonly featureFlagRouter_: FlagRouter protected readonly taxCalculationStrategy_: ITaxCalculationStrategy constructor({ - manager, taxProviderService, featureFlagRouter, taxCalculationStrategy, @@ -74,7 +70,6 @@ export default class NewTotalsService extends TransactionBaseService { // eslint-disable-next-line prefer-rest-params super(arguments[0]) - this.manager_ = manager this.taxProviderService_ = taxProviderService this.featureFlagRouter_ = featureFlagRouter this.taxCalculationStrategy_ = taxCalculationStrategy @@ -101,7 +96,6 @@ export default class NewTotalsService extends TransactionBaseService { ): Promise<{ [lineItemId: string]: LineItemTotals }> { items = Array.isArray(items) ? items : [items] - const manager = this.transactionManager_ ?? this.manager_ let lineItemsTaxLinesMap: { [lineItemId: string]: LineItemTaxLine[] } = {} if (!taxRate && includeTax) { @@ -113,7 +107,7 @@ export default class NewTotalsService extends TransactionBaseService { }) } else { const { lineItemsTaxLines } = await this.taxProviderService_ - .withTransaction(manager) + .withTransaction(this.activeManager_) .getTaxLinesMap(items, calculationContext) lineItemsTaxLinesMap = lineItemsTaxLines } @@ -585,7 +579,6 @@ export default class NewTotalsService extends TransactionBaseService { ? shippingMethods : [shippingMethods] - const manager = this.transactionManager_ ?? this.manager_ let shippingMethodsTaxLinesMap: { [shippingMethodId: string]: ShippingMethodTaxLine[] } = {} @@ -605,7 +598,7 @@ export default class NewTotalsService extends TransactionBaseService { shipping_methods: shippingMethods, } const { shippingMethodsTaxLines } = await this.taxProviderService_ - .withTransaction(manager) + .withTransaction(this.activeManager_) .getTaxLinesMap([], calculationContextWithGivenMethod) shippingMethodsTaxLinesMap = shippingMethodsTaxLines } diff --git a/packages/medusa/src/services/note.ts b/packages/medusa/src/services/note.ts index 867b5fdf3e..65f6412970 100644 --- a/packages/medusa/src/services/note.ts +++ b/packages/medusa/src/services/note.ts @@ -21,19 +21,13 @@ class NoteService extends TransactionBaseService { DELETED: "note.deleted", } - protected manager_: EntityManager - protected transactionManager_: EntityManager | undefined protected readonly noteRepository_: typeof NoteRepository protected readonly eventBus_: EventBusService - constructor({ - manager, - noteRepository, - eventBusService, - }: InjectedDependencies) { + constructor({ noteRepository, eventBusService }: InjectedDependencies) { + // eslint-disable-next-line prefer-rest-params super(arguments[0]) - this.manager_ = manager this.noteRepository_ = noteRepository this.eventBus_ = eventBusService } @@ -55,7 +49,7 @@ class NoteService extends TransactionBaseService { ) } - const noteRepo = this.manager_.withRepository(this.noteRepository_) + const noteRepo = this.activeManager_.withRepository(this.noteRepository_) const query = buildQuery({ id: noteId }, config) @@ -87,7 +81,7 @@ class NoteService extends TransactionBaseService { relations: [], } ): Promise { - const noteRepo = this.manager_.withRepository(this.noteRepository_) + const noteRepo = this.activeManager_.withRepository(this.noteRepository_) const query = buildQuery(selector, config) diff --git a/packages/medusa/src/services/notification.ts b/packages/medusa/src/services/notification.ts index c22da2e94c..0587e1952d 100644 --- a/packages/medusa/src/services/notification.ts +++ b/packages/medusa/src/services/notification.ts @@ -20,9 +20,6 @@ type InjectedDependencies = { type NotificationProviderKey = `noti_${string}` class NotificationService extends TransactionBaseService { - protected manager_: EntityManager - protected transactionManager_: EntityManager | undefined - protected subscribers_ = {} protected attachmentGenerator_: unknown = null protected readonly container_: InjectedDependencies & { @@ -36,20 +33,12 @@ class NotificationService extends TransactionBaseService { constructor(container: InjectedDependencies) { super(container) - const { - manager, - notificationProviderRepository, - notificationRepository, - logger, - } = container + const { notificationProviderRepository, notificationRepository, logger } = + container this.container_ = container - /** @private @const {EntityManager} */ - this.manager_ = manager this.logger_ = logger - - /** @private @const {NotificationRepository} */ this.notificationRepository_ = notificationRepository this.notificationProviderRepository_ = notificationProviderRepository } @@ -68,8 +57,10 @@ class NotificationService extends TransactionBaseService { * @param providerIds - a list of provider ids */ async registerInstalledProviders(providerIds: string[]): Promise { - const { manager, notificationProviderRepository } = this.container_ - const model = manager.withRepository(notificationProviderRepository) + const { notificationProviderRepository } = this.container_ + const model = this.activeManager_.withRepository( + notificationProviderRepository + ) await model.update({}, { is_installed: false }) for (const id of providerIds) { const n = model.create({ id, is_installed: true }) @@ -91,7 +82,7 @@ class NotificationService extends TransactionBaseService { order: { created_at: "DESC" }, } ): Promise { - const notiRepo = this.manager_.withRepository( + const notiRepo = this.activeManager_.withRepository( this.notificationRepository_ ) const query = buildQuery(selector, config) @@ -108,7 +99,7 @@ class NotificationService extends TransactionBaseService { id: string, config: FindConfig = {} ): Promise { - const notiRepository = this.manager_.withRepository( + const notiRepository = this.activeManager_.withRepository( this.notificationRepository_ ) diff --git a/packages/medusa/src/services/oauth.ts b/packages/medusa/src/services/oauth.ts index ff62ff7e81..2de2ee2d71 100644 --- a/packages/medusa/src/services/oauth.ts +++ b/packages/medusa/src/services/oauth.ts @@ -16,30 +16,25 @@ type InjectedDependencies = MedusaContainer & { } class Oauth extends TransactionBaseService { - protected manager_: EntityManager - protected transactionManager_: EntityManager | undefined static Events = { TOKEN_GENERATED: "oauth.token_generated", TOKEN_REFRESHED: "oauth.token_refreshed", } - protected manager: EntityManager protected container_: InjectedDependencies protected oauthRepository_: typeof OauthRepository protected eventBus_: EventBusService constructor(cradle: InjectedDependencies) { super(cradle) - const manager = cradle.manager - this.manager = manager this.container_ = cradle this.oauthRepository_ = cradle.oauthRepository this.eventBus_ = cradle.eventBusService } async retrieveByName(appName: string): Promise { - const repo = this.manager.withRepository(this.oauthRepository_) + const repo = this.activeManager_.withRepository(this.oauthRepository_) const oauth = await repo.findOne({ where: { application_name: appName, @@ -64,7 +59,7 @@ class Oauth extends TransactionBaseService { ) } - const repo = this.manager.withRepository(this.oauthRepository_) + const repo = this.activeManager_.withRepository(this.oauthRepository_) const oauth = await repo.findOne({ where: { id: oauthId, @@ -82,7 +77,7 @@ class Oauth extends TransactionBaseService { } async list(selector: Selector): Promise { - const repo = this.manager.withRepository(this.oauthRepository_) + const repo = this.activeManager_.withRepository(this.oauthRepository_) const query = buildQuery(selector, {}) @@ -90,7 +85,7 @@ class Oauth extends TransactionBaseService { } async create(data: CreateOauthInput): Promise { - const repo = this.manager.withRepository(this.oauthRepository_) + const repo = this.activeManager_.withRepository(this.oauthRepository_) const application = repo.create({ display_name: data.display_name, @@ -103,7 +98,7 @@ class Oauth extends TransactionBaseService { } async update(id: string, update: UpdateOauthInput): Promise { - const repo = this.manager.withRepository(this.oauthRepository_) + const repo = this.activeManager_.withRepository(this.oauthRepository_) const oauth = await this.retrieve(id) if ("data" in update) { diff --git a/packages/medusa/src/services/order-edit-item-change.ts b/packages/medusa/src/services/order-edit-item-change.ts index 847229e85f..0e1542fa41 100644 --- a/packages/medusa/src/services/order-edit-item-change.ts +++ b/packages/medusa/src/services/order-edit-item-change.ts @@ -1,6 +1,6 @@ import { TransactionBaseService } from "../interfaces" import { OrderItemChangeRepository } from "../repositories/order-item-change" -import { DeepPartial, EntityManager, In } from "typeorm" +import { EntityManager, In } from "typeorm" import { EventBusService, LineItemService } from "./index" import { FindConfig, Selector } from "../types/common" import { OrderItemChange } from "../models" @@ -23,16 +23,13 @@ export default class OrderEditItemChangeService extends TransactionBaseService { DELETED: "order-edit-item-change.DELETED", } - protected manager_: EntityManager - protected transactionManager_: EntityManager | undefined - + // eslint-disable-next-line max-len protected readonly orderItemChangeRepository_: typeof OrderItemChangeRepository protected readonly eventBus_: EventBusService protected readonly lineItemService_: LineItemService protected readonly taxProviderService_: TaxProviderService constructor({ - manager, orderItemChangeRepository, eventBusService, lineItemService, @@ -41,7 +38,6 @@ export default class OrderEditItemChangeService extends TransactionBaseService { // eslint-disable-next-line prefer-rest-params super(arguments[0]) - this.manager_ = manager this.orderItemChangeRepository_ = orderItemChangeRepository this.eventBus_ = eventBusService this.lineItemService_ = lineItemService @@ -52,8 +48,7 @@ export default class OrderEditItemChangeService extends TransactionBaseService { id: string, config: FindConfig = {} ): Promise { - const manager = this.transactionManager_ ?? this.manager_ - const orderItemChangeRepo = manager.withRepository( + const orderItemChangeRepo = this.activeManager_.withRepository( this.orderItemChangeRepository_ ) @@ -74,8 +69,7 @@ export default class OrderEditItemChangeService extends TransactionBaseService { selector: Selector, config: FindConfig = {} ): Promise { - const manager = this.transactionManager_ ?? this.manager_ - const orderItemChangeRepo = manager.withRepository( + const orderItemChangeRepo = this.activeManager_.withRepository( this.orderItemChangeRepository_ ) diff --git a/packages/medusa/src/services/order-edit.ts b/packages/medusa/src/services/order-edit.ts index f6812f5a2b..cabf262432 100644 --- a/packages/medusa/src/services/order-edit.ts +++ b/packages/medusa/src/services/order-edit.ts @@ -57,9 +57,6 @@ export default class OrderEditService extends TransactionBaseService { CONFIRMED: "order-edit.confirmed", } - protected readonly manager_: EntityManager - protected transactionManager_: EntityManager | undefined - protected readonly orderEditRepository_: typeof OrderEditRepository protected readonly orderService_: OrderService @@ -72,7 +69,6 @@ export default class OrderEditService extends TransactionBaseService { protected readonly orderEditItemChangeService_: OrderEditItemChangeService constructor({ - manager, orderEditRepository, orderService, lineItemService, @@ -86,7 +82,6 @@ export default class OrderEditService extends TransactionBaseService { // eslint-disable-next-line prefer-rest-params super(arguments[0]) - this.manager_ = manager this.orderEditRepository_ = orderEditRepository this.orderService_ = orderService this.lineItemService_ = lineItemService @@ -109,8 +104,7 @@ export default class OrderEditService extends TransactionBaseService { ) } - const manager = this.transactionManager_ ?? this.manager_ - const orderEditRepository = manager.withRepository( + const orderEditRepository = this.activeManager_.withRepository( this.orderEditRepository_ ) @@ -131,8 +125,7 @@ export default class OrderEditService extends TransactionBaseService { selector: Selector & { q?: string }, config?: FindConfig ): Promise<[OrderEdit[], number]> { - const manager = this.transactionManager_ ?? this.manager_ - const orderEditRepository = manager.withRepository( + const orderEditRepository = this.activeManager_.withRepository( this.orderEditRepository_ ) @@ -441,10 +434,8 @@ export default class OrderEditService extends TransactionBaseService { orderEditId: string, config = { preserveCustomAdjustments: false } ) { - const manager = this.transactionManager_ ?? this.manager_ - const lineItemAdjustmentServiceTx = - this.lineItemAdjustmentService_.withTransaction(manager) + this.lineItemAdjustmentService_.withTransaction(this.activeManager_) const orderEdit = await this.retrieve(orderEditId, { relations: [ @@ -491,18 +482,19 @@ export default class OrderEditService extends TransactionBaseService { } async decorateTotals(orderEdit: OrderEdit): Promise { - const manager = this.transactionManager_ ?? this.manager_ const { order_id, items } = await this.retrieve(orderEdit.id, { select: ["id", "order_id", "items"], relations: [ "items", "items.tax_lines", "items.adjustments", - "items.variant" + "items.variant", ], }) - const orderServiceTx = this.orderService_.withTransaction(manager) + const orderServiceTx = this.orderService_.withTransaction( + this.activeManager_ + ) const order = await orderServiceTx.retrieve(order_id, { relations: [ @@ -576,7 +568,7 @@ export default class OrderEditService extends TransactionBaseService { let lineItem = await lineItemServiceTx.create(lineItemData) lineItem = await lineItemServiceTx.retrieve(lineItem.id, { - relations: ['variant', 'variant.product'] + relations: ["variant", "variant.product"], }) await this.refreshAdjustments(orderEditId) @@ -780,8 +772,7 @@ export default class OrderEditService extends TransactionBaseService { orderId: string, config: FindConfig = {} ): Promise { - const manager = this.transactionManager_ ?? this.manager_ - const orderEditRepository = manager.withRepository( + const orderEditRepository = this.activeManager_.withRepository( this.orderEditRepository_ ) @@ -798,12 +789,14 @@ export default class OrderEditService extends TransactionBaseService { } protected async deleteClonedItems(orderEditId: string): Promise { - const manager = this.transactionManager_ ?? this.manager_ - const lineItemServiceTx = this.lineItemService_.withTransaction(manager) + const lineItemServiceTx = this.lineItemService_.withTransaction( + this.activeManager_ + ) const lineItemAdjustmentServiceTx = - this.lineItemAdjustmentService_.withTransaction(manager) - const taxProviderServiceTs = - this.taxProviderService_.withTransaction(manager) + this.lineItemAdjustmentService_.withTransaction(this.activeManager_) + const taxProviderServiceTs = this.taxProviderService_.withTransaction( + this.activeManager_ + ) const clonedLineItems = await lineItemServiceTx.list( { @@ -821,7 +814,7 @@ export default class OrderEditService extends TransactionBaseService { relations: [ "changes", "changes.original_line_item", - "changes.original_line_item.variant" + "changes.original_line_item.variant", ], }) diff --git a/packages/medusa/src/services/order.ts b/packages/medusa/src/services/order.ts index 9417ad89e2..7b3afff055 100644 --- a/packages/medusa/src/services/order.ts +++ b/packages/medusa/src/services/order.ts @@ -115,9 +115,6 @@ class OrderService extends TransactionBaseService { COMPLETED: "order.completed", } - protected manager_: EntityManager - protected transactionManager_: EntityManager - protected readonly orderRepository_: typeof OrderRepository protected readonly customerService_: CustomerService protected readonly paymentProviderService_: PaymentProviderService @@ -141,7 +138,6 @@ class OrderService extends TransactionBaseService { protected readonly productVariantInventoryService_: ProductVariantInventoryService constructor({ - manager, orderRepository, customerService, paymentProviderService, @@ -166,7 +162,6 @@ class OrderService extends TransactionBaseService { // eslint-disable-next-line prefer-rest-params super(arguments[0]) - this.manager_ = manager this.orderRepository_ = orderRepository this.customerService_ = customerService this.paymentProviderService_ = paymentProviderService @@ -219,7 +214,7 @@ class OrderService extends TransactionBaseService { order: { created_at: "DESC" }, } ): Promise<[Order[], number]> { - const orderRepo = this.manager_.withRepository(this.orderRepository_) + const orderRepo = this.activeManager_.withRepository(this.orderRepository_) let q if (selector.q) { @@ -412,8 +407,7 @@ class OrderService extends TransactionBaseService { return await this.retrieveLegacy(orderId, config) } - const manager = this.manager_ - const orderRepo = manager.withRepository(this.orderRepository_) + const orderRepo = this.activeManager_.withRepository(this.orderRepository_) const query = buildQuery({ id: orderId }, config) @@ -440,7 +434,7 @@ class OrderService extends TransactionBaseService { orderIdOrSelector: string | Selector, config: FindConfig = {} ): Promise { - const orderRepo = this.manager_.withRepository(this.orderRepository_) + const orderRepo = this.activeManager_.withRepository(this.orderRepository_) const { select, relations, totalsToSelect } = this.transformQueryForTotals(config) @@ -496,7 +490,7 @@ class OrderService extends TransactionBaseService { cartId: string, config: FindConfig = {} ): Promise { - const orderRepo = this.manager_.withRepository(this.orderRepository_) + const orderRepo = this.activeManager_.withRepository(this.orderRepository_) const { select, relations, totalsToSelect } = this.transformQueryForTotals(config) @@ -537,7 +531,7 @@ class OrderService extends TransactionBaseService { externalId: string, config: FindConfig = {} ): Promise { - const orderRepo = this.manager_.withRepository(this.orderRepository_) + const orderRepo = this.activeManager_.withRepository(this.orderRepository_) const { select, relations, totalsToSelect } = this.transformQueryForTotals(config) @@ -941,11 +935,11 @@ class OrderService extends TransactionBaseService { order: Order, address: Address ): Promise { - const addrRepo = this.manager_.withRepository(this.addressRepository_) + const addrRepo = this.activeManager_.withRepository(this.addressRepository_) address.country_code = address.country_code?.toLowerCase() ?? null const region = await this.regionService_ - .withTransaction(this.manager_) + .withTransaction(this.activeManager_) .retrieve(order.region_id, { relations: ["countries"], }) @@ -980,11 +974,11 @@ class OrderService extends TransactionBaseService { order: Order, address: Address ): Promise { - const addrRepo = this.manager_.withRepository(this.addressRepository_) + const addrRepo = this.activeManager_.withRepository(this.addressRepository_) address.country_code = address.country_code?.toLowerCase() ?? null const region = await this.regionService_ - .withTransaction(this.manager_) + .withTransaction(this.activeManager_) .retrieve(order.region_id, { relations: ["countries"], }) @@ -1693,7 +1687,7 @@ class OrderService extends TransactionBaseService { } case "total": { order.total = await this.totalsService_ - .withTransaction(this.manager_) + .withTransaction(this.activeManager_) .getTotal(order) break } @@ -1778,8 +1772,9 @@ class OrderService extends TransactionBaseService { return await this.decorateTotalsLegacy(order, totalsFieldsOrConfig) } - const manager = this.transactionManager_ ?? this.manager_ - const newTotalsServiceTx = this.newTotalsService_.withTransaction(manager) + const newTotalsServiceTx = this.newTotalsService_.withTransaction( + this.activeManager_ + ) const calculationContext = await this.totalsService_.getCalculationContext( order diff --git a/packages/medusa/src/services/payment-collection.ts b/packages/medusa/src/services/payment-collection.ts index f3bfc07d08..b08e6919e5 100644 --- a/packages/medusa/src/services/payment-collection.ts +++ b/packages/medusa/src/services/payment-collection.ts @@ -40,8 +40,6 @@ export default class PaymentCollectionService extends TransactionBaseService { PAYMENT_AUTHORIZED: "payment-collection.payment_authorized", } - protected readonly manager_: EntityManager - protected transactionManager_: EntityManager | undefined protected readonly eventBusService_: EventBusService protected readonly paymentProviderService_: PaymentProviderService protected readonly customerService_: CustomerService @@ -49,7 +47,6 @@ export default class PaymentCollectionService extends TransactionBaseService { protected readonly paymentCollectionRepository_: typeof PaymentCollectionRepository constructor({ - manager, paymentCollectionRepository, paymentProviderService, customerService, @@ -58,7 +55,6 @@ export default class PaymentCollectionService extends TransactionBaseService { // eslint-disable-next-line prefer-rest-params super(arguments[0]) - this.manager_ = manager this.paymentCollectionRepository_ = paymentCollectionRepository this.paymentProviderService_ = paymentProviderService this.eventBusService_ = eventBusService @@ -82,8 +78,7 @@ export default class PaymentCollectionService extends TransactionBaseService { ) } - const manager = this.transactionManager_ ?? this.manager_ - const paymentCollectionRepository = manager.withRepository( + const paymentCollectionRepository = this.activeManager_.withRepository( this.paymentCollectionRepository_ ) diff --git a/packages/medusa/src/services/payment-provider.ts b/packages/medusa/src/services/payment-provider.ts index 53ec886f60..f7c71f69b3 100644 --- a/packages/medusa/src/services/payment-provider.ts +++ b/packages/medusa/src/services/payment-provider.ts @@ -48,8 +48,6 @@ type InjectedDependencies = { * Helps retrieve payment providers */ export default class PaymentProviderService extends TransactionBaseService { - protected manager_: EntityManager - protected transactionManager_: EntityManager | undefined protected readonly container_: InjectedDependencies protected readonly paymentSessionRepository_: typeof PaymentSessionRepository // eslint-disable-next-line max-len @@ -65,7 +63,6 @@ export default class PaymentProviderService extends TransactionBaseService { super(container) this.container_ = container - this.manager_ = container.manager this.paymentSessionRepository_ = container.paymentSessionRepository this.paymentProviderRepository_ = container.paymentProviderRepository this.paymentRepository_ = container.paymentRepository @@ -95,7 +92,7 @@ export default class PaymentProviderService extends TransactionBaseService { } async list(): Promise { - const ppRepo = this.manager_.withRepository( + const ppRepo = this.activeManager_.withRepository( this.paymentProviderRepository_ ) return await ppRepo.find() @@ -105,7 +102,7 @@ export default class PaymentProviderService extends TransactionBaseService { id: string, relations: string[] = [] ): Promise { - const paymentRepo = this.manager_.withRepository( + const paymentRepo = this.activeManager_.withRepository( this.paymentRepository_ ) const query = { @@ -137,7 +134,7 @@ export default class PaymentProviderService extends TransactionBaseService { order: { created_at: "DESC" }, } ): Promise { - const payRepo = this.manager_.withRepository(this.paymentRepository_) + const payRepo = this.activeManager_.withRepository(this.paymentRepository_) const query = buildQuery(selector, config) return await payRepo.find(query) } @@ -146,7 +143,7 @@ export default class PaymentProviderService extends TransactionBaseService { id: string, relations: string[] = [] ): Promise { - const sessionRepo = this.manager_.withRepository( + const sessionRepo = this.activeManager_.withRepository( this.paymentSessionRepository_ ) @@ -467,7 +464,9 @@ export default class PaymentProviderService extends TransactionBaseService { async getStatus(payment: Payment): Promise { const provider = this.retrieveProvider(payment.provider_id) - return await provider.withTransaction(this.manager_).getStatus(payment.data) + return await provider + .withTransaction(this.activeManager_) + .getStatus(payment.data) } async capturePayment( @@ -619,7 +618,7 @@ export default class PaymentProviderService extends TransactionBaseService { id: string, config: FindConfig = {} ): Promise { - const refRepo = this.manager_.withRepository(this.refundRepository_) + const refRepo = this.activeManager_.withRepository(this.refundRepository_) const query = buildQuery({ id }, config) const refund = await refRepo.findOne(query) @@ -690,9 +689,7 @@ export default class PaymentProviderService extends TransactionBaseService { status?: PaymentSessionStatus } ): Promise { - const manager = this.transactionManager_ ?? this.manager_ - - const sessionRepo = manager.withRepository( + const sessionRepo = this.activeManager_.withRepository( this.paymentSessionRepository_ ) @@ -738,11 +735,9 @@ export default class PaymentProviderService extends TransactionBaseService { return } - const manager = this.transactionManager_ ?? this.manager_ - if (update_requests.customer_metadata && data.customer?.id) { await this.customerService_ - .withTransaction(manager) + .withTransaction(this.activeManager_) .update(data.customer.id, { metadata: update_requests.customer_metadata, }) diff --git a/packages/medusa/src/services/payment.ts b/packages/medusa/src/services/payment.ts index 08c495aa72..2889853bf0 100644 --- a/packages/medusa/src/services/payment.ts +++ b/packages/medusa/src/services/payment.ts @@ -23,8 +23,6 @@ export type PaymentDataInput = { } export default class PaymentService extends TransactionBaseService { - protected readonly manager_: EntityManager - protected transactionManager_: EntityManager | undefined protected readonly eventBusService_: EventBusService protected readonly paymentProviderService_: PaymentProviderService protected readonly paymentRepository_: typeof PaymentRepository @@ -38,7 +36,6 @@ export default class PaymentService extends TransactionBaseService { } constructor({ - manager, paymentRepository, paymentProviderService, eventBusService, @@ -46,7 +43,6 @@ export default class PaymentService extends TransactionBaseService { // eslint-disable-next-line prefer-rest-params super(arguments[0]) - this.manager_ = manager this.paymentRepository_ = paymentRepository this.paymentProviderService_ = paymentProviderService this.eventBusService_ = eventBusService @@ -69,8 +65,7 @@ export default class PaymentService extends TransactionBaseService { ) } - const manager = this.transactionManager_ ?? this.manager_ - const paymentRepository = manager.withRepository( + const paymentRepository = this.activeManager_.withRepository( this.paymentRepository_ ) @@ -97,9 +92,7 @@ export default class PaymentService extends TransactionBaseService { return await this.atomicPhase_(async (manager: EntityManager) => { const { data, currency_code, amount, provider_id } = paymentInput - const paymentRepository = manager.withRepository( - this.paymentRepository_ - ) + const paymentRepository = manager.withRepository(this.paymentRepository_) const created = paymentRepository.create({ provider_id, @@ -131,9 +124,7 @@ export default class PaymentService extends TransactionBaseService { return await this.atomicPhase_(async (manager: EntityManager) => { const payment = await this.retrieve(paymentId) - const paymentRepository = manager.withRepository( - this.paymentRepository_ - ) + const paymentRepository = manager.withRepository(this.paymentRepository_) if (data?.order_id) { payment.order_id = data.order_id diff --git a/packages/medusa/src/services/price-list.ts b/packages/medusa/src/services/price-list.ts index a3a1554c92..4e79ab4121 100644 --- a/packages/medusa/src/services/price-list.ts +++ b/packages/medusa/src/services/price-list.ts @@ -47,9 +47,6 @@ type PriceListConstructorProps = { * Provides layer to manipulate product tags. */ class PriceListService extends TransactionBaseService { - protected manager_: EntityManager - protected transactionManager_: EntityManager | undefined - protected readonly customerGroupService_: CustomerGroupService protected readonly regionService_: RegionService protected readonly productService_: ProductService @@ -60,7 +57,6 @@ class PriceListService extends TransactionBaseService { protected readonly featureFlagRouter_: FlagRouter constructor({ - manager, customerGroupService, regionService, productService, @@ -73,7 +69,6 @@ class PriceListService extends TransactionBaseService { // eslint-disable-next-line prefer-rest-params super(arguments[0]) - this.manager_ = manager this.customerGroupService_ = customerGroupService this.productService_ = productService this.variantService_ = productVariantService @@ -101,7 +96,9 @@ class PriceListService extends TransactionBaseService { ) } - const priceListRepo = this.manager_.withRepository(this.priceListRepo_) + const priceListRepo = this.activeManager_.withRepository( + this.priceListRepo_ + ) const query = buildQuery({ id: priceListId }, config) const priceList = await priceListRepo.findOne(query) @@ -298,8 +295,9 @@ class PriceListService extends TransactionBaseService { selector: FilterablePriceListProps = {}, config: FindConfig = { skip: 0, take: 20 } ): Promise { - const manager = this.manager_ - const priceListRepo = manager.withRepository(this.priceListRepo_) + const priceListRepo = this.activeManager_.withRepository( + this.priceListRepo_ + ) const { q, ...priceListSelector } = selector const query = buildQuery( @@ -330,8 +328,9 @@ class PriceListService extends TransactionBaseService { take: 20, } ): Promise<[PriceList[], number]> { - const manager = this.manager_ - const priceListRepo = manager.withRepository(this.priceListRepo_) + const priceListRepo = this.activeManager_.withRepository( + this.priceListRepo_ + ) const { q, ...priceListSelector } = selector const query = buildQuery(priceListSelector, config) query.where = query.where as FindOptionsWhere @@ -389,7 +388,9 @@ class PriceListService extends TransactionBaseService { priceListId: string, customerGroups: { id: string }[] ): Promise { - const priceListRepo = this.manager_.withRepository(this.priceListRepo_) + const priceListRepo = this.activeManager_.withRepository( + this.priceListRepo_ + ) const priceList = await this.retrieve(priceListId, { select: ["id"] }) const groups: CustomerGroup[] = [] @@ -564,7 +565,9 @@ class PriceListService extends TransactionBaseService { >(prices: T[]): Promise { const prices_: typeof prices = [] - const regionServiceTx = this.regionService_.withTransaction(this.manager_) + const regionServiceTx = this.regionService_.withTransaction( + this.activeManager_ + ) for (const price of prices) { const p = { ...price } diff --git a/packages/medusa/src/services/pricing.ts b/packages/medusa/src/services/pricing.ts index 93b155b776..3d4944dead 100644 --- a/packages/medusa/src/services/pricing.ts +++ b/packages/medusa/src/services/pricing.ts @@ -33,8 +33,6 @@ type InjectedDependencies = { * Allows retrieval of prices. */ class PricingService extends TransactionBaseService { - protected manager_: EntityManager - protected transactionManager_: EntityManager | undefined protected readonly regionService: RegionService protected readonly taxProviderService: TaxProviderService protected readonly priceSelectionStrategy: IPriceSelectionStrategy @@ -42,7 +40,6 @@ class PricingService extends TransactionBaseService { protected readonly featureFlagRouter: FlagRouter constructor({ - manager, productVariantService, taxProviderService, regionService, @@ -52,7 +49,6 @@ class PricingService extends TransactionBaseService { // eslint-disable-next-line prefer-rest-params super(arguments[0]) - this.manager_ = manager this.regionService = regionService this.taxProviderService = taxProviderService this.priceSelectionStrategy = priceSelectionStrategy @@ -76,7 +72,7 @@ class PricingService extends TransactionBaseService { let region: Region if (context.region_id) { region = await this.regionService - .withTransaction(this.manager_) + .withTransaction(this.activeManager_) .retrieve(context.region_id, { select: ["id", "currency_code", "automatic_taxes", "tax_rate"], }) @@ -169,12 +165,10 @@ class PricingService extends TransactionBaseService { taxRates: TaxServiceRate[], context: PricingContext ): Promise { - const transactionManager = this.transactionManager_ ?? this.manager_ - context.price_selection.tax_rates = taxRates const pricing = await this.priceSelectionStrategy - .withTransaction(transactionManager) + .withTransaction(this.activeManager_) .calculateVariantPrice(variantId, context.price_selection) const pricingResult: ProductVariantPricing = { @@ -267,11 +261,11 @@ class PricingService extends TransactionBaseService { pricingContext.price_selection.region_id ) { const { product_id } = await this.productVariantService - .withTransaction(this.manager_) + .withTransaction(this.activeManager_) .retrieve(variantId, { select: ["id", "product_id"] }) productRates = await this.taxProviderService - .withTransaction(this.manager_) + .withTransaction(this.activeManager_) .getRegionRatesForProduct(product_id, { id: pricingContext.price_selection.region_id, tax_rate: pricingContext.tax_rate, @@ -312,7 +306,7 @@ class PricingService extends TransactionBaseService { ) as string[] const variants = await this.productVariantService - .withTransaction(this.manager_) + .withTransaction(this.activeManager_) .list({ id: ids }, { select: ["id", "product_id"] }) const variantsMap = new Map( @@ -329,7 +323,7 @@ class PricingService extends TransactionBaseService { if (pricingContext.price_selection.region_id) { productRates = await this.taxProviderService - .withTransaction(this.manager_) + .withTransaction(this.activeManager_) .getRegionRatesForProduct(product_id, { id: pricingContext.price_selection.region_id, tax_rate: pricingContext.tax_rate, @@ -353,11 +347,10 @@ class PricingService extends TransactionBaseService { variants: ProductVariant[], context: PricingContext ): Promise> { - const transactionManager = this.transactionManager_ ?? this.manager_ let taxRates: TaxServiceRate[] = [] if (context.automatic_taxes && context.price_selection.region_id) { taxRates = await this.taxProviderService - .withTransaction(transactionManager) + .withTransaction(this.activeManager_) .getRegionRatesForProduct(productId, { id: context.price_selection.region_id, tax_rate: context.tax_rate, @@ -509,7 +502,7 @@ class PricingService extends TransactionBaseService { pricingContext.price_selection.region_id ) { shippingOptionRates = await this.taxProviderService - .withTransaction(this.manager_) + .withTransaction(this.activeManager_) .getRegionRatesForShipping(shippingOption.id, { id: pricingContext.price_selection.region_id, tax_rate: pricingContext.tax_rate, diff --git a/packages/medusa/src/services/product-category.ts b/packages/medusa/src/services/product-category.ts index ed48259de4..c8f8918571 100644 --- a/packages/medusa/src/services/product-category.ts +++ b/packages/medusa/src/services/product-category.ts @@ -1,9 +1,9 @@ import { isDefined, MedusaError } from "medusa-core-utils" -import { EntityManager, DeepPartial } from "typeorm" +import { EntityManager } from "typeorm" import { TransactionBaseService } from "../interfaces" import { ProductCategory } from "../models" import { ProductCategoryRepository } from "../repositories/product-category" -import { FindConfig, Selector, QuerySelector } from "../types/common" +import { FindConfig, QuerySelector, Selector } from "../types/common" import { buildQuery } from "../utils" import { EventBusService } from "." import { @@ -23,8 +23,6 @@ type InjectedDependencies = { class ProductCategoryService extends TransactionBaseService { protected readonly productCategoryRepo_: typeof ProductCategoryRepository protected readonly eventBusService_: EventBusService - protected transactionManager_: EntityManager | undefined - protected manager_: EntityManager static Events = { CREATED: "product-category.created", @@ -33,14 +31,12 @@ class ProductCategoryService extends TransactionBaseService { } constructor({ - manager, productCategoryRepository, eventBusService, }: InjectedDependencies) { // eslint-disable-next-line prefer-rest-params super(arguments[0]) - this.manager_ = manager this.eventBusService_ = eventBusService this.productCategoryRepo_ = productCategoryRepository } @@ -61,8 +57,7 @@ class ProductCategoryService extends TransactionBaseService { }, treeSelector: QuerySelector = {} ): Promise<[ProductCategory[], number]> { - const manager = this.transactionManager_ ?? this.manager_ - const productCategoryRepo = manager.withRepository( + const productCategoryRepo = this.activeManager_.withRepository( this.productCategoryRepo_ ) @@ -103,7 +98,7 @@ class ProductCategoryService extends TransactionBaseService { const selectors = Object.assign({ id: productCategoryId }, selector) const query = buildQuery(selectors, config) - const productCategoryRepo = this.manager_.withRepository( + const productCategoryRepo = this.activeManager_.withRepository( this.productCategoryRepo_ ) @@ -229,8 +224,9 @@ class ProductCategoryService extends TransactionBaseService { productIds: string[] ): Promise { return await this.atomicPhase_(async (manager) => { - const productCategoryRepository = - manager.withRepository(this.productCategoryRepo_) + const productCategoryRepository = manager.withRepository( + this.productCategoryRepo_ + ) await productCategoryRepository.addProducts(productCategoryId, productIds) }) @@ -247,8 +243,9 @@ class ProductCategoryService extends TransactionBaseService { productIds: string[] ): Promise { return await this.atomicPhase_(async (manager) => { - const productCategoryRepository = - manager.withRepository(this.productCategoryRepo_) + const productCategoryRepository = manager.withRepository( + this.productCategoryRepo_ + ) await productCategoryRepository.removeProducts( productCategoryId, diff --git a/packages/medusa/src/services/product-collection.ts b/packages/medusa/src/services/product-collection.ts index 352aa320ee..7a730e29eb 100644 --- a/packages/medusa/src/services/product-collection.ts +++ b/packages/medusa/src/services/product-collection.ts @@ -33,22 +33,18 @@ type ListAndCountSelector = Selector & { * Provides layer to manipulate product collections. */ class ProductCollectionService extends TransactionBaseService { - protected manager_: EntityManager - protected transactionManager_: EntityManager | undefined - protected readonly eventBus_: EventBusService // eslint-disable-next-line max-len protected readonly productCollectionRepository_: typeof ProductCollectionRepository protected readonly productRepository_: typeof ProductRepository constructor({ - manager, productCollectionRepository, productRepository, eventBusService, }: InjectedDependencies) { + // eslint-disable-next-line prefer-rest-params super(arguments[0]) - this.manager_ = manager this.productCollectionRepository_ = productCollectionRepository this.productRepository_ = productRepository @@ -72,7 +68,7 @@ class ProductCollectionService extends TransactionBaseService { ) } - const collectionRepo = this.manager_.withRepository( + const collectionRepo = this.activeManager_.withRepository( this.productCollectionRepository_ ) @@ -99,7 +95,7 @@ class ProductCollectionService extends TransactionBaseService { collectionHandle: string, config: FindConfig = {} ): Promise { - const collectionRepo = this.manager_.withRepository( + const collectionRepo = this.activeManager_.withRepository( this.productCollectionRepository_ ) @@ -247,7 +243,7 @@ class ProductCollectionService extends TransactionBaseService { selector: ListAndCountSelector = {}, config: FindConfig = { skip: 0, take: 20 } ): Promise<[ProductCollection[], number]> { - const productCollectionRepo = this.manager_.withRepository( + const productCollectionRepo = this.activeManager_.withRepository( this.productCollectionRepository_ ) diff --git a/packages/medusa/src/services/product-tag.ts b/packages/medusa/src/services/product-tag.ts index 6188d276b4..80e35b5dfb 100644 --- a/packages/medusa/src/services/product-tag.ts +++ b/packages/medusa/src/services/product-tag.ts @@ -12,14 +12,12 @@ type ProductTagConstructorProps = { } class ProductTagService extends TransactionBaseService { - protected manager_: EntityManager - protected transactionManager_: EntityManager | undefined - protected readonly tagRepo_: typeof ProductTagRepository - constructor({ manager, productTagRepository }: ProductTagConstructorProps) { + constructor({ productTagRepository }: ProductTagConstructorProps) { + // eslint-disable-next-line prefer-rest-params super(arguments[0]) - this.manager_ = manager + this.tagRepo_ = productTagRepository } @@ -33,7 +31,7 @@ class ProductTagService extends TransactionBaseService { tagId: string, config: FindConfig = {} ): Promise { - const tagRepo = this.manager_.withRepository(this.tagRepo_) + const tagRepo = this.activeManager_.withRepository(this.tagRepo_) const query = buildQuery({ id: tagId }, config) const tag = await tagRepo.findOne(query) @@ -92,7 +90,7 @@ class ProductTagService extends TransactionBaseService { } = {}, config: FindConfig = { skip: 0, take: 20 } ): Promise<[ProductTag[], number]> { - const tagRepo = this.manager_.withRepository(this.tagRepo_) + const tagRepo = this.activeManager_.withRepository(this.tagRepo_) let q: string | undefined if (isString(selector.q)) { diff --git a/packages/medusa/src/services/product-tax-rate.ts b/packages/medusa/src/services/product-tax-rate.ts index 791efbef80..f63c341ed2 100644 --- a/packages/medusa/src/services/product-tax-rate.ts +++ b/packages/medusa/src/services/product-tax-rate.ts @@ -1,4 +1,3 @@ -import { EntityManager } from "typeorm" import { ProductTaxRate } from "../models" import { ProductTaxRateRepository } from "../repositories/product-tax-rate" import { FindConfig } from "../types/common" @@ -7,15 +6,12 @@ import { TransactionBaseService } from "../interfaces" import { buildQuery } from "../utils" class ProductTaxRateService extends TransactionBaseService { - protected manager_: EntityManager - protected transactionManager_: EntityManager | undefined - protected readonly productTaxRateRepository_: typeof ProductTaxRateRepository - constructor({ manager, productTaxRateRepository }) { + constructor({ productTaxRateRepository }) { + // eslint-disable-next-line prefer-rest-params super(arguments[0]) - this.manager_ = manager this.productTaxRateRepository_ = productTaxRateRepository } @@ -28,7 +24,7 @@ class ProductTaxRateService extends TransactionBaseService { selector: FilterableProductTaxRateProps, config: FindConfig = { relations: [], skip: 0, take: 20 } ): Promise { - const pTaxRateRepo = this.manager_.withRepository( + const pTaxRateRepo = this.activeManager_.withRepository( this.productTaxRateRepository_ ) diff --git a/packages/medusa/src/services/product-type.ts b/packages/medusa/src/services/product-type.ts index f42718496e..3a1a63cd42 100644 --- a/packages/medusa/src/services/product-type.ts +++ b/packages/medusa/src/services/product-type.ts @@ -1,5 +1,5 @@ import { MedusaError } from "medusa-core-utils" -import { EntityManager, FindOptionsWhere, ILike } from "typeorm" +import { FindOptionsWhere, ILike } from "typeorm" import { ProductType } from "../models" import { ProductTypeRepository } from "../repositories/product-type" import { ExtendedFindConfig, FindConfig, Selector } from "../types/common" @@ -7,15 +7,12 @@ import { TransactionBaseService } from "../interfaces" import { buildQuery, isString } from "../utils" class ProductTypeService extends TransactionBaseService { - protected manager_: EntityManager - protected transactionManager_: EntityManager | undefined - protected readonly typeRepository_: typeof ProductTypeRepository - constructor({ manager, productTypeRepository }) { + constructor({ productTypeRepository }) { + // eslint-disable-next-line prefer-rest-params super(arguments[0]) - this.manager_ = manager this.typeRepository_ = productTypeRepository } @@ -31,7 +28,7 @@ class ProductTypeService extends TransactionBaseService { id: string, config: FindConfig = {} ): Promise { - const typeRepo = this.manager_.withRepository(this.typeRepository_) + const typeRepo = this.activeManager_.withRepository(this.typeRepository_) const query = buildQuery({ id }, config) const type = await typeRepo.findOne(query) @@ -76,7 +73,7 @@ class ProductTypeService extends TransactionBaseService { } = {}, config: FindConfig = { skip: 0, take: 20 } ): Promise<[ProductType[], number]> { - const typeRepo = this.manager_.withRepository(this.typeRepository_) + const typeRepo = this.activeManager_.withRepository(this.typeRepository_) let q if (isString(selector.q)) { diff --git a/packages/medusa/src/services/product-variant-inventory.ts b/packages/medusa/src/services/product-variant-inventory.ts index 618f441d66..0a33d39558 100644 --- a/packages/medusa/src/services/product-variant-inventory.ts +++ b/packages/medusa/src/services/product-variant-inventory.ts @@ -30,9 +30,6 @@ type InjectedDependencies = { } class ProductVariantInventoryService extends TransactionBaseService { - protected manager_: EntityManager - protected transactionManager_: EntityManager | undefined - protected readonly salesChannelLocationService_: SalesChannelLocationService protected readonly salesChannelInventoryService_: SalesChannelInventoryService protected readonly productVariantService_: ProductVariantService @@ -41,7 +38,6 @@ class ProductVariantInventoryService extends TransactionBaseService { protected readonly cacheService_: CacheService constructor({ - manager, stockLocationService, salesChannelLocationService, salesChannelInventoryService, @@ -51,7 +47,6 @@ class ProductVariantInventoryService extends TransactionBaseService { // eslint-disable-next-line prefer-rest-params super(arguments[0]) - this.manager_ = manager this.salesChannelLocationService_ = salesChannelLocationService this.salesChannelInventoryService_ = salesChannelInventoryService this.stockLocationService_ = stockLocationService @@ -75,9 +70,8 @@ class ProductVariantInventoryService extends TransactionBaseService { return true } - const manager = this.transactionManager_ || this.manager_ const productVariant = await this.productVariantService_ - .withTransaction(manager) + .withTransaction(this.activeManager_) .retrieve(variantId, { select: [ "id", @@ -122,7 +116,7 @@ class ProductVariantInventoryService extends TransactionBaseService { variantInventory.map(async (inventoryPart) => { const itemQuantity = inventoryPart.required_quantity * quantity return await this.inventoryService_ - .withTransaction(manager) + .withTransaction(this.activeManager_) .confirmInventory( inventoryPart.inventory_item_id, locationIds, @@ -145,9 +139,7 @@ class ProductVariantInventoryService extends TransactionBaseService { inventoryItemId: string, variantId: string ): Promise { - const manager = this.transactionManager_ || this.manager_ - - const variantInventoryRepo = manager.getRepository( + const variantInventoryRepo = this.activeManager_.getRepository( ProductVariantInventoryItem ) @@ -171,9 +163,7 @@ class ProductVariantInventoryService extends TransactionBaseService { * @returns list of inventory items */ async listByItem(itemIds: string[]): Promise { - const manager = this.transactionManager_ || this.manager_ - - const variantInventoryRepo = manager.getRepository( + const variantInventoryRepo = this.activeManager_.getRepository( ProductVariantInventoryItem ) @@ -192,9 +182,7 @@ class ProductVariantInventoryService extends TransactionBaseService { private async listByVariant( variantId: string | string[] ): Promise { - const manager = this.transactionManager_ || this.manager_ - - const variantInventoryRepo = manager.getRepository( + const variantInventoryRepo = this.activeManager_.getRepository( ProductVariantInventoryItem ) @@ -257,23 +245,21 @@ class ProductVariantInventoryService extends TransactionBaseService { inventoryItemId: string, requiredQuantity?: number ): Promise { - const manager = this.transactionManager_ || this.manager_ - // Verify that variant exists await this.productVariantService_ - .withTransaction(manager) + .withTransaction(this.activeManager_) .retrieve(variantId, { select: ["id"], }) // Verify that item exists await this.inventoryService_ - .withTransaction(manager) + .withTransaction(this.activeManager_) .retrieveInventoryItem(inventoryItemId, { select: ["id"], }) - const variantInventoryRepo = manager.getRepository( + const variantInventoryRepo = this.activeManager_.getRepository( ProductVariantInventoryItem ) @@ -318,9 +304,7 @@ class ProductVariantInventoryService extends TransactionBaseService { inventoryItemId: string, variantId?: string ): Promise { - const manager = this.transactionManager_ || this.manager_ - - const variantInventoryRepo = manager.getRepository( + const variantInventoryRepo = this.activeManager_.getRepository( ProductVariantInventoryItem ) @@ -351,8 +335,6 @@ class ProductVariantInventoryService extends TransactionBaseService { quantity: number, context: ReserveQuantityContext = {} ): Promise { - const manager = this.transactionManager_ || this.manager_ - if (!this.inventoryService_) { return this.atomicPhase_(async (manager) => { const variantServiceTx = @@ -381,7 +363,7 @@ class ProductVariantInventoryService extends TransactionBaseService { let locationId = context.locationId if (!isDefined(locationId) && context.salesChannelId) { const locations = await this.salesChannelLocationService_ - .withTransaction(manager) + .withTransaction(this.activeManager_) .listLocationIds(context.salesChannelId) if (!locations.length) { @@ -398,7 +380,7 @@ class ProductVariantInventoryService extends TransactionBaseService { variantInventory.map(async (inventoryPart) => { const itemQuantity = inventoryPart.required_quantity * quantity return await this.inventoryService_ - .withTransaction(manager) + .withTransaction(this.activeManager_) .createReservationItem({ ...toReserve, location_id: locationId as string, @@ -440,9 +422,8 @@ class ProductVariantInventoryService extends TransactionBaseService { }) } - const manager = this.transactionManager_ || this.manager_ const [reservations, reservationCount] = await this.inventoryService_ - .withTransaction(manager) + .withTransaction(this.activeManager_) .listReservationItems( { line_item_id: lineItemId, @@ -471,11 +452,11 @@ class ProductVariantInventoryService extends TransactionBaseService { if (reservationQtyUpdate === 0) { await this.inventoryService_ - .withTransaction(manager) + .withTransaction(this.activeManager_) .deleteReservationItem(reservation.id) } else { await this.inventoryService_ - .withTransaction(manager) + .withTransaction(this.activeManager_) .updateReservationItem(reservation.id, { quantity: reservationQtyUpdate, }) @@ -558,9 +539,8 @@ class ProductVariantInventoryService extends TransactionBaseService { }) } - const manager = this.transactionManager_ || this.manager_ await this.inventoryService_ - .withTransaction(manager) + .withTransaction(this.activeManager_) .deleteReservationItemsByLineItem(lineItemId) } @@ -592,7 +572,6 @@ class ProductVariantInventoryService extends TransactionBaseService { }) }) } else { - const manager = this.transactionManager_ || this.manager_ const variantInventory = await this.listByVariant(variantId) if (variantInventory.length === 0) { @@ -603,7 +582,7 @@ class ProductVariantInventoryService extends TransactionBaseService { variantInventory.map(async (inventoryPart) => { const itemQuantity = inventoryPart.required_quantity * quantity return await this.inventoryService_ - .withTransaction(manager) + .withTransaction(this.activeManager_) .adjustInventory( inventoryPart.inventory_item_id, locationId, @@ -636,6 +615,10 @@ class ProductVariantInventoryService extends TransactionBaseService { // first get all inventory items required for a variant const variantInventory = await this.listByVariant(variant.id) + const salesChannelInventoryServiceTx = + this.salesChannelInventoryService_.withTransaction( + this.activeManager_ + ) // the inventory quantity of the variant should be equal to the inventory // item with the smallest stock, adjusted for quantity required to fulfill // the given variant @@ -648,7 +631,7 @@ class ProductVariantInventoryService extends TransactionBaseService { // can fulfill and set that as quantity return ( // eslint-disable-next-line max-len - (await this.salesChannelInventoryService_.retrieveAvailableItemQuantity( + (await salesChannelInventoryServiceTx.retrieveAvailableItemQuantity( salesChannelId, variantInventory.inventory_item_id )) / variantInventory.required_quantity diff --git a/packages/medusa/src/services/product-variant.ts b/packages/medusa/src/services/product-variant.ts index f0c1524993..749358ff82 100644 --- a/packages/medusa/src/services/product-variant.ts +++ b/packages/medusa/src/services/product-variant.ts @@ -48,9 +48,6 @@ class ProductVariantService extends TransactionBaseService { DELETED: "product-variant.deleted", } - protected manager_: EntityManager - protected transactionManager_: EntityManager | undefined - protected readonly productVariantRepository_: typeof ProductVariantRepository protected readonly productRepository_: typeof ProductRepository protected readonly eventBus_: EventBusService @@ -62,7 +59,6 @@ class ProductVariantService extends TransactionBaseService { protected readonly cartRepository_: typeof CartRepository constructor({ - manager, productVariantRepository, productRepository, eventBusService, @@ -75,7 +71,6 @@ class ProductVariantService extends TransactionBaseService { // eslint-disable-next-line prefer-rest-params super(arguments[0]) - this.manager_ = manager this.productVariantRepository_ = productVariantRepository this.productRepository_ = productRepository this.eventBus_ = eventBusService @@ -98,7 +93,7 @@ class ProductVariantService extends TransactionBaseService { include_discount_prices: false, } ): Promise { - const variantRepo = this.manager_.withRepository( + const variantRepo = this.activeManager_.withRepository( this.productVariantRepository_ ) const query = buildQuery({ id: variantId }, config) as FindOneOptions @@ -126,7 +121,7 @@ class ProductVariantService extends TransactionBaseService { include_discount_prices: false, } ): Promise { - const variantRepo = this.manager_.withRepository( + const variantRepo = this.activeManager_.withRepository( this.productVariantRepository_ ) @@ -568,7 +563,7 @@ class ProductVariantService extends TransactionBaseService { include_discount_prices: false, } ): Promise<[ProductVariant[], number]> { - const variantRepo = this.manager_.withRepository( + const variantRepo = this.activeManager_.withRepository( this.productVariantRepository_ ) @@ -628,7 +623,7 @@ class ProductVariantService extends TransactionBaseService { take: 20, } ): Promise { - const productVariantRepo = this.manager_.withRepository( + const productVariantRepo = this.activeManager_.withRepository( this.productVariantRepository_ ) diff --git a/packages/medusa/src/services/product.ts b/packages/medusa/src/services/product.ts index 0f868620bd..87faaf8357 100644 --- a/packages/medusa/src/services/product.ts +++ b/packages/medusa/src/services/product.ts @@ -49,9 +49,6 @@ type InjectedDependencies = { } class ProductService extends TransactionBaseService { - protected manager_: EntityManager - protected transactionManager_: EntityManager | undefined - protected readonly productOptionRepository_: typeof ProductOptionRepository protected readonly productRepository_: typeof ProductRepository protected readonly productVariantRepository_: typeof ProductVariantRepository @@ -73,7 +70,6 @@ class ProductService extends TransactionBaseService { } constructor({ - manager, productOptionRepository, productRepository, productVariantRepository, @@ -89,7 +85,6 @@ class ProductService extends TransactionBaseService { // eslint-disable-next-line prefer-rest-params super(arguments[0]) - this.manager_ = manager this.productOptionRepository_ = productOptionRepository this.productRepository_ = productRepository this.productVariantRepository_ = productVariantRepository @@ -144,8 +139,9 @@ class ProductService extends TransactionBaseService { include_discount_prices: false, } ): Promise<[Product[], number]> { - const manager = this.manager_ - const productRepo = manager.withRepository(this.productRepository_) + const productRepo = this.activeManager_.withRepository( + this.productRepository_ + ) const { q, ...productSelector } = selector const query = buildQuery(productSelector, config) as ExtendedFindConfig< @@ -161,8 +157,9 @@ class ProductService extends TransactionBaseService { * @return {Promise} the result of the count operation */ async count(selector: Selector = {}): Promise { - const manager = this.manager_ - const productRepo = manager.withRepository(this.productRepository_) + const productRepo = this.activeManager_.withRepository( + this.productRepository_ + ) const query = buildQuery(selector) return await productRepo.count(query) } @@ -247,8 +244,9 @@ class ProductService extends TransactionBaseService { include_discount_prices: false, // TODO: this seams to be unused from the repository } ): Promise { - const manager = this.transactionManager_ ?? this.manager_ - const productRepo = manager.withRepository(this.productRepository_) + const productRepo = this.activeManager_.withRepository( + this.productRepository_ + ) const query = buildQuery(selector, config as FindConfig) const product = await productRepo.findOne(query) @@ -322,8 +320,7 @@ class ProductService extends TransactionBaseService { } async listTypes(): Promise { - const manager = this.manager_ - const productTypeRepository = manager.withRepository( + const productTypeRepository = this.activeManager_.withRepository( this.productTypeRepository_ ) @@ -331,8 +328,9 @@ class ProductService extends TransactionBaseService { } async listTagsByUsage(count = 10): Promise { - const manager = this.manager_ - const productTagRepo = manager.withRepository(this.productTagRepository_) + const productTagRepo = this.activeManager_.withRepository( + this.productTagRepository_ + ) return await productTagRepo.listTagsByUsage(count) } @@ -777,7 +775,7 @@ class ProductService extends TransactionBaseService { title: string, productId: string ): Promise { - const productOptionRepo = this.manager_.withRepository( + const productOptionRepo = this.activeManager_.withRepository( this.productOptionRepository_ ) diff --git a/packages/medusa/src/services/publishable-api-key.ts b/packages/medusa/src/services/publishable-api-key.ts index 50363ba699..ed8e3afc46 100644 --- a/packages/medusa/src/services/publishable-api-key.ts +++ b/packages/medusa/src/services/publishable-api-key.ts @@ -31,9 +31,6 @@ class PublishableApiKeyService extends TransactionBaseService { REVOKED: "publishable_api_key.revoked", } - protected manager_: EntityManager - protected transactionManager_: EntityManager | undefined - protected readonly eventBusService_: EventBusService // eslint-disable-next-line max-len protected readonly publishableApiKeyRepository_: typeof PublishableApiKeyRepository @@ -41,14 +38,13 @@ class PublishableApiKeyService extends TransactionBaseService { protected readonly publishableApiKeySalesChannelRepository_: typeof PublishableApiKeySalesChannelRepository constructor({ - manager, eventBusService, publishableApiKeyRepository, publishableApiKeySalesChannelRepository, }: InjectedDependencies) { + // eslint-disable-next-line prefer-rest-params super(arguments[0]) - this.manager_ = manager this.eventBusService_ = eventBusService this.publishableApiKeyRepository_ = publishableApiKeyRepository this.publishableApiKeySalesChannelRepository_ = @@ -117,7 +113,9 @@ class PublishableApiKeyService extends TransactionBaseService { selector: Selector, config: FindConfig = {} ): Promise { - const repo = this.manager_.withRepository(this.publishableApiKeyRepository_) + const repo = this.activeManager_.withRepository( + this.publishableApiKeyRepository_ + ) const query = buildQuery(selector, config) query.relationLoadStrategy = "query" @@ -150,8 +148,9 @@ class PublishableApiKeyService extends TransactionBaseService { take: 20, } ): Promise<[PublishableApiKey[], number]> { - const manager = this.manager_ - const pubKeyRepo = manager.withRepository(this.publishableApiKeyRepository_) + const pubKeyRepo = this.activeManager_.withRepository( + this.publishableApiKeyRepository_ + ) let q if (isString(selector.q)) { @@ -310,8 +309,7 @@ class PublishableApiKeyService extends TransactionBaseService { publishableApiKeyId: string, config?: { q?: string } ): Promise { - const manager = this.manager_ - const pubKeySalesChannelRepo = manager.withRepository( + const pubKeySalesChannelRepo = this.activeManager_.withRepository( this.publishableApiKeySalesChannelRepository_ ) @@ -329,8 +327,7 @@ class PublishableApiKeyService extends TransactionBaseService { async getResourceScopes( publishableApiKeyId: string ): Promise<{ sales_channel_id: string[] }> { - const manager = this.manager_ - const pubKeySalesChannelRepo = manager.withRepository( + const pubKeySalesChannelRepo = this.activeManager_.withRepository( this.publishableApiKeySalesChannelRepository_ ) diff --git a/packages/medusa/src/services/region.ts b/packages/medusa/src/services/region.ts index e8f26a9e91..10a4f45a81 100644 --- a/packages/medusa/src/services/region.ts +++ b/packages/medusa/src/services/region.ts @@ -47,8 +47,6 @@ class RegionService extends TransactionBaseService { DELETED: "region.deleted", } - protected manager_: EntityManager - protected transactionManager_: EntityManager | undefined protected featureFlagRouter_: FlagRouter protected readonly eventBus_: EventBusService @@ -65,7 +63,6 @@ class RegionService extends TransactionBaseService { protected readonly taxProviderRepository_: typeof TaxProviderRepository constructor({ - manager, regionRepository, countryRepository, storeService, @@ -78,22 +75,9 @@ class RegionService extends TransactionBaseService { fulfillmentProviderService, featureFlagRouter, }: InjectedDependencies) { - super({ - manager, - regionRepository, - countryRepository, - storeService, - eventBusService, - currencyRepository, - paymentProviderRepository, - fulfillmentProviderRepository, - taxProviderRepository, - paymentProviderService, - fulfillmentProviderService, - featureFlagRouter, - }) + // eslint-disable-next-line prefer-rest-params + super(arguments[0]) - this.manager_ = manager this.regionRepository_ = regionRepository this.countryRepository_ = countryRepository this.storeService_ = storeService @@ -260,13 +244,13 @@ class RegionService extends TransactionBaseService { regionData: Omit, id?: T extends UpdateRegionInput ? string : undefined ): Promise> { - const ppRepository = this.manager_.withRepository( + const ppRepository = this.activeManager_.withRepository( this.paymentProviderRepository_ ) - const fpRepository = this.manager_.withRepository( + const fpRepository = this.activeManager_.withRepository( this.fulfillmentProviderRepository_ ) - const tpRepository = this.manager_.withRepository( + const tpRepository = this.activeManager_.withRepository( this.taxProviderRepository_ ) @@ -385,7 +369,7 @@ class RegionService extends TransactionBaseService { code: Country["iso_2"], regionId: string ): Promise { - const countryRepository = this.manager_.withRepository( + const countryRepository = this.activeManager_.withRepository( this.countryRepository_ ) @@ -434,7 +418,7 @@ class RegionService extends TransactionBaseService { code: Country["iso_2"], config: FindConfig = {} ): Promise { - const countryRepository = this.manager_.withRepository( + const countryRepository = this.activeManager_.withRepository( this.countryRepository_ ) @@ -495,7 +479,7 @@ class RegionService extends TransactionBaseService { ) } - const regionRepository = this.manager_.withRepository( + const regionRepository = this.activeManager_.withRepository( this.regionRepository_ ) @@ -527,7 +511,9 @@ class RegionService extends TransactionBaseService { take: 10, } ): Promise { - const regionRepo = this.manager_.withRepository(this.regionRepository_) + const regionRepo = this.activeManager_.withRepository( + this.regionRepository_ + ) const query = buildQuery(selector, config) return regionRepo.find(query) diff --git a/packages/medusa/src/services/return-reason.ts b/packages/medusa/src/services/return-reason.ts index 495e6c6d42..a5f11e2a23 100644 --- a/packages/medusa/src/services/return-reason.ts +++ b/packages/medusa/src/services/return-reason.ts @@ -15,14 +15,10 @@ type InjectedDependencies = { class ReturnReasonService extends TransactionBaseService { protected readonly retReasonRepo_: typeof ReturnReasonRepository - protected manager_: EntityManager - protected transactionManager_: EntityManager | undefined - - constructor({ manager, returnReasonRepository }: InjectedDependencies) { + constructor({ returnReasonRepository }: InjectedDependencies) { // eslint-disable-next-line prefer-rest-params super(arguments[0]) - this.manager_ = manager this.retReasonRepo_ = returnReasonRepository } @@ -77,7 +73,7 @@ class ReturnReasonService extends TransactionBaseService { order: { created_at: "DESC" }, } ): Promise { - const rrRepo = this.manager_.withRepository(this.retReasonRepo_) + const rrRepo = this.activeManager_.withRepository(this.retReasonRepo_) const query = buildQuery(selector, config) return rrRepo.find(query) } @@ -99,7 +95,7 @@ class ReturnReasonService extends TransactionBaseService { ) } - const rrRepo = this.manager_.withRepository(this.retReasonRepo_) + const rrRepo = this.activeManager_.withRepository(this.retReasonRepo_) const query = buildQuery({ id: returnReasonId }, config) const item = await rrRepo.findOne(query) diff --git a/packages/medusa/src/services/return.ts b/packages/medusa/src/services/return.ts index 0c21856b28..a1b264243e 100644 --- a/packages/medusa/src/services/return.ts +++ b/packages/medusa/src/services/return.ts @@ -49,9 +49,6 @@ type Transformer = ( ) => Promise> | DeepPartial class ReturnService extends TransactionBaseService { - protected manager_: EntityManager - protected transactionManager_: EntityManager | undefined - protected readonly totalsService_: TotalsService protected readonly returnRepository_: typeof ReturnRepository protected readonly returnItemRepository_: typeof ReturnItemRepository @@ -65,7 +62,6 @@ class ReturnService extends TransactionBaseService { protected readonly productVariantInventoryService_: ProductVariantInventoryService constructor({ - manager, totalsService, lineItemService, returnRepository, @@ -80,7 +76,6 @@ class ReturnService extends TransactionBaseService { // eslint-disable-next-line prefer-rest-params super(arguments[0]) - this.manager_ = manager this.totalsService_ = totalsService this.returnRepository_ = returnRepository this.returnItemRepository_ = returnItemRepository @@ -151,7 +146,9 @@ class ReturnService extends TransactionBaseService { order: { created_at: "DESC" }, } ): Promise { - const returnRepo = this.manager_.withRepository(this.returnRepository_) + const returnRepo = this.activeManager_.withRepository( + this.returnRepository_ + ) const query = buildQuery(selector, config) return returnRepo.find(query) } @@ -270,7 +267,7 @@ class ReturnService extends TransactionBaseService { ) } - const returnRepository = this.manager_.withRepository( + const returnRepository = this.activeManager_.withRepository( this.returnRepository_ ) @@ -291,7 +288,7 @@ class ReturnService extends TransactionBaseService { swapId: string, relations: string[] = [] ): Promise { - const returnRepository = this.manager_.withRepository( + const returnRepository = this.activeManager_.withRepository( this.returnRepository_ ) diff --git a/packages/medusa/src/services/sales-channel-inventory.ts b/packages/medusa/src/services/sales-channel-inventory.ts index 7a64519fca..1dd066e1c8 100644 --- a/packages/medusa/src/services/sales-channel-inventory.ts +++ b/packages/medusa/src/services/sales-channel-inventory.ts @@ -1,8 +1,7 @@ import { EntityManager } from "typeorm" -import { IInventoryService } from "../interfaces/services" - -import { SalesChannelLocationService, EventBusService } from "./" +import { EventBusService, SalesChannelLocationService } from "./" +import { IInventoryService, TransactionBaseService } from "../interfaces" type InjectedDependencies = { inventoryService: IInventoryService @@ -11,9 +10,7 @@ type InjectedDependencies = { manager: EntityManager } -class SalesChannelInventoryService { - protected manager_: EntityManager - +class SalesChannelInventoryService extends TransactionBaseService { protected readonly salesChannelLocationService_: SalesChannelLocationService protected readonly eventBusService_: EventBusService protected readonly inventoryService_: IInventoryService @@ -22,9 +19,10 @@ class SalesChannelInventoryService { salesChannelLocationService, inventoryService, eventBusService, - manager, }: InjectedDependencies) { - this.manager_ = manager + // eslint-disable-next-line prefer-rest-params + super(arguments[0]) + this.salesChannelLocationService_ = salesChannelLocationService this.eventBusService_ = eventBusService this.inventoryService_ = inventoryService @@ -40,14 +38,13 @@ class SalesChannelInventoryService { salesChannelId: string, inventoryItemId: string ): Promise { - const locationIds = await this.salesChannelLocationService_.listLocationIds( - salesChannelId - ) + const locationIds = await this.salesChannelLocationService_ + .withTransaction(this.activeManager_) + .listLocationIds(salesChannelId) - return await this.inventoryService_.retrieveAvailableQuantity( - inventoryItemId, - locationIds - ) + return await this.inventoryService_ + .withTransaction(this.activeManager_) + .retrieveAvailableQuantity(inventoryItemId, locationIds) } } diff --git a/packages/medusa/src/services/sales-channel-location.ts b/packages/medusa/src/services/sales-channel-location.ts index cfc6bfc3bc..2c64cb3432 100644 --- a/packages/medusa/src/services/sales-channel-location.ts +++ b/packages/medusa/src/services/sales-channel-location.ts @@ -1,6 +1,6 @@ import { EntityManager } from "typeorm" import { IStockLocationService, TransactionBaseService } from "../interfaces" -import { SalesChannelService, EventBusService } from "./" +import { EventBusService, SalesChannelService } from "./" import { SalesChannelLocation } from "../models/sales-channel-location" @@ -16,9 +16,6 @@ type InjectedDependencies = { */ class SalesChannelLocationService extends TransactionBaseService { - protected manager_: EntityManager - protected transactionManager_: EntityManager | undefined - protected readonly salesChannelService_: SalesChannelService protected readonly eventBusService: EventBusService protected readonly stockLocationService: IStockLocationService @@ -27,12 +24,10 @@ class SalesChannelLocationService extends TransactionBaseService { salesChannelService, stockLocationService, eventBusService, - manager, }: InjectedDependencies) { // eslint-disable-next-line prefer-rest-params super(arguments[0]) - this.manager_ = manager this.salesChannelService_ = salesChannelService this.eventBusService = eventBusService this.stockLocationService = stockLocationService @@ -48,9 +43,8 @@ class SalesChannelLocationService extends TransactionBaseService { locationId: string, salesChannelId?: string ): Promise { - const manager = this.transactionManager_ || this.manager_ - - const salesChannelLocationRepo = manager.getRepository(SalesChannelLocation) + const salesChannelLocationRepo = + this.activeManager_.getRepository(SalesChannelLocation) const where: any = { location_id: locationId, @@ -78,9 +72,8 @@ class SalesChannelLocationService extends TransactionBaseService { salesChannelId: string, locationId: string ): Promise { - const manager = this.transactionManager_ || this.manager_ const salesChannel = await this.salesChannelService_ - .withTransaction(manager) + .withTransaction(this.activeManager_) .retrieve(salesChannelId) if (this.stockLocationService) { @@ -88,12 +81,15 @@ class SalesChannelLocationService extends TransactionBaseService { await this.stockLocationService.retrieve(locationId) } - const salesChannelLocation = manager.create(SalesChannelLocation, { - sales_channel_id: salesChannel.id, - location_id: locationId, - }) + const salesChannelLocation = this.activeManager_.create( + SalesChannelLocation, + { + sales_channel_id: salesChannel.id, + location_id: locationId, + } + ) - await manager.save(salesChannelLocation) + await this.activeManager_.save(salesChannelLocation) } /** @@ -102,12 +98,11 @@ class SalesChannelLocationService extends TransactionBaseService { * @returns A promise that resolves with an array of location IDs. */ async listLocationIds(salesChannelId: string): Promise { - const manager = this.transactionManager_ || this.manager_ const salesChannel = await this.salesChannelService_ - .withTransaction(manager) + .withTransaction(this.activeManager_) .retrieve(salesChannelId) - const locations = await manager.find(SalesChannelLocation, { + const locations = await this.activeManager_.find(SalesChannelLocation, { where: { sales_channel_id: salesChannel.id }, select: ["location_id"], }) diff --git a/packages/medusa/src/services/sales-channel.ts b/packages/medusa/src/services/sales-channel.ts index b106ad73a2..6c15d8b66e 100644 --- a/packages/medusa/src/services/sales-channel.ts +++ b/packages/medusa/src/services/sales-channel.ts @@ -27,9 +27,6 @@ class SalesChannelService extends TransactionBaseService { DELETED: "sales_channel.deleted", } - protected manager_: EntityManager - protected transactionManager_: EntityManager | undefined - protected readonly salesChannelRepository_: typeof SalesChannelRepository protected readonly eventBusService_: EventBusService protected readonly storeService_: StoreService @@ -37,22 +34,16 @@ class SalesChannelService extends TransactionBaseService { constructor({ salesChannelRepository, eventBusService, - manager, storeService, }: InjectedDependencies) { // eslint-disable-next-line prefer-rest-params super(arguments[0]) - this.manager_ = manager this.salesChannelRepository_ = salesChannelRepository this.eventBusService_ = eventBusService this.storeService_ = storeService } - private getManager(): EntityManager { - return this.transactionManager_ ?? this.manager_ - } - /** * A generic retrieve used to find a sales channel by different attributes. * @@ -64,9 +55,7 @@ class SalesChannelService extends TransactionBaseService { selector: Selector, config: FindConfig = {} ): Promise { - const manager = this.getManager() - - const salesChannelRepo = manager.withRepository( + const salesChannelRepo = this.activeManager_.withRepository( this.salesChannelRepository_ ) @@ -149,8 +138,7 @@ class SalesChannelService extends TransactionBaseService { take: 20, } ): Promise<[SalesChannel[], number]> { - const manager = this.getManager() - const salesChannelRepo = manager.withRepository( + const salesChannelRepo = this.activeManager_.withRepository( this.salesChannelRepository_ ) @@ -298,11 +286,11 @@ class SalesChannelService extends TransactionBaseService { * @return the sales channel */ async retrieveDefault(): Promise { - const manager = this.getManager() - - const store = await this.storeService_.withTransaction(manager).retrieve({ - relations: ["default_sales_channel"], - }) + const store = await this.storeService_ + .withTransaction(this.activeManager_) + .retrieve({ + relations: ["default_sales_channel"], + }) if (!store.default_sales_channel) { throw new MedusaError( diff --git a/packages/medusa/src/services/shipping-option.ts b/packages/medusa/src/services/shipping-option.ts index 2d1f735115..59c73a6430 100644 --- a/packages/medusa/src/services/shipping-option.ts +++ b/packages/medusa/src/services/shipping-option.ts @@ -49,11 +49,7 @@ class ShippingOptionService extends TransactionBaseService { protected readonly methodRepository_: typeof ShippingMethodRepository protected readonly featureFlagRouter_: FlagRouter - protected manager_: EntityManager - protected transactionManager_: EntityManager | undefined - constructor({ - manager, shippingOptionRepository, shippingOptionRequirementRepository, shippingMethodRepository, @@ -64,7 +60,6 @@ class ShippingOptionService extends TransactionBaseService { // eslint-disable-next-line prefer-rest-params super(arguments[0]) - this.manager_ = manager this.optionRepository_ = shippingOptionRepository this.methodRepository_ = shippingMethodRepository this.requirementRepository_ = shippingOptionRequirementRepository @@ -151,8 +146,7 @@ class ShippingOptionService extends TransactionBaseService { selector: Selector, config: FindConfig = { skip: 0, take: 50 } ): Promise { - const manager = this.manager_ - const optRepo = manager.withRepository(this.optionRepository_) + const optRepo = this.activeManager_.withRepository(this.optionRepository_) const query = buildQuery(selector, config) return optRepo.find(query) @@ -167,8 +161,7 @@ class ShippingOptionService extends TransactionBaseService { selector: Selector, config: FindConfig = { skip: 0, take: 50 } ): Promise<[ShippingOption[], number]> { - const manager = this.manager_ - const optRepo = manager.withRepository(this.optionRepository_) + const optRepo = this.activeManager_.withRepository(this.optionRepository_) const query = buildQuery(selector, config) return await optRepo.findAndCount(query) @@ -192,8 +185,7 @@ class ShippingOptionService extends TransactionBaseService { ) } - const manager = this.manager_ - const soRepo = manager.withRepository(this.optionRepository_) + const soRepo = this.activeManager_.withRepository(this.optionRepository_) const query = buildQuery({ id: optionId }, options) diff --git a/packages/medusa/src/services/shipping-profile.ts b/packages/medusa/src/services/shipping-profile.ts index e7be3140d0..008fe58169 100644 --- a/packages/medusa/src/services/shipping-profile.ts +++ b/packages/medusa/src/services/shipping-profile.ts @@ -42,20 +42,16 @@ class ShippingProfileService extends TransactionBaseService { protected readonly shippingProfileRepository_: typeof ShippingProfileRepository protected readonly productRepository_: typeof ProductRepository - protected manager_: EntityManager - protected transactionManager_: EntityManager | undefined - constructor({ - manager, shippingProfileRepository, productService, productRepository, shippingOptionService, customShippingOptionService, }: InjectedDependencies) { + // eslint-disable-next-line prefer-rest-params super(arguments[0]) - this.manager_ = manager this.shippingProfileRepository_ = shippingProfileRepository this.productService_ = productService this.productRepository_ = productRepository @@ -72,7 +68,7 @@ class ShippingProfileService extends TransactionBaseService { selector: Selector = {}, config: FindConfig = { relations: [], skip: 0, take: 10 } ): Promise { - const shippingProfileRepo = this.manager_.withRepository( + const shippingProfileRepo = this.activeManager_.withRepository( this.shippingProfileRepository_ ) @@ -146,7 +142,7 @@ class ShippingProfileService extends TransactionBaseService { ) } - const profileRepository = this.manager_.withRepository( + const profileRepository = this.activeManager_.withRepository( this.shippingProfileRepository_ ) @@ -165,7 +161,7 @@ class ShippingProfileService extends TransactionBaseService { } async retrieveDefault(): Promise { - const profileRepository = this.manager_.withRepository( + const profileRepository = this.activeManager_.withRepository( this.shippingProfileRepository_ ) @@ -208,7 +204,7 @@ class ShippingProfileService extends TransactionBaseService { * @return the shipping profile for gift cards */ async retrieveGiftCardDefault(): Promise { - const profileRepository = this.manager_.withRepository( + const profileRepository = this.activeManager_.withRepository( this.shippingProfileRepository_ ) diff --git a/packages/medusa/src/services/shipping-tax-rate.ts b/packages/medusa/src/services/shipping-tax-rate.ts index b51e730f75..f6df5666a7 100644 --- a/packages/medusa/src/services/shipping-tax-rate.ts +++ b/packages/medusa/src/services/shipping-tax-rate.ts @@ -1,4 +1,3 @@ -import { EntityManager } from "typeorm" import { ShippingTaxRate } from "../models" import { ShippingTaxRateRepository } from "../repositories/shipping-tax-rate" import { FindConfig } from "../types/common" @@ -7,16 +6,13 @@ import { TransactionBaseService } from "../interfaces" import { buildQuery } from "../utils" class ShippingTaxRateService extends TransactionBaseService { - protected manager_: EntityManager - protected transactionManager_: EntityManager | undefined - // eslint-disable-next-line max-len protected readonly shippingTaxRateRepository_: typeof ShippingTaxRateRepository - constructor({ manager, shippingTaxRateRepository }) { + constructor({ shippingTaxRateRepository }) { + // eslint-disable-next-line prefer-rest-params super(arguments[0]) - this.manager_ = manager this.shippingTaxRateRepository_ = shippingTaxRateRepository } @@ -30,7 +26,7 @@ class ShippingTaxRateService extends TransactionBaseService { selector: FilterableShippingTaxRateProps, config: FindConfig = { relations: [], skip: 0, take: 20 } ): Promise { - const sTaxRateRepo = this.manager_.withRepository( + const sTaxRateRepo = this.activeManager_.withRepository( this.shippingTaxRateRepository_ ) diff --git a/packages/medusa/src/services/store.ts b/packages/medusa/src/services/store.ts index 361d6abcb8..465c378036 100644 --- a/packages/medusa/src/services/store.ts +++ b/packages/medusa/src/services/store.ts @@ -21,22 +21,18 @@ type InjectedDependencies = { * Provides layer to manipulate store settings. */ class StoreService extends TransactionBaseService { - protected manager_: EntityManager - protected transactionManager_: EntityManager - protected readonly storeRepository_: typeof StoreRepository protected readonly currencyRepository_: typeof CurrencyRepository protected readonly eventBus_: EventBusService constructor({ - manager, storeRepository, currencyRepository, eventBusService, }: InjectedDependencies) { + // eslint-disable-next-line prefer-rest-params super(arguments[0]) - this.manager_ = manager this.storeRepository_ = storeRepository this.currencyRepository_ = currencyRepository this.eventBus_ = eventBusService @@ -85,8 +81,7 @@ class StoreService extends TransactionBaseService { * @return the store */ async retrieve(config: FindConfig = {}): Promise { - const manager = this.manager_ - const storeRepo = manager.withRepository(this.storeRepository_) + const storeRepo = this.activeManager_.withRepository(this.storeRepository_) const query = buildQuery( { id: Not(IsNull()), diff --git a/packages/medusa/src/services/strategy-resolver.ts b/packages/medusa/src/services/strategy-resolver.ts index 070181a412..7cc6b4fbe4 100644 --- a/packages/medusa/src/services/strategy-resolver.ts +++ b/packages/medusa/src/services/strategy-resolver.ts @@ -8,12 +8,8 @@ type InjectedDependencies = { } export default class StrategyResolver extends TransactionBaseService { - protected manager_: EntityManager - protected transactionManager_: EntityManager | undefined - constructor(protected readonly container: InjectedDependencies) { super(container) - this.manager_ = container.manager } resolveBatchJobByType(type: string): AbstractBatchJobStrategy { diff --git a/packages/medusa/src/services/swap.ts b/packages/medusa/src/services/swap.ts index 38933e6f2a..25529ad36b 100644 --- a/packages/medusa/src/services/swap.ts +++ b/packages/medusa/src/services/swap.ts @@ -74,9 +74,6 @@ class SwapService extends TransactionBaseService { FULFILLMENT_CREATED: "swap.fulfillment_created", } - protected manager_: EntityManager - protected transactionManager_: EntityManager | undefined - protected readonly swapRepository_: typeof SwapRepository protected readonly cartService_: CartService @@ -94,7 +91,6 @@ class SwapService extends TransactionBaseService { protected readonly productVariantInventoryService_: ProductVariantInventoryService constructor({ - manager, swapRepository, eventBusService, cartService, @@ -112,8 +108,6 @@ class SwapService extends TransactionBaseService { // eslint-disable-next-line prefer-rest-params super(arguments[0]) - this.manager_ = manager - this.swapRepository_ = swapRepository this.totalsService_ = totalsService this.lineItemService_ = lineItemService @@ -219,7 +213,7 @@ class SwapService extends TransactionBaseService { ) } - const swapRepo = this.manager_.withRepository(this.swapRepository_) + const swapRepo = this.activeManager_.withRepository(this.swapRepository_) const { cartSelects, cartRelations, ...newConfig } = this.transformQueryForCart(config) @@ -234,7 +228,7 @@ class SwapService extends TransactionBaseService { if (cartRelations || cartSelects) { swap.cart = await this.cartService_ - .withTransaction(this.manager_) + .withTransaction(this.activeManager_) .retrieve(swap.cart_id, { select: cartSelects, relations: cartRelations, @@ -255,7 +249,7 @@ class SwapService extends TransactionBaseService { cartId: string, relations: FindConfig["relations"] = [] ): Promise { - const swapRepo = this.manager_.withRepository(this.swapRepository_) + const swapRepo = this.activeManager_.withRepository(this.swapRepository_) const swap = await swapRepo.findOne({ where: { @@ -286,7 +280,7 @@ class SwapService extends TransactionBaseService { order: { created_at: "DESC" }, } ): Promise { - const swapRepo = this.manager_.withRepository(this.swapRepository_) + const swapRepo = this.activeManager_.withRepository(this.swapRepository_) const query = buildQuery(selector, config) query.relationLoadStrategy = "query" @@ -649,7 +643,13 @@ class SwapService extends TransactionBaseService { cart = await this.cartService_ .withTransaction(manager) .retrieve(cart.id, { - relations: ["items", "items.variant", "region", "discounts", "discounts.rule"], + relations: [ + "items", + "items.variant", + "region", + "discounts", + "discounts.rule", + ], }) await Promise.all( diff --git a/packages/medusa/src/services/system-payment-provider.ts b/packages/medusa/src/services/system-payment-provider.ts index 65ae67fc7d..8a30e31ab1 100644 --- a/packages/medusa/src/services/system-payment-provider.ts +++ b/packages/medusa/src/services/system-payment-provider.ts @@ -1,10 +1,6 @@ -import { EntityManager } from "typeorm" import { TransactionBaseService } from "../interfaces/transaction-base-service" class SystemProviderService extends TransactionBaseService { - protected manager_: EntityManager - protected transactionManager_: EntityManager | undefined - static identifier = "system" constructor(_) { diff --git a/packages/medusa/src/services/tax-provider.ts b/packages/medusa/src/services/tax-provider.ts index 4771bc7f2f..f335462781 100644 --- a/packages/medusa/src/services/tax-provider.ts +++ b/packages/medusa/src/services/tax-provider.ts @@ -1,6 +1,6 @@ import { MedusaError } from "medusa-core-utils" import { AwilixContainer } from "awilix" -import { EntityManager, In } from "typeorm" +import { In } from "typeorm" import { LineItemTaxLineRepository } from "../repositories/line-item-tax-line" import { ShippingMethodTaxLineRepository } from "../repositories/shipping-method-tax-line" @@ -37,9 +37,6 @@ type RegionDetails = { * Finds tax providers and assists in tax related operations. */ class TaxProviderService extends TransactionBaseService { - protected manager_: EntityManager - protected transactionManager_: EntityManager - protected readonly container_: AwilixContainer protected readonly cacheService_: ICacheService protected readonly taxRateService_: TaxRateService @@ -58,12 +55,10 @@ class TaxProviderService extends TransactionBaseService { this.taxRateService_ = container["taxRateService"] this.eventBus_ = container["eventBusService"] this.taxProviderRepo_ = container["taxProviderRepository"] - - this.manager_ = container["manager"] } async list(): Promise { - const tpRepo = this.manager_.withRepository(this.taxProviderRepo_) + const tpRepo = this.activeManager_.withRepository(this.taxProviderRepo_) return tpRepo.find({}) } @@ -96,9 +91,7 @@ class TaxProviderService extends TransactionBaseService { async clearLineItemsTaxLines(itemIds: string[]): Promise { return await this.atomicPhase_(async (transactionManager) => { - const taxLineRepo = transactionManager.withRepository( - this.taxLineRepo_ - ) + const taxLineRepo = transactionManager.withRepository(this.taxLineRepo_) await taxLineRepo.delete({ item_id: In(itemIds) }) }) @@ -106,9 +99,7 @@ class TaxProviderService extends TransactionBaseService { async clearTaxLines(cartId: string): Promise { return await this.atomicPhase_(async (transactionManager) => { - const taxLineRepo = transactionManager.withRepository( - this.taxLineRepo_ - ) + const taxLineRepo = transactionManager.withRepository(this.taxLineRepo_) const shippingTaxRepo = transactionManager.withRepository( this.smTaxLineRepo_ ) @@ -222,7 +213,9 @@ class TaxProviderService extends TransactionBaseService { calculationContext ) - const smTaxLineRepo = this.manager_.withRepository(this.smTaxLineRepo_) + const smTaxLineRepo = this.activeManager_.withRepository( + this.smTaxLineRepo_ + ) // .create only creates entities nothing is persisted in DB return providerLines.map((pl) => { @@ -311,8 +304,10 @@ class TaxProviderService extends TransactionBaseService { calculationContext ) - const liTaxLineRepo = this.manager_.withRepository(this.taxLineRepo_) - const smTaxLineRepo = this.manager_.withRepository(this.smTaxLineRepo_) + const liTaxLineRepo = this.activeManager_.withRepository(this.taxLineRepo_) + const smTaxLineRepo = this.activeManager_.withRepository( + this.smTaxLineRepo_ + ) // .create only creates entities nothing is persisted in DB return providerLines.map((pl) => { @@ -398,7 +393,7 @@ class TaxProviderService extends TransactionBaseService { let toReturn: TaxServiceRate[] = [] const optionRates = await this.taxRateService_ - .withTransaction(this.manager_) + .withTransaction(this.activeManager_) .listByShippingOption(optionId) if (optionRates.length > 0) { @@ -445,7 +440,7 @@ class TaxProviderService extends TransactionBaseService { let toReturn: TaxServiceRate[] = [] const productRates = await this.taxRateService_ - .withTransaction(this.manager_) + .withTransaction(this.activeManager_) .listByProduct(productId, { region_id: region.id, }) @@ -486,7 +481,7 @@ class TaxProviderService extends TransactionBaseService { } async registerInstalledProviders(providers: string[]): Promise { - const model = this.manager_.withRepository(this.taxProviderRepo_) + const model = this.activeManager_.withRepository(this.taxProviderRepo_) await model.update({}, { is_installed: false }) for (const p of providers) { diff --git a/packages/medusa/src/services/tax-rate.ts b/packages/medusa/src/services/tax-rate.ts index 0c9df19059..c679873d61 100644 --- a/packages/medusa/src/services/tax-rate.ts +++ b/packages/medusa/src/services/tax-rate.ts @@ -21,24 +21,20 @@ import { buildQuery, PostgresError } from "../utils" import { TransactionBaseService } from "../interfaces" class TaxRateService extends TransactionBaseService { - protected manager_: EntityManager - protected transactionManager_: EntityManager | undefined - protected readonly productService_: ProductService protected readonly productTypeService_: ProductTypeService protected readonly shippingOptionService_: ShippingOptionService protected readonly taxRateRepository_: typeof TaxRateRepository constructor({ - manager, productService, productTypeService, shippingOptionService, taxRateRepository, }) { + // eslint-disable-next-line prefer-rest-params super(arguments[0]) - this.manager_ = manager this.taxRateRepository_ = taxRateRepository this.productService_ = productService this.productTypeService_ = productTypeService @@ -49,7 +45,9 @@ class TaxRateService extends TransactionBaseService { selector: FilterableTaxRateProps, config: FindConfig = {} ): Promise { - const taxRateRepo = this.manager_.withRepository(this.taxRateRepository_) + const taxRateRepo = this.activeManager_.withRepository( + this.taxRateRepository_ + ) const query = buildQuery(selector, config) return await taxRateRepo.findWithResolution(query) } @@ -58,7 +56,9 @@ class TaxRateService extends TransactionBaseService { selector: FilterableTaxRateProps, config: FindConfig = {} ): Promise<[TaxRate[], number]> { - const taxRateRepo = this.manager_.withRepository(this.taxRateRepository_) + const taxRateRepo = this.activeManager_.withRepository( + this.taxRateRepository_ + ) const query = buildQuery(selector, config) return await taxRateRepo.findAndCountWithResolution(query) } @@ -74,8 +74,9 @@ class TaxRateService extends TransactionBaseService { ) } - const manager = this.manager_ - const taxRateRepo = manager.withRepository(this.taxRateRepository_) + const taxRateRepo = this.activeManager_.withRepository( + this.taxRateRepository_ + ) const query = buildQuery({ id: taxRateId }, config) const taxRate = await taxRateRepo.findOneWithResolution(query) @@ -315,14 +316,16 @@ class TaxRateService extends TransactionBaseService { config: TaxRateListByConfig ): Promise { // Check both ProductTaxRate + ProductTypeTaxRate - const manager = this.manager_ - const taxRateRepo = manager.withRepository(this.taxRateRepository_) + const taxRateRepo = this.activeManager_.withRepository( + this.taxRateRepository_ + ) return await taxRateRepo.listByProduct(productId, config) } async listByShippingOption(shippingOptionId: string): Promise { - const manager = this.manager_ - const taxRateRepo = manager.withRepository(this.taxRateRepository_) + const taxRateRepo = this.activeManager_.withRepository( + this.taxRateRepository_ + ) return await taxRateRepo.listByShippingOption(shippingOptionId) } } diff --git a/packages/medusa/src/services/totals.ts b/packages/medusa/src/services/totals.ts index dfc3d1606c..e4991e94c5 100644 --- a/packages/medusa/src/services/totals.ts +++ b/packages/medusa/src/services/totals.ts @@ -102,29 +102,24 @@ type CalculationContextOptions = { * @implements {BaseService} */ class TotalsService extends TransactionBaseService { - protected manager_: EntityManager - protected transactionManager_: EntityManager - protected readonly taxProviderService_: TaxProviderService protected readonly newTotalsService_: NewTotalsService protected readonly taxCalculationStrategy_: ITaxCalculationStrategy protected readonly featureFlagRouter_: FlagRouter constructor({ - manager, taxProviderService, newTotalsService, taxCalculationStrategy, featureFlagRouter, }: TotalsServiceProps) { + // eslint-disable-next-line prefer-rest-params super(arguments[0]) - this.manager_ = manager this.taxProviderService_ = taxProviderService this.newTotalsService_ = newTotalsService this.taxCalculationStrategy_ = taxCalculationStrategy - this.manager_ = manager this.featureFlagRouter_ = featureFlagRouter } @@ -223,7 +218,7 @@ class TotalsService extends TransactionBaseService { ) } else if (totals.tax_lines.length === 0) { const orderLines = await this.taxProviderService_ - .withTransaction(this.manager_) + .withTransaction(this.activeManager_) .getTaxLines(cartOrOrder.items, calculationContext) totals.tax_lines = orderLines.filter((ol) => { @@ -392,7 +387,7 @@ class TotalsService extends TransactionBaseService { } } else { taxLines = await this.taxProviderService_ - .withTransaction(this.manager_) + .withTransaction(this.activeManager_) .getTaxLines(cartOrOrder.items, calculationContext) if (cartOrOrder.type === "swap") { @@ -872,7 +867,7 @@ class TotalsService extends TransactionBaseService { taxLines = lineItem.tax_lines } else { taxLines = (await this.taxProviderService_ - .withTransaction(this.manager_) + .withTransaction(this.activeManager_) .getTaxLines([lineItem], calculationContext)) as LineItemTaxLine[] } } diff --git a/packages/medusa/src/services/user.ts b/packages/medusa/src/services/user.ts index aade379380..fceb6f4455 100644 --- a/packages/medusa/src/services/user.ts +++ b/packages/medusa/src/services/user.ts @@ -37,8 +37,6 @@ class UserService extends TransactionBaseService { DELETED: "user.deleted", } - protected manager_: EntityManager - protected transactionManager_: EntityManager protected readonly analyticsConfigService_: AnalyticsConfigService protected readonly userRepository_: typeof UserRepository protected readonly eventBus_: EventBusService @@ -49,7 +47,6 @@ class UserService extends TransactionBaseService { eventBusService, analyticsConfigService, featureFlagRouter, - manager, }: UserServiceProps) { // eslint-disable-next-line prefer-rest-params super(arguments[0]) @@ -58,7 +55,6 @@ class UserService extends TransactionBaseService { this.analyticsConfigService_ = analyticsConfigService this.featureFlagRouter_ = featureFlagRouter this.eventBus_ = eventBusService - this.manager_ = manager } /** @@ -67,8 +63,7 @@ class UserService extends TransactionBaseService { * @return {Promise} the result of the find operation */ async list(selector: FilterableUserProps, config = {}): Promise { - const manager = this.manager_ - const userRepo = manager.withRepository(this.userRepository_) + const userRepo = this.activeManager_.withRepository(this.userRepository_) return await userRepo.find(buildQuery(selector, config)) } @@ -87,8 +82,7 @@ class UserService extends TransactionBaseService { ) } - const manager = this.manager_ - const userRepo = manager.withRepository(this.userRepository_) + const userRepo = this.activeManager_.withRepository(this.userRepository_) const query = buildQuery({ id: userId }, config) const user = await userRepo.findOne(query) @@ -114,8 +108,7 @@ class UserService extends TransactionBaseService { apiToken: string, relations: string[] = [] ): Promise { - const manager = this.manager_ - const userRepo = manager.withRepository(this.userRepository_) + const userRepo = this.activeManager_.withRepository(this.userRepository_) const user = await userRepo.findOne({ where: { api_token: apiToken }, @@ -143,8 +136,7 @@ class UserService extends TransactionBaseService { email: string, config: FindConfig = {} ): Promise { - const manager = this.manager_ - const userRepo = manager.withRepository(this.userRepository_) + const userRepo = this.activeManager_.withRepository(this.userRepository_) const query = buildQuery({ email: email.toLowerCase() }, config) const user = await userRepo.findOne(query) diff --git a/packages/stock-location/src/services/stock-location.ts b/packages/stock-location/src/services/stock-location.ts index afd08dc8dd..6ed9c35e71 100644 --- a/packages/stock-location/src/services/stock-location.ts +++ b/packages/stock-location/src/services/stock-location.ts @@ -32,13 +32,10 @@ export default class StockLocationService extends TransactionBaseService { DELETED: "stock-location.deleted", } - protected manager_: EntityManager - protected transactionManager_: EntityManager | undefined - protected readonly eventBusService_: IEventBusService constructor( - { eventBusService, manager }: InjectedDependencies, + { eventBusService }: InjectedDependencies, options?: unknown, moduleDeclaration?: ConfigurableModuleDeclaration ) { @@ -53,11 +50,6 @@ export default class StockLocationService extends TransactionBaseService { } this.eventBusService_ = eventBusService - this.manager_ = manager - } - - private getManager(): EntityManager { - return this.transactionManager_ ?? this.manager_ } /** @@ -70,7 +62,7 @@ export default class StockLocationService extends TransactionBaseService { selector: FilterableStockLocationProps = {}, config: FindConfig = { relations: [], skip: 0, take: 10 } ): Promise { - const manager = this.getManager() + const manager = this.activeManager_ const locationRepo = manager.getRepository(StockLocation) const query = buildQuery(selector, config) @@ -87,7 +79,7 @@ export default class StockLocationService extends TransactionBaseService { selector: FilterableStockLocationProps = {}, config: FindConfig = { relations: [], skip: 0, take: 10 } ): Promise<[StockLocation[], number]> { - const manager = this.getManager() + const manager = this.activeManager_ const locationRepo = manager.getRepository(StockLocation) const query = buildQuery(selector, config) @@ -112,7 +104,7 @@ export default class StockLocationService extends TransactionBaseService { ) } - const manager = this.getManager() + const manager = this.activeManager_ const locationRepo = manager.getRepository(StockLocation) const query = buildQuery({ id: stockLocationId }, config)