Chore/rm main entity concept (#7709)

**What**
Update the `MedusaService` class, factory and types to remove the concept of main modules. The idea being that all method will be explicitly named and suffixes to represent the object you are trying to manipulate.
This pr also includes various fixes in different modules

Co-authored-by: Stevche Radevski <4820812+sradevski@users.noreply.github.com>
Co-authored-by: Oli Juhl <59018053+olivermrbl@users.noreply.github.com>
This commit is contained in:
Adrien de Peretti
2024-06-19 15:02:16 +02:00
committed by GitHub
parent 2895ccfba8
commit 48963f55ef
533 changed files with 6469 additions and 9769 deletions

View File

@@ -1,3 +1,7 @@
import { moduleDefinition } from "./module-definition"
import { ModuleExports } from "@medusajs/types"
import { CustomerModuleService } from "@services"
const moduleDefinition: ModuleExports = {
service: CustomerModuleService,
}
export default moduleDefinition

View File

@@ -1,49 +1,21 @@
import { Modules } from "@medusajs/modules-sdk"
import { ModuleJoinerConfig } from "@medusajs/types"
import { MapToConfig } from "@medusajs/utils"
import { Address, Customer, CustomerGroup } from "@models"
import {
buildEntitiesNameToLinkableKeysMap,
defineJoinerConfig,
MapToConfig,
} from "@medusajs/utils"
export const LinkableKeys = {
customer_id: Customer.name,
customer_group_id: CustomerGroup.name,
customer_address_id: Address.name,
}
const entityLinkableKeysMap: MapToConfig = {}
Object.entries(LinkableKeys).forEach(([key, value]) => {
entityLinkableKeysMap[value] ??= []
entityLinkableKeysMap[value].push({
mapTo: key,
valueFrom: key.split("_").pop()!,
})
})
export const entityNameToLinkableKeysMap: MapToConfig = entityLinkableKeysMap
export const joinerConfig: ModuleJoinerConfig = {
serviceName: Modules.CUSTOMER,
primaryKeys: ["id"],
linkableKeys: LinkableKeys,
export const joinerConfig = defineJoinerConfig(Modules.CUSTOMER, {
alias: [
{
name: ["customer", "customers"],
args: {
entity: Customer.name,
},
},
{
name: ["customer_group", "customer_groups"],
args: {
entity: CustomerGroup.name,
methodSuffix: "CustomerGroups",
},
},
{
name: ["customer_address", "customer_addresses"],
args: {
entity: Address.name,
entity: "Address",
methodSuffix: "Addresses",
},
},
],
}
})
export const entityNameToLinkableKeysMap: MapToConfig =
buildEntitiesNameToLinkableKeysMap(joinerConfig.linkableKeys)

View File

@@ -2,3 +2,4 @@ export { default as Address } from "./address"
export { default as Customer } from "./customer"
export { default as CustomerGroup } from "./customer-group"
export { default as CustomerGroupCustomer } from "./customer-group-customer"

View File

@@ -1,8 +0,0 @@
import { ModuleExports } from "@medusajs/types"
import { CustomerModuleService } from "@services"
const service = CustomerModuleService
export const moduleDefinition: ModuleExports = {
service,
}

View File

@@ -1,19 +0,0 @@
#!/usr/bin/env node
import { EOL } from "os"
import { run } from "../seed"
const args = process.argv
const path = args.pop() as string
export default (async () => {
const { config } = await import("dotenv")
config()
if (!path) {
throw new Error(
`filePath is required.${EOL}Example: medusa-cart-seed <filePath>`
)
}
await run({ path })
})()

View File

@@ -1,58 +0,0 @@
import { Modules } from "@medusajs/modules-sdk"
import { LoaderOptions, Logger, ModulesSdkTypes } from "@medusajs/types"
import { DALUtils, ModulesSdkUtils } from "@medusajs/utils"
import { EntitySchema } from "@mikro-orm/core"
import * as CustomerModels from "@models"
import { EOL } from "os"
import { resolve } from "path"
export async function run({
options,
logger,
path,
}: Partial<
Pick<
LoaderOptions<ModulesSdkTypes.ModuleServiceInitializeOptions>,
"options" | "logger"
>
> & {
path: string
}) {
logger ??= console as unknown as Logger
logger.info(`Loading seed data from ${path}...`)
const { customerData } = await import(resolve(process.cwd(), path)).catch(
(e) => {
logger?.error(
`Failed to load seed data from ${path}. Please, provide a relative path and check that you export the following: customerData.${EOL}${e}`
)
throw e
}
)
const dbData = ModulesSdkUtils.loadDatabaseConfig(Modules.CUSTOMER, options)!
const entities = Object.values(CustomerModels) as unknown as EntitySchema[]
const pathToMigrations = __dirname + "/../migrations"
const orm = await DALUtils.mikroOrmCreateConnection(
dbData,
entities,
pathToMigrations
)
const manager = orm.em.fork()
try {
logger.info("Seeding customer data..")
// TODO: implement customer seed data
// await createCustomers(manager, customersData)
} catch (e) {
logger.error(
`Failed to insert the seed data in the PostgreSQL database ${dbData.clientUrl}.${EOL}${e}`
)
}
await orm.close(true)
}

View File

@@ -1,6 +1,9 @@
import {
Context,
CustomerAddressDTO,
CustomerDTO,
CustomerGroupCustomerDTO,
CustomerGroupDTO,
CustomerTypes,
DAL,
ICustomerModuleService,
@@ -14,16 +17,16 @@ import {
InjectTransactionManager,
isString,
MedusaContext,
ModulesSdkUtils,
MedusaService,
} from "@medusajs/utils"
import { entityNameToLinkableKeysMap, joinerConfig } from "../joiner-config"
import { EntityManager } from "@mikro-orm/core"
import {
Address,
Customer,
CustomerGroup,
CustomerGroupCustomer,
} from "@models"
import { EntityManager } from "@mikro-orm/core"
import { entityNameToLinkableKeysMap, joinerConfig } from "../joiner-config"
type InjectedDependencies = {
baseRepository: DAL.RepositoryService
@@ -33,33 +36,23 @@ type InjectedDependencies = {
customerGroupCustomerService: ModulesSdkTypes.IMedusaInternalService<any>
}
const generateMethodForModels = {
Address: { singular: "Address", plural: "Addresses" },
CustomerGroup,
CustomerGroupCustomer,
}
export default class CustomerModuleService<
TAddress extends Address = Address,
TCustomer extends Customer = Customer,
TCustomerGroup extends CustomerGroup = CustomerGroup,
TCustomerGroupCustomer extends CustomerGroupCustomer = CustomerGroupCustomer
>
extends ModulesSdkUtils.MedusaService<
CustomerDTO,
{
Address: { dto: any }
CustomerGroup: { dto: any }
CustomerGroupCustomer: { dto: any }
}
>(Customer, generateMethodForModels, entityNameToLinkableKeysMap)
export default class CustomerModuleService
extends MedusaService<{
Address: { dto: CustomerAddressDTO }
Customer: { dto: CustomerDTO }
CustomerGroup: { dto: CustomerGroupDTO }
CustomerGroupCustomer: { dto: CustomerGroupCustomerDTO }
}>(
{ Address, Customer, CustomerGroup, CustomerGroupCustomer },
entityNameToLinkableKeysMap
)
implements ICustomerModuleService
{
protected baseRepository_: DAL.RepositoryService
protected customerService_: ModulesSdkTypes.IMedusaInternalService<TCustomer>
protected addressService_: ModulesSdkTypes.IMedusaInternalService<TAddress>
protected customerGroupService_: ModulesSdkTypes.IMedusaInternalService<TCustomerGroup>
protected customerGroupCustomerService_: ModulesSdkTypes.IMedusaInternalService<TCustomerGroupCustomer>
protected customerService_: ModulesSdkTypes.IMedusaInternalService<Customer>
protected addressService_: ModulesSdkTypes.IMedusaInternalService<Address>
protected customerGroupService_: ModulesSdkTypes.IMedusaInternalService<CustomerGroup>
protected customerGroupCustomerService_: ModulesSdkTypes.IMedusaInternalService<CustomerGroupCustomer>
constructor(
{
@@ -85,24 +78,25 @@ export default class CustomerModuleService<
return joinerConfig
}
async create(
// @ts-expect-error
async createCustomers(
data: CustomerTypes.CreateCustomerDTO,
sharedContext?: Context
): Promise<CustomerTypes.CustomerDTO>
async create(
async createCustomers(
data: CustomerTypes.CreateCustomerDTO[],
sharedContext?: Context
): Promise<CustomerTypes.CustomerDTO[]>
@InjectManager("baseRepository_")
async create(
async createCustomers(
dataOrArray:
| CustomerTypes.CreateCustomerDTO
| CustomerTypes.CreateCustomerDTO[],
@MedusaContext() sharedContext: Context = {}
): Promise<CustomerTypes.CustomerDTO | CustomerTypes.CustomerDTO[]> {
const customers = await this.create_(dataOrArray, sharedContext)
const customers = await this.createCustomers_(dataOrArray, sharedContext)
const serialized = await this.baseRepository_.serialize<
CustomerTypes.CustomerDTO[]
@@ -114,7 +108,7 @@ export default class CustomerModuleService<
}
@InjectTransactionManager("baseRepository_")
async create_(
async createCustomers_(
dataOrArray:
| CustomerTypes.CreateCustomerDTO
| CustomerTypes.CreateCustomerDTO[],
@@ -137,29 +131,30 @@ export default class CustomerModuleService<
})
.flat()
await this.addAddresses(addressDataWithCustomerIds, sharedContext)
await this.createAddresses(addressDataWithCustomerIds, sharedContext)
return customers as unknown as CustomerTypes.CustomerDTO[]
}
update(
// @ts-expect-error
updateCustomers(
customerId: string,
data: CustomerTypes.CustomerUpdatableFields,
sharedContext?: Context
): Promise<CustomerTypes.CustomerDTO>
update(
updateCustomers(
customerIds: string[],
data: CustomerTypes.CustomerUpdatableFields,
sharedContext?: Context
): Promise<CustomerTypes.CustomerDTO[]>
update(
updateCustomers(
selector: CustomerTypes.FilterableCustomerProps,
data: CustomerTypes.CustomerUpdatableFields,
sharedContext?: Context
): Promise<CustomerTypes.CustomerDTO[]>
@InjectTransactionManager("baseRepository_")
async update(
async updateCustomers(
idsOrSelector: string | string[] | CustomerTypes.FilterableCustomerProps,
data: CustomerTypes.CustomerUpdatableFields,
@MedusaContext() sharedContext: Context = {}
@@ -203,18 +198,19 @@ export default class CustomerModuleService<
return isString(idsOrSelector) ? serialized[0] : serialized
}
async createCustomerGroup(
// @ts-expect-error
async createCustomerGroups(
dataOrArrayOfData: CustomerTypes.CreateCustomerGroupDTO,
sharedContext?: Context
): Promise<CustomerTypes.CustomerGroupDTO>
async createCustomerGroup(
async createCustomerGroups(
dataOrArrayOfData: CustomerTypes.CreateCustomerGroupDTO[],
sharedContext?: Context
): Promise<CustomerTypes.CustomerGroupDTO[]>
@InjectTransactionManager("baseRepository_")
async createCustomerGroup(
async createCustomerGroups(
dataOrArrayOfData:
| CustomerTypes.CreateCustomerGroupDTO
| CustomerTypes.CreateCustomerGroupDTO[],
@@ -232,7 +228,7 @@ export default class CustomerModuleService<
})
}
// @ts-ignore
// @ts-expect-error
async updateCustomerGroups(
groupId: string,
data: CustomerTypes.CustomerGroupUpdatableFields,
@@ -319,7 +315,7 @@ export default class CustomerModuleService<
)
if (Array.isArray(data)) {
return (groupCustomers as unknown as TCustomerGroupCustomer[]).map(
return (groupCustomers as unknown as CustomerGroupCustomer[]).map(
(gc) => ({ id: gc.id })
)
}
@@ -327,18 +323,18 @@ export default class CustomerModuleService<
return { id: groupCustomers.id }
}
// TODO: should be createAddresses to conform to the convention
async addAddresses(
// @ts-expect-error
async createAddresses(
addresses: CustomerTypes.CreateCustomerAddressDTO[],
sharedContext?: Context
): Promise<CustomerTypes.CustomerAddressDTO[]>
async addAddresses(
async createAddresses(
address: CustomerTypes.CreateCustomerAddressDTO,
sharedContext?: Context
): Promise<CustomerTypes.CustomerAddressDTO>
@InjectManager("baseRepository_")
async addAddresses(
async createAddresses(
data:
| CustomerTypes.CreateCustomerAddressDTO
| CustomerTypes.CreateCustomerAddressDTO[],
@@ -346,7 +342,7 @@ export default class CustomerModuleService<
): Promise<
CustomerTypes.CustomerAddressDTO | CustomerTypes.CustomerAddressDTO[]
> {
const addresses = await this.addAddresses_(data, sharedContext)
const addresses = await this.createAddresses_(data, sharedContext)
const serialized = await this.baseRepository_.serialize<
CustomerTypes.CustomerAddressDTO[]
@@ -360,7 +356,7 @@ export default class CustomerModuleService<
}
@InjectTransactionManager("baseRepository_")
private async addAddresses_(
private async createAddresses_(
data:
| CustomerTypes.CreateCustomerAddressDTO
| CustomerTypes.CreateCustomerAddressDTO[],
@@ -372,7 +368,7 @@ export default class CustomerModuleService<
)
}
// @ts-ignore
// @ts-expect-error
async updateAddresses(
addressId: string,
data: CustomerTypes.UpdateCustomerAddressDTO,