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 13:02:16 +00:00
committed by GitHub
co-authored by Stevche Radevski Oli Juhl
parent 2895ccfba8
commit 48963f55ef
533 changed files with 6469 additions and 9769 deletions
+8 -1
View File
@@ -1,3 +1,10 @@
import { moduleDefinition } from "./module-definition"
import { ModuleExports } from "@medusajs/types"
import { CartModuleService } from "./services"
const service = CartModuleService
export const moduleDefinition: ModuleExports = {
service,
}
export default moduleDefinition
+7 -94
View File
@@ -1,98 +1,11 @@
import { Modules } from "@medusajs/modules-sdk"
import { ModuleJoinerConfig } from "@medusajs/types"
import { MapToConfig } from "@medusajs/utils"
import {
Address,
Cart,
LineItem,
LineItemAdjustment,
LineItemTaxLine,
ShippingMethod,
ShippingMethodAdjustment,
ShippingMethodTaxLine,
} from "@models"
buildEntitiesNameToLinkableKeysMap,
defineJoinerConfig,
MapToConfig,
} from "@medusajs/utils"
export const LinkableKeys = {
cart_id: Cart.name,
line_item_id: LineItem.name,
shipping_method_id: ShippingMethod.name,
address_id: Address.name,
line_item_adjustment_id: LineItemAdjustment.name,
shipping_method_adjustment_id: ShippingMethodAdjustment.name,
line_item_tax_line_id: LineItemTaxLine.name,
shipping_method_tax_line_id: ShippingMethodTaxLine.name,
}
export const joinerConfig = defineJoinerConfig(Modules.CART)
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.CART,
primaryKeys: ["id"],
linkableKeys: LinkableKeys,
alias: [
{
name: ["cart", "carts"],
args: {
entity: Cart.name,
},
},
{
name: ["line_item", "line_items"],
args: {
entity: LineItem.name,
methodSuffix: "LineItems",
},
},
{
name: ["shipping_method", "shipping_methods"],
args: {
entity: ShippingMethod.name,
methodSuffix: "ShippingMethods",
},
},
{
name: ["address", "addresses"],
args: {
entity: Address.name,
methodSuffix: "Addresses",
},
},
{
name: ["line_item_adjustment", "line_item_adjustments"],
args: {
entity: LineItemAdjustment.name,
methodSuffix: "LineItemAdjustments",
},
},
{
name: ["shipping_method_adjustment", "shipping_method_adjustments"],
args: {
entity: ShippingMethodAdjustment.name,
methodSuffix: "ShippingMethodAdjustments",
},
},
{
name: ["line_item_tax_line", "line_item_tax_lines"],
args: {
entity: LineItemTaxLine.name,
methodSuffix: "LineItemTaxLines",
},
},
{
name: ["shipping_method_tax_line", "shipping_method_tax_lines"],
args: {
entity: ShippingMethodTaxLine.name,
methodSuffix: "ShippingMethodTaxLines",
},
},
],
}
export const entityNameToLinkableKeysMap: MapToConfig =
buildEntitiesNameToLinkableKeysMap(joinerConfig.linkableKeys)
@@ -1,8 +0,0 @@
import { ModuleExports } from "@medusajs/types"
import { CartModuleService } from "./services"
const service = CartModuleService
export const moduleDefinition: ModuleExports = {
service,
}
@@ -1,2 +0,0 @@
export { MikroOrmBaseRepository as BaseRepository } from "@medusajs/utils";
@@ -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 })
})()
-63
View File
@@ -1,63 +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 CartModels 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 { cartData } = 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: cartData.${EOL}${e}`
)
throw e
})
const dbData = ModulesSdkUtils.loadDatabaseConfig(
Modules.CART,
options
)!
const entities = Object.values(
CartModels
) 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 cart data..")
// TODO: implement cart seed data
// await createCarts(manager, cartsData)
} catch (e) {
logger.error(
`Failed to insert the seed data in the PostgreSQL database ${dbData.clientUrl}.${EOL}${e}`
)
}
await orm.close(true)
}
@@ -54,6 +54,7 @@ type InjectedDependencies = {
}
const generateMethodForModels = {
Cart,
Address,
LineItem,
LineItemAdjustment,
@@ -63,39 +64,28 @@ const generateMethodForModels = {
ShippingMethodTaxLine,
}
export default class CartModuleService<
TCart extends Cart = Cart,
TAddress extends Address = Address,
TLineItem extends LineItem = LineItem,
TLineItemAdjustment extends LineItemAdjustment = LineItemAdjustment,
TLineItemTaxLine extends LineItemTaxLine = LineItemTaxLine,
TShippingMethodAdjustment extends ShippingMethodAdjustment = ShippingMethodAdjustment,
TShippingMethodTaxLine extends ShippingMethodTaxLine = ShippingMethodTaxLine,
TShippingMethod extends ShippingMethod = ShippingMethod
>
extends ModulesSdkUtils.MedusaService<
CartTypes.CartDTO,
{
Address: { dto: CartTypes.CartAddressDTO }
LineItem: { dto: CartTypes.CartLineItemDTO }
LineItemAdjustment: { dto: CartTypes.LineItemAdjustmentDTO }
LineItemTaxLine: { dto: CartTypes.LineItemTaxLineDTO }
ShippingMethod: { dto: CartTypes.CartShippingMethodDTO }
ShippingMethodAdjustment: { dto: CartTypes.ShippingMethodAdjustmentDTO }
ShippingMethodTaxLine: { dto: CartTypes.ShippingMethodTaxLineDTO }
}
>(Cart, generateMethodForModels, entityNameToLinkableKeysMap)
export default class CartModuleService
extends ModulesSdkUtils.MedusaService<{
Cart: { dto: CartTypes.CartDTO }
Address: { dto: CartTypes.CartAddressDTO }
LineItem: { dto: CartTypes.CartLineItemDTO }
LineItemAdjustment: { dto: CartTypes.LineItemAdjustmentDTO }
LineItemTaxLine: { dto: CartTypes.LineItemTaxLineDTO }
ShippingMethod: { dto: CartTypes.CartShippingMethodDTO }
ShippingMethodAdjustment: { dto: CartTypes.ShippingMethodAdjustmentDTO }
ShippingMethodTaxLine: { dto: CartTypes.ShippingMethodTaxLineDTO }
}>(generateMethodForModels, entityNameToLinkableKeysMap)
implements ICartModuleService
{
protected baseRepository_: DAL.RepositoryService
protected cartService_: ModulesSdkTypes.IMedusaInternalService<TCart>
protected addressService_: ModulesSdkTypes.IMedusaInternalService<TAddress>
protected lineItemService_: ModulesSdkTypes.IMedusaInternalService<TLineItem>
protected shippingMethodAdjustmentService_: ModulesSdkTypes.IMedusaInternalService<TShippingMethodAdjustment>
protected shippingMethodService_: ModulesSdkTypes.IMedusaInternalService<TShippingMethod>
protected lineItemAdjustmentService_: ModulesSdkTypes.IMedusaInternalService<TLineItemAdjustment>
protected lineItemTaxLineService_: ModulesSdkTypes.IMedusaInternalService<TLineItemTaxLine>
protected shippingMethodTaxLineService_: ModulesSdkTypes.IMedusaInternalService<TShippingMethodTaxLine>
protected cartService_: ModulesSdkTypes.IMedusaInternalService<Cart>
protected addressService_: ModulesSdkTypes.IMedusaInternalService<Address>
protected lineItemService_: ModulesSdkTypes.IMedusaInternalService<LineItem>
protected shippingMethodAdjustmentService_: ModulesSdkTypes.IMedusaInternalService<ShippingMethodAdjustment>
protected shippingMethodService_: ModulesSdkTypes.IMedusaInternalService<ShippingMethod>
protected lineItemAdjustmentService_: ModulesSdkTypes.IMedusaInternalService<LineItemAdjustment>
protected lineItemTaxLineService_: ModulesSdkTypes.IMedusaInternalService<LineItemTaxLine>
protected shippingMethodTaxLineService_: ModulesSdkTypes.IMedusaInternalService<ShippingMethodTaxLine>
constructor(
{
@@ -189,7 +179,8 @@ export default class CartModuleService<
})
}
async retrieve(
// @ts-expect-error
async retrieveCart(
id: string,
config?: FindConfig<any> | undefined,
sharedContext?: Context | undefined
@@ -197,7 +188,7 @@ export default class CartModuleService<
config ??= {}
const includeTotals = this.shouldIncludeTotals(config)
const cart = await super.retrieve(id, config, sharedContext)
const cart = await super.retrieveCart(id, config, sharedContext)
if (includeTotals) {
createRawPropertiesFromBigNumber(decorateCartTotals(cart))
@@ -206,7 +197,8 @@ export default class CartModuleService<
return cart
}
async list(
// @ts-expect-error
async listCarts(
filters?: any,
config?: FindConfig<any> | undefined,
sharedContext?: Context | undefined
@@ -214,7 +206,7 @@ export default class CartModuleService<
config ??= {}
const includeTotals = this.shouldIncludeTotals(config)
const carts = await super.list(filters, config, sharedContext)
const carts = await super.listCarts(filters, config, sharedContext)
if (includeTotals) {
carts.forEach((cart) => {
@@ -225,7 +217,8 @@ export default class CartModuleService<
return carts
}
async listAndCount(
// @ts-expect-error
async listAndCountCarts(
filters?: any,
config?: FindConfig<any> | undefined,
sharedContext?: Context | undefined
@@ -233,7 +226,7 @@ export default class CartModuleService<
config ??= {}
const includeTotals = this.shouldIncludeTotals(config)
const [carts, count] = await super.listAndCount(
const [carts, count] = await super.listAndCountCarts(
filters,
config,
sharedContext
@@ -248,26 +241,27 @@ export default class CartModuleService<
return [carts, count]
}
async create(
// @ts-expect-error
async createCarts(
data: CartTypes.CreateCartDTO[],
sharedContext?: Context
): Promise<CartTypes.CartDTO[]>
async create(
async createCarts(
data: CartTypes.CreateCartDTO,
sharedContext?: Context
): Promise<CartTypes.CartDTO>
@InjectManager("baseRepository_")
async create(
async createCarts(
data: CartTypes.CreateCartDTO[] | CartTypes.CreateCartDTO,
@MedusaContext() sharedContext: Context = {}
): Promise<CartTypes.CartDTO[] | CartTypes.CartDTO> {
const input = Array.isArray(data) ? data : [data]
const carts = await this.create_(input, sharedContext)
const carts = await this.createCarts_(input, sharedContext)
const result = await this.list(
const result = await this.listCarts(
{ id: carts.map((p) => p!.id) },
{
relations: ["shipping_address", "billing_address"],
@@ -281,7 +275,7 @@ export default class CartModuleService<
}
@InjectTransactionManager("baseRepository_")
protected async create_(
protected async createCarts_(
data: CartTypes.CreateCartDTO[],
@MedusaContext() sharedContext: Context = {}
) {
@@ -311,20 +305,23 @@ export default class CartModuleService<
return createdCarts
}
async update(data: CartTypes.UpdateCartDTO[]): Promise<CartTypes.CartDTO[]>
async update(
// @ts-expect-error
async updateCarts(
data: CartTypes.UpdateCartDTO[]
): Promise<CartTypes.CartDTO[]>
async updateCarts(
cartId: string,
data: CartTypes.UpdateCartDataDTO,
sharedContext?: Context
): Promise<CartTypes.CartDTO>
async update(
async updateCarts(
selector: Partial<CartTypes.CartDTO>,
data: CartTypes.UpdateCartDataDTO,
sharedContext?: Context
): Promise<CartTypes.CartDTO[]>
@InjectManager("baseRepository_")
async update(
async updateCarts(
dataOrIdOrSelector:
| CartTypes.UpdateCartDTO[]
| string
@@ -332,7 +329,11 @@ export default class CartModuleService<
data?: CartTypes.UpdateCartDataDTO,
@MedusaContext() sharedContext: Context = {}
): Promise<CartTypes.CartDTO[] | CartTypes.CartDTO> {
const result = await this.update_(dataOrIdOrSelector, data, sharedContext)
const result = await this.updateCarts_(
dataOrIdOrSelector,
data,
sharedContext
)
const serializedResult = await this.baseRepository_.serialize<
CartTypes.CartDTO[]
@@ -344,7 +345,7 @@ export default class CartModuleService<
}
@InjectTransactionManager("baseRepository_")
protected async update_(
protected async updateCarts_(
dataOrIdOrSelector:
| CartTypes.UpdateCartDTO[]
| string
@@ -428,7 +429,11 @@ export default class CartModuleService<
items: CartTypes.CreateLineItemDTO[],
@MedusaContext() sharedContext: Context = {}
): Promise<LineItem[]> {
const cart = await this.retrieve(cartId, { select: ["id"] }, sharedContext)
const cart = await this.retrieveCart(
cartId,
{ select: ["id"] },
sharedContext
)
const toUpdate: CreateLineItemDTO[] = items.map((item) => {
return {
@@ -666,7 +671,11 @@ export default class CartModuleService<
data: CartTypes.CreateShippingMethodForSingleCartDTO[],
@MedusaContext() sharedContext: Context = {}
): Promise<ShippingMethod[]> {
const cart = await this.retrieve(cartId, { select: ["id"] }, sharedContext)
const cart = await this.retrieveCart(
cartId,
{ select: ["id"] },
sharedContext
)
const methods = data.map((method) => {
return {
@@ -712,7 +721,7 @@ export default class CartModuleService<
): Promise<CartTypes.LineItemAdjustmentDTO[]> {
let addedAdjustments: LineItemAdjustment[] = []
if (isString(cartIdOrData)) {
const cart = await this.retrieve(
const cart = await this.retrieveCart(
cartIdOrData,
{ select: ["id"], relations: ["items"] },
sharedContext
@@ -758,7 +767,7 @@ export default class CartModuleService<
)[],
@MedusaContext() sharedContext: Context = {}
): Promise<CartTypes.LineItemAdjustmentDTO[]> {
const cart = await this.retrieve(
const cart = await this.retrieveCart(
cartId,
{ select: ["id"], relations: ["items.adjustments"] },
sharedContext
@@ -813,7 +822,7 @@ export default class CartModuleService<
)[],
@MedusaContext() sharedContext: Context = {}
): Promise<CartTypes.ShippingMethodAdjustmentDTO[]> {
const cart = await this.retrieve(
const cart = await this.retrieveCart(
cartId,
{ select: ["id"], relations: ["shipping_methods.adjustments"] },
sharedContext
@@ -887,7 +896,7 @@ export default class CartModuleService<
> {
let addedAdjustments: ShippingMethodAdjustment[] = []
if (isString(cartIdOrData)) {
const cart = await this.retrieve(
const cart = await this.retrieveCart(
cartIdOrData,
{ select: ["id"], relations: ["shipping_methods"] },
sharedContext
@@ -961,7 +970,7 @@ export default class CartModuleService<
let addedTaxLines: LineItemTaxLine[]
if (isString(cartIdOrData)) {
// existence check
await this.retrieve(cartIdOrData, { select: ["id"] }, sharedContext)
await this.retrieveCart(cartIdOrData, { select: ["id"] }, sharedContext)
const lines = Array.isArray(taxLines) ? taxLines : [taxLines]
@@ -1000,7 +1009,7 @@ export default class CartModuleService<
)[],
@MedusaContext() sharedContext: Context = {}
): Promise<CartTypes.LineItemTaxLineDTO[]> {
const cart = await this.retrieve(
const cart = await this.retrieveCart(
cartId,
{ select: ["id"], relations: ["items.tax_lines"] },
sharedContext
@@ -1077,7 +1086,7 @@ export default class CartModuleService<
let addedTaxLines: ShippingMethodTaxLine[]
if (isString(cartIdOrData)) {
// existence check
await this.retrieve(cartIdOrData, { select: ["id"] }, sharedContext)
await this.retrieveCart(cartIdOrData, { select: ["id"] }, sharedContext)
const lines = Array.isArray(taxLines) ? taxLines : [taxLines]
@@ -1116,7 +1125,7 @@ export default class CartModuleService<
)[],
@MedusaContext() sharedContext: Context = {}
): Promise<CartTypes.ShippingMethodTaxLineDTO[]> {
const cart = await this.retrieve(
const cart = await this.retrieveCart(
cartId,
{ select: ["id"], relations: ["shipping_methods.tax_lines"] },
sharedContext