feat(medusa): Expose an activeManager_ getter in TransactionBaseService (#3256)

This commit is contained in:
Adrien de Peretti authored and GitHub committed 2023-02-16 10:26:23 +00:00
1 parent 75924b682f
commit aefe5aa133
68 files changed
+514 -839

No files matched your search

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