chore: Abstract module service (#6188)

**What**
- Remove services that do not have any custom business and replace them with a simple interfaces
- Abstract module service provide the following base implementation
  - retrieve
  - list
  - listAndCount
  - delete
  - softDelete
  - restore

The above methods are created for the main model and also for each other models for which a config is provided

all method such as list, listAndCount, delete, softDelete and restore are pluralized with the model it refers to

**Migration**
- [x] product
- [x] pricing
- [x] promotion
- [x] cart
- [x] auth
- [x] customer
- [x] payment
- [x] Sales channel
- [x] Workflow-*


**Usage**

**Module**

The module service can now extend the ` ModulesSdkUtils.abstractModuleServiceFactory` which returns a class with the default implementation for each method and each model following the standard naming convention mentioned above.
This factory have 3 template arguments being the container, the main model DTO and an object representing the other model with a config object that contains at list the DTO and optionally a singular and plural property in case it needs to be set manually. It looks like the following:

```ts
export default class PricingModuleService</* ... */>
  extends ModulesSdkUtils.abstractModuleServiceFactory<
    InjectedDependencies,
    PricingTypes.PriceSetDTO,
    {
      Currency: { dto: PricingTypes.CurrencyDTO }
      MoneyAmount: { dto: PricingTypes.MoneyAmountDTO }
      PriceSetMoneyAmount: { dto: PricingTypes.PriceSetMoneyAmountDTO }
      PriceSetMoneyAmountRules: {
        dto: PricingTypes.PriceSetMoneyAmountRulesDTO
      }
      PriceRule: { dto: PricingTypes.PriceRuleDTO }
      RuleType: { dto: PricingTypes.RuleTypeDTO }
      PriceList: { dto: PricingTypes.PriceListDTO }
      PriceListRule: { dto: PricingTypes.PriceListRuleDTO }
    }
  >(PriceSet, generateMethodForModels, entityNameToLinkableKeysMap)
  implements PricingTypes.IPricingModuleService
{
// ...
}
```

In the above, the singular and plural can be inferred as there is no tricky naming. Also, the default implementation does not remove the fact that you need to provides all the overloads etc in your module service interface. The above will provide a default implementation following the interface `AbstractModuleService` which is also auto generated, hence you will have the following methods available:

**for the main model**
- list
- retrieve
- listAndCount 
- delete
- softDelete
- restore


**for the other models**
- list**MyModels**
- retrieve**MyModel**
- listAndCount**MyModels**
- delete**MyModels**
- softDelete**MyModels**
- restore**MyModels**

**Internal module service**

The internal module service can now extend `ModulesSdkUtils.internalModuleServiceFactory` which takes only one template argument which is the container type. 
All internal services provides a default implementation for all retrieve, list, listAndCount, create, update, delete, softDelete, restore methods which follow the following interface `ModulesSdkTypes.InternalModuleService`:

```ts
export interface InternalModuleService<
  TEntity extends {},
  TContainer extends object = object
> {
  get __container__(): TContainer

  retrieve(
    idOrObject: string,
    config?: FindConfig<any>,
    sharedContext?: Context
  ): Promise<TEntity>
  retrieve(
    idOrObject: object,
    config?: FindConfig<any>,
    sharedContext?: Context
  ): Promise<TEntity>

  list(
    filters?: FilterQuery<any> | BaseFilterable<FilterQuery<any>>,
    config?: FindConfig<any>,
    sharedContext?: Context
  ): Promise<TEntity[]>

  listAndCount(
    filters?: FilterQuery<any> | BaseFilterable<FilterQuery<any>>,
    config?: FindConfig<any>,
    sharedContext?: Context
  ): Promise<[TEntity[], number]>

  create(data: any[], sharedContext?: Context): Promise<TEntity[]>
  create(data: any, sharedContext?: Context): Promise<TEntity>

  update(data: any[], sharedContext?: Context): Promise<TEntity[]>
  update(data: any, sharedContext?: Context): Promise<TEntity>
  update(
    selectorAndData: {
      selector: FilterQuery<any> | BaseFilterable<FilterQuery<any>>
      data: any
    },
    sharedContext?: Context
  ): Promise<TEntity[]>
  update(
    selectorAndData: {
      selector: FilterQuery<any> | BaseFilterable<FilterQuery<any>>
      data: any
    }[],
    sharedContext?: Context
  ): Promise<TEntity[]>

  delete(idOrSelector: string, sharedContext?: Context): Promise<void>
  delete(idOrSelector: string[], sharedContext?: Context): Promise<void>
  delete(idOrSelector: object, sharedContext?: Context): Promise<void>
  delete(idOrSelector: object[], sharedContext?: Context): Promise<void>
  delete(
    idOrSelector: {
      selector: FilterQuery<any> | BaseFilterable<FilterQuery<any>>
    },
    sharedContext?: Context
  ): Promise<void>

  softDelete(
    idsOrFilter: string[] | InternalFilterQuery,
    sharedContext?: Context
  ): Promise<[TEntity[], Record<string, unknown[]>]>

  restore(
    idsOrFilter: string[] | InternalFilterQuery,
    sharedContext?: Context
  ): Promise<[TEntity[], Record<string, unknown[]>]>

  upsert(data: any[], sharedContext?: Context): Promise<TEntity[]>
  upsert(data: any, sharedContext?: Context): Promise<TEntity>
}
```

When a service is auto generated you can use that interface to type your class property representing the expected internal service.

**Repositories**

The repositories can now extend `DALUtils.mikroOrmBaseRepositoryFactory` which takes one template argument being the entity or the template entity and provides all the default implementation. If the repository is auto generated you can type it using the `RepositoryService` interface. Here is the new interface typings.

```ts
export interface RepositoryService<T = any> extends BaseRepositoryService<T> {
  find(options?: FindOptions<T>, context?: Context): Promise<T[]>

  findAndCount(
    options?: FindOptions<T>,
    context?: Context
  ): Promise<[T[], number]>

  create(data: any[], context?: Context): Promise<T[]>

  // Becareful here, if you have a custom internal service, the update data should never be the entity otherwise
 // both entity and update will point to the same ref and create issues with mikro orm
  update(data: { entity; update }[], context?: Context): Promise<T[]>

  delete(
    idsOrPKs: FilterQuery<T> & BaseFilterable<FilterQuery<T>>,
    context?: Context
  ): Promise<void>

  /**
   * Soft delete entities and cascade to related entities if configured.
   *
   * @param idsOrFilter
   * @param context
   *
   * @returns [T[], Record<string, string[]>] the second value being the map of the entity names and ids that were soft deleted
   */
  softDelete(
    idsOrFilter: string[] | InternalFilterQuery,
    context?: Context
  ): Promise<[T[], Record<string, unknown[]>]>

  restore(
    idsOrFilter: string[] | InternalFilterQuery,
    context?: Context
  ): Promise<[T[], Record<string, unknown[]>]>

  upsert(data: any[], context?: Context): Promise<T[]>
}
```
This commit is contained in:
Adrien de Peretti
2024-02-02 14:20:32 +00:00
committed by GitHub
parent abc30517cb
commit a7be5d7b6d
163 changed files with 2867 additions and 5080 deletions
@@ -55,7 +55,7 @@ describe("Promotion Module Service: Campaigns", () => {
campaign_identifier: "test-1",
starts_at: expect.any(Date),
ends_at: expect.any(Date),
budget: expect.any(String),
budget: expect.any(Object),
created_at: expect.any(Date),
updated_at: expect.any(Date),
deleted_at: null,
@@ -68,7 +68,7 @@ describe("Promotion Module Service: Campaigns", () => {
campaign_identifier: "test-2",
starts_at: expect.any(Date),
ends_at: expect.any(Date),
budget: expect.any(String),
budget: expect.any(Object),
created_at: expect.any(Date),
updated_at: expect.any(Date),
deleted_at: null,
@@ -378,7 +378,7 @@ describe("Promotion Module Service: Campaigns", () => {
error = e
}
expect(error.message).toEqual('"campaignId" must be defined')
expect(error.message).toEqual("campaign - id must be defined")
})
it("should return campaign based on config select param", async () => {
@@ -890,7 +890,7 @@ describe("Promotion Service", () => {
error = e
}
expect(error.message).toEqual('"promotionId" must be defined')
expect(error.message).toEqual("promotion - id must be defined")
})
it("should return promotion based on config select param", async () => {
@@ -938,7 +938,7 @@ describe("Promotion Service", () => {
campaign: null,
is_automatic: false,
type: "standard",
application_method: expect.any(String),
application_method: expect.any(Object),
created_at: expect.any(Date),
updated_at: expect.any(Date),
deleted_at: null,
@@ -1081,7 +1081,7 @@ describe("Promotion Service", () => {
error = e
}
expect(error.message).toEqual('"promotionId" must be defined')
expect(error.message).toEqual("promotion - id must be defined")
})
it("should successfully create rules for a promotion", async () => {
@@ -1156,7 +1156,7 @@ describe("Promotion Service", () => {
error = e
}
expect(error.message).toEqual('"promotionId" must be defined')
expect(error.message).toEqual("promotion - id must be defined")
})
it("should successfully create target rules for a promotion", async () => {
@@ -1246,7 +1246,7 @@ describe("Promotion Service", () => {
error = e
}
expect(error.message).toEqual('"promotionId" must be defined')
expect(error.message).toEqual("promotion - id must be defined")
})
it("should successfully create buy rules for a buyget promotion", async () => {
@@ -1334,7 +1334,7 @@ describe("Promotion Service", () => {
error = e
}
expect(error.message).toEqual('"promotionId" must be defined')
expect(error.message).toEqual("promotion - id must be defined")
})
it("should successfully create rules for a promotion", async () => {
@@ -1405,7 +1405,7 @@ describe("Promotion Service", () => {
error = e
}
expect(error.message).toEqual('"promotionId" must be defined')
expect(error.message).toEqual("promotion - id must be defined")
})
it("should successfully create rules for a promotion", async () => {
@@ -1489,7 +1489,7 @@ describe("Promotion Service", () => {
error = e
}
expect(error.message).toEqual('"promotionId" must be defined')
expect(error.message).toEqual("promotion - id must be defined")
})
it("should successfully remove rules for a promotion", async () => {
@@ -4,13 +4,9 @@ import { SqlEntityManager } from "@mikro-orm/postgresql"
import { Campaign, Promotion } from "@models"
import { CreateCampaignDTO, UpdateCampaignDTO } from "@types"
export class CampaignRepository extends DALUtils.mikroOrmBaseRepositoryFactory<
Campaign,
{
create: CreateCampaignDTO
update: UpdateCampaignDTO
}
>(Campaign) {
export class CampaignRepository extends DALUtils.mikroOrmBaseRepositoryFactory<Campaign>(
Campaign
) {
async create(
data: CreateCampaignDTO[],
context: Context = {}
@@ -64,7 +60,7 @@ export class CampaignRepository extends DALUtils.mikroOrmBaseRepositoryFactory<
}
async update(
data: UpdateCampaignDTO[],
data: { entity: Campaign; update: UpdateCampaignDTO }[],
context: Context = {}
): Promise<Campaign[]> {
const manager = this.getActiveManager<SqlEntityManager>(context)
@@ -72,7 +68,7 @@ export class CampaignRepository extends DALUtils.mikroOrmBaseRepositoryFactory<
const campaignIds: string[] = []
const campaignPromotionIdsMap = new Map<string, string[]>()
data.forEach((campaignData) => {
data.forEach(({ update: campaignData }) => {
const campaignPromotionIds = campaignData.promotions?.map((p) => p.id)
campaignIds.push(campaignData.id)
@@ -1,27 +0,0 @@
import { DAL, PromotionTypes } from "@medusajs/types"
import { ApplicationMethod } from "@models"
import { ModulesSdkUtils } from "@medusajs/utils"
import { CreateApplicationMethodDTO, UpdateApplicationMethodDTO } from "@types"
type InjectedDependencies = {
applicationMethodRepository: DAL.RepositoryService
}
export default class ApplicationMethodService<
TEntity extends ApplicationMethod = ApplicationMethod
> extends ModulesSdkUtils.abstractServiceFactory<
InjectedDependencies,
{
create: CreateApplicationMethodDTO
update: UpdateApplicationMethodDTO
},
{
list: PromotionTypes.FilterableApplicationMethodProps
listAndCount: PromotionTypes.FilterableApplicationMethodProps
}
>(ApplicationMethod)<TEntity> {
constructor(...args: any[]) {
// @ts-ignore
super(...arguments)
}
}
@@ -1,27 +0,0 @@
import { DAL, PromotionTypes } from "@medusajs/types"
import { ModulesSdkUtils } from "@medusajs/utils"
import { CampaignBudget } from "@models"
import { CreateCampaignBudgetDTO, UpdateCampaignBudgetDTO } from "../types"
type InjectedDependencies = {
campaignBudgetRepository: DAL.RepositoryService
}
export default class CampaignBudgetService<
TEntity extends CampaignBudget = CampaignBudget
> extends ModulesSdkUtils.abstractServiceFactory<
InjectedDependencies,
{
create: CreateCampaignBudgetDTO
update: UpdateCampaignBudgetDTO
},
{
list: PromotionTypes.FilterableCampaignBudgetProps
listAndCount: PromotionTypes.FilterableCampaignBudgetProps
}
>(CampaignBudget)<TEntity> {
constructor(...args: any[]) {
// @ts-ignore
super(...arguments)
}
}
@@ -1,27 +0,0 @@
import { DAL, PromotionTypes } from "@medusajs/types"
import { ModulesSdkUtils } from "@medusajs/utils"
import { Campaign } from "@models"
import { CreateCampaignDTO, UpdateCampaignDTO } from "../types"
type InjectedDependencies = {
campaignRepository: DAL.RepositoryService
}
export default class CampaignService<
TEntity extends Campaign = Campaign
> extends ModulesSdkUtils.abstractServiceFactory<
InjectedDependencies,
{
create: CreateCampaignDTO
update: UpdateCampaignDTO
},
{
list: PromotionTypes.FilterableCampaignProps
listAndCount: PromotionTypes.FilterableCampaignProps
}
>(Campaign)<TEntity> {
constructor(...args: any[]) {
// @ts-ignore
super(...arguments)
}
}
-6
View File
@@ -1,7 +1 @@
export { default as ApplicationMethodService } from "./application-method"
export { default as CampaignService } from "./campaign"
export { default as CampaignBudgetService } from "./campaign-budget"
export { default as PromotionService } from "./promotion"
export { default as PromotionModuleService } from "./promotion-module"
export { default as PromotionRuleService } from "./promotion-rule"
export { default as PromotionRuleValueService } from "./promotion-rule-value"
@@ -1,23 +1,21 @@
import {
Context,
DAL,
FindConfig,
InternalModuleDeclaration,
ModuleJoinerConfig,
ModulesSdkTypes,
PromotionTypes,
RestoreReturn,
SoftDeleteReturn,
} from "@medusajs/types"
import {
ApplicationMethodTargetType,
CampaignBudgetType,
InjectManager,
InjectTransactionManager,
isString,
MedusaContext,
MedusaError,
ModulesSdkUtils,
PromotionType,
isString,
mapObjectTo,
} from "@medusajs/utils"
import {
ApplicationMethod,
@@ -27,14 +25,6 @@ import {
PromotionRule,
PromotionRuleValue,
} from "@models"
import {
ApplicationMethodService,
CampaignBudgetService,
CampaignService,
PromotionRuleService,
PromotionRuleValueService,
PromotionService,
} from "@services"
import {
ApplicationMethodRuleTypes,
CreateApplicationMethodDTO,
@@ -48,43 +38,60 @@ import {
UpdatePromotionDTO,
} from "@types"
import {
ComputeActionUtils,
allowedAllocationForQuantity,
areRulesValidForContext,
ComputeActionUtils,
validateApplicationMethodAttributes,
validatePromotionRuleAttributes,
} from "@utils"
import {
LinkableKeys,
entityNameToLinkableKeysMap,
joinerConfig,
} from "../joiner-config"
import { entityNameToLinkableKeysMap, joinerConfig } from "../joiner-config"
type InjectedDependencies = {
baseRepository: DAL.RepositoryService
promotionService: PromotionService<any>
applicationMethodService: ApplicationMethodService<any>
promotionRuleService: PromotionRuleService<any>
promotionRuleValueService: PromotionRuleValueService<any>
campaignService: CampaignService<any>
campaignBudgetService: CampaignBudgetService<any>
promotionService: ModulesSdkTypes.InternalModuleService<any>
applicationMethodService: ModulesSdkTypes.InternalModuleService<any>
promotionRuleService: ModulesSdkTypes.InternalModuleService<any>
promotionRuleValueService: ModulesSdkTypes.InternalModuleService<any>
campaignService: ModulesSdkTypes.InternalModuleService<any>
campaignBudgetService: ModulesSdkTypes.InternalModuleService<any>
}
const generateMethodForModels = [
ApplicationMethod,
Campaign,
CampaignBudget,
PromotionRule,
PromotionRuleValue,
]
export default class PromotionModuleService<
TPromotion extends Promotion = Promotion,
TPromotionRule extends PromotionRule = PromotionRule,
TPromotionRuleValue extends PromotionRuleValue = PromotionRuleValue,
TCampaign extends Campaign = Campaign,
TCampaignBudget extends CampaignBudget = CampaignBudget
> implements PromotionTypes.IPromotionModuleService
TApplicationMethod extends ApplicationMethod = ApplicationMethod,
TPromotion extends Promotion = Promotion,
TPromotionRule extends PromotionRule = PromotionRule,
TPromotionRuleValue extends PromotionRuleValue = PromotionRuleValue,
TCampaign extends Campaign = Campaign,
TCampaignBudget extends CampaignBudget = CampaignBudget
>
extends ModulesSdkUtils.abstractModuleServiceFactory<
InjectedDependencies,
PromotionTypes.PromotionDTO,
{
ApplicationMethod: { dto: PromotionTypes.ApplicationMethodDTO }
Campaign: { dto: PromotionTypes.CampaignDTO }
CampaignBudget: { dto: PromotionTypes.CampaignBudgetDTO }
PromotionRule: { dto: PromotionTypes.PromotionRuleDTO }
PromotionRuleValue: { dto: PromotionTypes.PromotionRuleValueDTO }
}
>(Promotion, generateMethodForModels, entityNameToLinkableKeysMap)
implements PromotionTypes.IPromotionModuleService
{
protected baseRepository_: DAL.RepositoryService
protected promotionService_: PromotionService<TPromotion>
protected applicationMethodService_: ApplicationMethodService
protected promotionRuleService_: PromotionRuleService<TPromotionRule>
protected promotionRuleValueService_: PromotionRuleValueService<TPromotionRuleValue>
protected campaignService_: CampaignService<TCampaign>
protected campaignBudgetService_: CampaignBudgetService<TCampaignBudget>
protected promotionService_: ModulesSdkTypes.InternalModuleService<TPromotion>
protected applicationMethodService_: ModulesSdkTypes.InternalModuleService<TApplicationMethod>
protected promotionRuleService_: ModulesSdkTypes.InternalModuleService<TPromotionRule>
protected promotionRuleValueService_: ModulesSdkTypes.InternalModuleService<TPromotionRuleValue>
protected campaignService_: ModulesSdkTypes.InternalModuleService<TCampaign>
protected campaignBudgetService_: ModulesSdkTypes.InternalModuleService<TCampaignBudget>
constructor(
{
@@ -98,6 +105,9 @@ export default class PromotionModuleService<
}: InjectedDependencies,
protected readonly moduleDeclaration: InternalModuleDeclaration
) {
// @ts-ignore
super(...arguments)
this.baseRepository_ = baseRepository
this.promotionService_ = promotionService
this.applicationMethodService_ = applicationMethodService
@@ -399,63 +409,6 @@ export default class PromotionModuleService<
return computedActions
}
@InjectManager("baseRepository_")
async retrieve(
id: string,
config: FindConfig<PromotionTypes.PromotionDTO> = {},
@MedusaContext() sharedContext: Context = {}
): Promise<PromotionTypes.PromotionDTO> {
const promotion = await this.promotionService_.retrieve(
id,
config,
sharedContext
)
return await this.baseRepository_.serialize<PromotionTypes.PromotionDTO>(
promotion,
{ populate: true }
)
}
@InjectManager("baseRepository_")
async list(
filters: PromotionTypes.FilterablePromotionProps = {},
config: FindConfig<PromotionTypes.PromotionDTO> = {},
@MedusaContext() sharedContext: Context = {}
): Promise<PromotionTypes.PromotionDTO[]> {
const promotions = await this.promotionService_.list(
filters,
config,
sharedContext
)
return await this.baseRepository_.serialize<PromotionTypes.PromotionDTO[]>(
promotions,
{ populate: true }
)
}
@InjectManager("baseRepository_")
async listAndCount(
filters: PromotionTypes.FilterablePromotionProps = {},
config: FindConfig<PromotionTypes.PromotionDTO> = {},
@MedusaContext() sharedContext: Context = {}
): Promise<[PromotionTypes.PromotionDTO[], number]> {
const [promotions, count] = await this.promotionService_.listAndCount(
filters,
config,
sharedContext
)
return [
await this.baseRepository_.serialize<PromotionTypes.PromotionDTO[]>(
promotions,
{ populate: true }
),
count,
]
}
async create(
data: PromotionTypes.CreatePromotionDTO,
sharedContext?: Context
@@ -921,88 +874,6 @@ export default class PromotionModuleService<
}
}
@InjectTransactionManager("baseRepository_")
async delete(
ids: string[] | string,
@MedusaContext() sharedContext: Context = {}
): Promise<void> {
const idsToDelete = Array.isArray(ids) ? ids : [ids]
await this.promotionService_.delete(idsToDelete, sharedContext)
}
@InjectManager("baseRepository_")
async softDelete<
TReturnableLinkableKeys extends string = Lowercase<
keyof typeof LinkableKeys
>
>(
ids: string | string[],
{ returnLinkableKeys }: SoftDeleteReturn<TReturnableLinkableKeys> = {},
@MedusaContext() sharedContext: Context = {}
): Promise<Record<Lowercase<keyof typeof LinkableKeys>, string[]> | void> {
const idsToDelete = Array.isArray(ids) ? ids : [ids]
let [_, cascadedEntitiesMap] = await this.softDelete_(
idsToDelete,
sharedContext
)
let mappedCascadedEntitiesMap
if (returnLinkableKeys) {
mappedCascadedEntitiesMap = mapObjectTo<
Record<Lowercase<keyof typeof LinkableKeys>, string[]>
>(cascadedEntitiesMap, entityNameToLinkableKeysMap, {
pick: returnLinkableKeys,
})
}
return mappedCascadedEntitiesMap ? mappedCascadedEntitiesMap : void 0
}
@InjectTransactionManager("baseRepository_")
protected async softDelete_(
promotionIds: string[],
@MedusaContext() sharedContext: Context = {}
): Promise<[TPromotion[], Record<string, unknown[]>]> {
return await this.promotionService_.softDelete(promotionIds, sharedContext)
}
@InjectManager("baseRepository_")
async restore<
TReturnableLinkableKeys extends string = Lowercase<
keyof typeof LinkableKeys
>
>(
ids: string | string[],
{ returnLinkableKeys }: RestoreReturn<TReturnableLinkableKeys> = {},
@MedusaContext() sharedContext: Context = {}
): Promise<Record<Lowercase<keyof typeof LinkableKeys>, string[]> | void> {
const idsToRestore = Array.isArray(ids) ? ids : [ids]
const [_, cascadedEntitiesMap] = await this.restore_(
idsToRestore,
sharedContext
)
let mappedCascadedEntitiesMap
if (returnLinkableKeys) {
mappedCascadedEntitiesMap = mapObjectTo<
Record<Lowercase<keyof typeof LinkableKeys>, string[]>
>(cascadedEntitiesMap, entityNameToLinkableKeysMap, {
pick: returnLinkableKeys,
})
}
return mappedCascadedEntitiesMap ? mappedCascadedEntitiesMap : void 0
}
@InjectTransactionManager("baseRepository_")
async restore_(
ids: string[],
@MedusaContext() sharedContext: Context = {}
): Promise<[TPromotion[], Record<string, unknown[]>]> {
return await this.promotionService_.restore(ids, sharedContext)
}
@InjectManager("baseRepository_")
async removePromotionRules(
promotionId: string,
@@ -1134,63 +1005,6 @@ export default class PromotionModuleService<
)
}
@InjectManager("baseRepository_")
async retrieveCampaign(
id: string,
config: FindConfig<PromotionTypes.CampaignDTO> = {},
@MedusaContext() sharedContext: Context = {}
): Promise<PromotionTypes.CampaignDTO> {
const campaign = await this.campaignService_.retrieve(
id,
config,
sharedContext
)
return await this.baseRepository_.serialize<PromotionTypes.CampaignDTO>(
campaign,
{ populate: true }
)
}
@InjectManager("baseRepository_")
async listCampaigns(
filters: PromotionTypes.FilterableCampaignProps = {},
config: FindConfig<PromotionTypes.CampaignDTO> = {},
@MedusaContext() sharedContext: Context = {}
): Promise<PromotionTypes.CampaignDTO[]> {
const campaigns = await this.campaignService_.list(
filters,
config,
sharedContext
)
return await this.baseRepository_.serialize<PromotionTypes.CampaignDTO[]>(
campaigns,
{ populate: true }
)
}
@InjectManager("baseRepository_")
async listAndCountCampaigns(
filters: PromotionTypes.FilterableCampaignProps = {},
config: FindConfig<PromotionTypes.CampaignDTO> = {},
@MedusaContext() sharedContext: Context = {}
): Promise<[PromotionTypes.CampaignDTO[], number]> {
const [campaigns, count] = await this.campaignService_.listAndCount(
filters,
config,
sharedContext
)
return [
await this.baseRepository_.serialize<PromotionTypes.CampaignDTO[]>(
campaigns,
{ populate: true }
),
count,
]
}
async createCampaigns(
data: PromotionTypes.CreateCampaignDTO,
sharedContext?: Context
@@ -1361,82 +1175,4 @@ export default class PromotionModuleService<
return updatedCampaigns
}
@InjectTransactionManager("baseRepository_")
async deleteCampaigns(
ids: string | string[],
@MedusaContext() sharedContext: Context = {}
): Promise<void> {
const idsToDelete = Array.isArray(ids) ? ids : [ids]
await this.campaignService_.delete(idsToDelete, sharedContext)
}
@InjectManager("baseRepository_")
async softDeleteCampaigns<TReturnableLinkableKeys extends string>(
ids: string | string[],
{ returnLinkableKeys }: SoftDeleteReturn<TReturnableLinkableKeys> = {},
@MedusaContext() sharedContext: Context = {}
): Promise<Record<Lowercase<keyof typeof LinkableKeys>, string[]> | void> {
const idsToDelete = Array.isArray(ids) ? ids : [ids]
let [_, cascadedEntitiesMap] = await this.softDeleteCampaigns_(
idsToDelete,
sharedContext
)
let mappedCascadedEntitiesMap
if (returnLinkableKeys) {
mappedCascadedEntitiesMap = mapObjectTo<
Record<Lowercase<keyof typeof LinkableKeys>, string[]>
>(cascadedEntitiesMap, entityNameToLinkableKeysMap, {
pick: returnLinkableKeys,
})
}
return mappedCascadedEntitiesMap ? mappedCascadedEntitiesMap : void 0
}
@InjectTransactionManager("baseRepository_")
protected async softDeleteCampaigns_(
campaignIds: string[],
@MedusaContext() sharedContext: Context = {}
): Promise<[TCampaign[], Record<string, unknown[]>]> {
return await this.campaignService_.softDelete(campaignIds, sharedContext)
}
@InjectManager("baseRepository_")
async restoreCampaigns<
TReturnableLinkableKeys extends string = Lowercase<
keyof typeof LinkableKeys
>
>(
ids: string | string[],
{ returnLinkableKeys }: RestoreReturn<TReturnableLinkableKeys> = {},
@MedusaContext() sharedContext: Context = {}
): Promise<Record<Lowercase<keyof typeof LinkableKeys>, string[]> | void> {
const idsToRestore = Array.isArray(ids) ? ids : [ids]
const [_, cascadedEntitiesMap] = await this.restoreCampaigns_(
idsToRestore,
sharedContext
)
let mappedCascadedEntitiesMap
if (returnLinkableKeys) {
mappedCascadedEntitiesMap = mapObjectTo<
Record<Lowercase<keyof typeof LinkableKeys>, string[]>
>(cascadedEntitiesMap, entityNameToLinkableKeysMap, {
pick: returnLinkableKeys,
})
}
return mappedCascadedEntitiesMap ? mappedCascadedEntitiesMap : void 0
}
@InjectTransactionManager("baseRepository_")
async restoreCampaigns_(
ids: string[],
@MedusaContext() sharedContext: Context = {}
): Promise<[TCampaign[], Record<string, unknown[]>]> {
return await this.campaignService_.restore(ids, sharedContext)
}
}
@@ -1,30 +0,0 @@
import { DAL, PromotionTypes } from "@medusajs/types"
import { ModulesSdkUtils } from "@medusajs/utils"
import { PromotionRuleValue } from "@models"
import {
CreatePromotionRuleValueDTO,
UpdatePromotionRuleValueDTO,
} from "../types"
type InjectedDependencies = {
promotionRuleValueRepository: DAL.RepositoryService
}
export default class PromotionRuleValueService<
TEntity extends PromotionRuleValue = PromotionRuleValue
> extends ModulesSdkUtils.abstractServiceFactory<
InjectedDependencies,
{
create: CreatePromotionRuleValueDTO
update: UpdatePromotionRuleValueDTO
},
{
list: PromotionTypes.FilterablePromotionRuleValueProps
listAndCount: PromotionTypes.FilterablePromotionRuleValueProps
}
>(PromotionRuleValue)<TEntity> {
constructor(...args: any[]) {
// @ts-ignore
super(...arguments)
}
}
@@ -1,27 +0,0 @@
import { DAL, PromotionTypes } from "@medusajs/types"
import { ModulesSdkUtils } from "@medusajs/utils"
import { PromotionRule } from "@models"
import { CreatePromotionRuleDTO, UpdatePromotionRuleDTO } from "../types"
type InjectedDependencies = {
promotionRuleRepository: DAL.RepositoryService
}
export default class PromotionRuleService<
TEntity extends PromotionRule = PromotionRule
> extends ModulesSdkUtils.abstractServiceFactory<
InjectedDependencies,
{
create: CreatePromotionRuleDTO
update: UpdatePromotionRuleDTO
},
{
list: PromotionTypes.FilterablePromotionRuleProps
listAndCount: PromotionTypes.FilterablePromotionRuleProps
}
>(PromotionRule)<TEntity> {
constructor(...args: any[]) {
// @ts-ignore
super(...arguments)
}
}
@@ -1,27 +0,0 @@
import { DAL, PromotionTypes } from "@medusajs/types"
import { ModulesSdkUtils } from "@medusajs/utils"
import { Promotion } from "@models"
import { CreatePromotionDTO, UpdatePromotionDTO } from "../types"
type InjectedDependencies = {
promotionRepository: DAL.RepositoryService
}
export default class PromotionService<
TEntity extends Promotion = Promotion
> extends ModulesSdkUtils.abstractServiceFactory<
InjectedDependencies,
{
create: CreatePromotionDTO
update: UpdatePromotionDTO
},
{
list: PromotionTypes.FilterablePromotionProps
listAndCount: PromotionTypes.FilterablePromotionProps
}
>(Promotion)<TEntity> {
constructor(...args: any[]) {
// @ts-ignore
super(...arguments)
}
}
-1
View File
@@ -10,4 +10,3 @@ export * from "./campaign-budget"
export * from "./promotion"
export * from "./promotion-rule"
export * from "./promotion-rule-value"
export * from "./repositories"
@@ -1,91 +0,0 @@
import {
ApplicationMethod,
Campaign,
CampaignBudget,
Promotion,
PromotionRule,
PromotionRuleValue,
} from "@models"
import { DAL } from "@medusajs/types"
import {
CreateApplicationMethodDTO,
UpdateApplicationMethodDTO,
} from "./application-method"
import { CreateCampaignDTO, UpdateCampaignDTO } from "./campaign"
import {
CreateCampaignBudgetDTO,
UpdateCampaignBudgetDTO,
} from "./campaign-budget"
import { CreatePromotionDTO, UpdatePromotionDTO } from "./promotion"
import {
CreatePromotionRuleDTO,
UpdatePromotionRuleDTO,
} from "./promotion-rule"
import {
CreatePromotionRuleValueDTO,
UpdatePromotionRuleValueDTO,
} from "./promotion-rule-value"
// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface IApplicationMethodRepository<
TEntity extends ApplicationMethod = ApplicationMethod
> extends DAL.RepositoryService<
TEntity,
{
create: CreateApplicationMethodDTO
update: UpdateApplicationMethodDTO
}
> {}
// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface ICampaignRepository<TEntity extends Campaign = Campaign>
extends DAL.RepositoryService<
TEntity,
{
create: CreateCampaignDTO
update: UpdateCampaignDTO
}
> {}
// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface ICampaignBudgetRepository<
TEntity extends CampaignBudget = CampaignBudget
> extends DAL.RepositoryService<
TEntity,
{
create: CreateCampaignBudgetDTO
update: UpdateCampaignBudgetDTO
}
> {}
// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface IPromotionRepository<TEntity extends Promotion = Promotion>
extends DAL.RepositoryService<
TEntity,
{
create: CreatePromotionDTO
Update: UpdatePromotionDTO
}
> {}
// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface IPromotionRuleRepository<
TEntity extends PromotionRule = PromotionRule
> extends DAL.RepositoryService<
TEntity,
{
create: CreatePromotionRuleDTO
update: UpdatePromotionRuleDTO
}
> {}
// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface IPromotionRuleValueRepository<
TEntity extends PromotionRuleValue = PromotionRuleValue
> extends DAL.RepositoryService<
TEntity,
{
create: CreatePromotionRuleValueDTO
update: UpdatePromotionRuleValueDTO
}
> {}