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:
authored and GitHub committed 2024-06-19 13:02:16 +00:00
1 parent 2895ccfba8
commit 48963f55ef
533 files changed
+6469 -9769

No files matched your search

@@ -1,15 +1,12 @@
import { Modules } from "@medusajs/modules-sdk"
import { IRegionModuleService } from "@medusajs/types"
import { moduleIntegrationTestRunner, SuiteOptions } from "medusa-test-utils"
import { moduleIntegrationTestRunner } from "medusa-test-utils"
jest.setTimeout(30000)
moduleIntegrationTestRunner({
moduleIntegrationTestRunner<IRegionModuleService>({
moduleName: Modules.REGION,
testSuite: ({
MikroOrmWrapper,
service,
}: SuiteOptions<IRegionModuleService>) => {
testSuite: ({ service }) => {
describe("Region Module Service", () => {
it("should create countries on application start", async () => {
const countries = await service.listCountries({}, { take: null })
@@ -17,7 +14,7 @@ moduleIntegrationTestRunner({
})
it("should create and list a region", async () => {
const createdRegion = await service.create({
const createdRegion = await service.createRegions({
name: "Europe",
currency_code: "EUR",
automatic_taxes: false,
@@ -33,7 +30,7 @@ moduleIntegrationTestRunner({
})
)
const region = await service.retrieve(createdRegion.id, {
const region = await service.retrieveRegion(createdRegion.id, {
relations: ["countries"],
})
@@ -48,13 +45,13 @@ moduleIntegrationTestRunner({
})
it("should create a region with countries", async () => {
const createdRegion = await service.create({
const createdRegion = await service.createRegions({
name: "North America",
currency_code: "USD",
countries: ["us", "ca"],
})
const region = await service.retrieve(createdRegion.id, {
const region = await service.retrieveRegion(createdRegion.id, {
relations: ["countries"],
})
@@ -80,7 +77,7 @@ moduleIntegrationTestRunner({
it("should throw when country doesn't exist", async () => {
await expect(
service.create({
service.createRegions({
name: "North America",
currency_code: "USD",
countries: ["neverland"],
@@ -89,14 +86,14 @@ moduleIntegrationTestRunner({
})
it("should throw when country is already assigned to a region", async () => {
await service.create({
await service.createRegions({
name: "North America",
currency_code: "USD",
countries: ["us"],
})
await expect(
service.create({
service.createRegions({
name: "United States",
currency_code: "USD",
countries: ["us"],
@@ -108,7 +105,7 @@ moduleIntegrationTestRunner({
it("should throw when country is being assigned to multiple regions", async () => {
await expect(
service.create([
service.createRegions([
{
name: "United States",
currency_code: "USD",
@@ -126,13 +123,13 @@ moduleIntegrationTestRunner({
})
it("should upsert the region successfully", async () => {
const createdRegion = await service.upsert({
const createdRegion = await service.upsertRegions({
name: "North America",
currency_code: "USD",
countries: ["us", "ca"],
})
await service.upsert({
await service.upsertRegions({
id: createdRegion.id,
name: "Americas",
currency_code: "MXN",
@@ -140,7 +137,7 @@ moduleIntegrationTestRunner({
automatic_taxes: false,
})
const latestRegion = await service.retrieve(createdRegion.id, {
const latestRegion = await service.retrieveRegion(createdRegion.id, {
relations: ["countries"],
})
@@ -154,13 +151,13 @@ moduleIntegrationTestRunner({
})
it("should allow mixing create and update operations in upsert", async () => {
const createdRegion = await service.upsert({
const createdRegion = await service.upsertRegions({
name: "North America",
currency_code: "USD",
countries: ["us", "ca"],
})
const upserted = await service.upsert([
const upserted = await service.upsertRegions([
{
id: createdRegion.id,
name: "Americas",
@@ -190,29 +187,29 @@ moduleIntegrationTestRunner({
})
it("should update the region successfully", async () => {
const createdRegion = await service.create({
const createdRegion = await service.createRegions({
name: "North America",
currency_code: "USD",
countries: ["us", "ca"],
})
const shouldNotBeChangedRegion = await service.create({
const shouldNotBeChangedRegion = await service.createRegions({
name: "Europe",
currency_code: "EUR",
countries: ["hr"],
})
await service.update(createdRegion.id, {
await service.updateRegions(createdRegion.id, {
name: "Americas",
currency_code: "MXN",
countries: ["us", "mx"],
})
const latestRegion = await service.retrieve(createdRegion.id, {
const latestRegion = await service.retrieveRegion(createdRegion.id, {
relations: ["countries"],
})
const shouldNotBeChangedRegionAfter = await service.retrieve(
const shouldNotBeChangedRegionAfter = await service.retrieveRegion(
shouldNotBeChangedRegion.id,
{
relations: ["countries"],
@@ -235,18 +232,18 @@ moduleIntegrationTestRunner({
})
it("should update the region without affecting countries if countries are undefined", async () => {
const createdRegion = await service.create({
const createdRegion = await service.createRegions({
name: "North America",
currency_code: "USD",
countries: ["us", "ca"],
})
await service.update(createdRegion.id, {
await service.updateRegions(createdRegion.id, {
name: "Americas",
currency_code: "MXN",
})
const updatedRegion = await service.retrieve(createdRegion.id, {
const updatedRegion = await service.retrieveRegion(createdRegion.id, {
relations: ["countries"],
})
@@ -263,19 +260,19 @@ moduleIntegrationTestRunner({
})
it("should remove the countries in a region successfully", async () => {
const createdRegion = await service.create({
const createdRegion = await service.createRegions({
name: "North America",
currency_code: "USD",
countries: ["us", "ca"],
})
await service.update(createdRegion.id, {
await service.updateRegions(createdRegion.id, {
name: "Americas",
currency_code: "MXN",
countries: [],
})
const updatedRegion = await service.retrieve(createdRegion.id, {
const updatedRegion = await service.retrieveRegion(createdRegion.id, {
relations: ["countries"],
})
@@ -289,14 +286,14 @@ moduleIntegrationTestRunner({
})
it("should fail updating the region countries to non-existent ones", async () => {
const createdRegion = await service.create({
const createdRegion = await service.createRegions({
name: "North America",
currency_code: "USD",
countries: ["us", "ca"],
})
await expect(
service.update(
service.updateRegions(
{ id: createdRegion.id },
{
countries: ["us", "neverland"],
@@ -306,14 +303,14 @@ moduleIntegrationTestRunner({
})
it("should fail updating the region if there are duplicate countries", async () => {
const createdRegion = await service.create({
const createdRegion = await service.createRegions({
name: "North America",
currency_code: "USD",
countries: ["us", "ca"],
})
await expect(
service.update(
service.updateRegions(
{ id: createdRegion.id },
{
countries: ["us", "us"],
@@ -325,7 +322,7 @@ moduleIntegrationTestRunner({
})
it("should fail updating the region if country is already used", async () => {
const [createdRegion] = await service.create([
const [createdRegion] = await service.createRegions([
{
name: "North America",
currency_code: "USD",
@@ -339,7 +336,7 @@ moduleIntegrationTestRunner({
])
await expect(
service.update(
service.updateRegions(
{ id: createdRegion.id },
{
countries: ["us", "mx"],
@@ -351,21 +348,21 @@ moduleIntegrationTestRunner({
})
it("should unset the region ID on the country when deleting a region", async () => {
const createdRegion = await service.create({
const createdRegion = await service.createRegions({
name: "North America",
currency_code: "USD",
countries: ["us", "ca"],
})
await service.delete(createdRegion.id)
await service.deleteRegions(createdRegion.id)
const newRegion = await service.create({
const newRegion = await service.createRegions({
name: "North America",
currency_code: "USD",
countries: ["us", "ca"],
})
const resp = await service.retrieve(newRegion.id, {
const resp = await service.retrieveRegion(newRegion.id, {
relations: ["countries"],
})
+1 -4
View File
@@ -8,10 +8,7 @@
"dist"
],
"engines": {
"node": ">=16"
},
"bin": {
"medusa-region-seed": "dist/scripts/bin/run-seed.js"
"node": ">=20"
},
"repository": {
"type": "git",
+7 -1
View File
@@ -1,3 +1,9 @@
import { moduleDefinition } from "./module-definition"
import { ModuleExports } from "@medusajs/types"
import { RegionModuleService } from "./services"
import loadDefaults from "./loaders/defaults"
const moduleDefinition: ModuleExports = {
service: RegionModuleService,
loaders: [loadDefaults],
}
export default moduleDefinition
+8 -33
View File
@@ -1,36 +1,11 @@
import { Modules } from "@medusajs/modules-sdk"
import { ModuleJoinerConfig } from "@medusajs/types"
import { MapToConfig } from "@medusajs/utils"
import { Country, Region } from "@models"
import {
buildEntitiesNameToLinkableKeysMap,
defineJoinerConfig,
MapToConfig,
} from "@medusajs/utils"
export const LinkableKeys = {
region_id: Region.name,
country_iso: Country.name,
}
export const joinerConfig = defineJoinerConfig(Modules.REGION)
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.REGION,
primaryKeys: ["id"],
linkableKeys: LinkableKeys,
alias: [
{
name: ["region", "regions"],
args: { entity: Region.name },
},
{
name: ["country", "countries"],
args: { entity: Country.name, methodSuffix: "Countries" },
},
],
} as ModuleJoinerConfig
export const entityNameToLinkableKeysMap: MapToConfig =
buildEntitiesNameToLinkableKeysMap(joinerConfig.linkableKeys)
@@ -1,11 +0,0 @@
import { ModuleExports } from "@medusajs/types"
import { RegionModuleService } from "./services"
import loadDefaults from "./loaders/defaults"
const service = RegionModuleService
const loaders = [loadDefaults]
export const moduleDefinition: ModuleExports = {
service,
loaders,
}
@@ -1 +0,0 @@
export { MikroOrmBaseRepository as BaseRepository } from "@medusajs/utils"
@@ -1,31 +0,0 @@
#!/usr/bin/env node
import { Modules } from "@medusajs/modules-sdk"
import { ModulesSdkUtils } from "@medusajs/utils"
import * as RegionModels from "@models"
import { EOL } from "os"
import { createRegions } from "../seed-utils"
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-region-seed <filePath>`
)
}
const run = ModulesSdkUtils.buildSeedScript({
moduleName: Modules.REGION,
models: RegionModels,
pathToMigrations: __dirname + "/../../migrations",
seedHandler: async ({ manager, data }) => {
const { regionData } = data
await createRegions(manager, regionData)
},
})
await run({ path })
})()
@@ -1,16 +0,0 @@
import { RequiredEntityData } from "@mikro-orm/core"
import { SqlEntityManager } from "@mikro-orm/postgresql"
import { Region } from "@models"
export async function createRegions(
manager: SqlEntityManager,
data: RequiredEntityData<Region>[]
) {
const regions = data.map((region) => {
return manager.create(Region, region)
})
await manager.persistAndFlush(regions)
return regions
}
@@ -20,7 +20,7 @@ import {
isString,
MedusaContext,
MedusaError,
ModulesSdkUtils,
MedusaService,
promiseAll,
removeUndefined,
} from "@medusajs/utils"
@@ -36,25 +36,20 @@ type InjectedDependencies = {
countryService: ModulesSdkTypes.IMedusaInternalService<any>
}
const generateMethodForModels = { Country }
export default class RegionModuleService<
TRegion extends Region = Region,
TCountry extends Country = Country
>
extends ModulesSdkUtils.MedusaService<
RegionDTO,
{
Country: {
dto: RegionCountryDTO
}
export default class RegionModuleService
extends MedusaService<{
Region: {
dto: RegionDTO
}
>(Region, generateMethodForModels, entityNameToLinkableKeysMap)
Country: {
dto: RegionCountryDTO
}
}>({ Region, Country }, entityNameToLinkableKeysMap)
implements IRegionModuleService
{
protected baseRepository_: DAL.RepositoryService
protected readonly regionService_: ModulesSdkTypes.IMedusaInternalService<TRegion>
protected readonly countryService_: ModulesSdkTypes.IMedusaInternalService<TCountry>
protected readonly regionService_: ModulesSdkTypes.IMedusaInternalService<Region>
protected readonly countryService_: ModulesSdkTypes.IMedusaInternalService<Country>
constructor(
{ baseRepository, regionService, countryService }: InjectedDependencies,
@@ -71,22 +66,24 @@ export default class RegionModuleService<
return joinerConfig
}
async create(
//@ts-expect-error
async createRegions(
data: CreateRegionDTO[],
sharedContext?: Context
): Promise<RegionDTO[]>
async create(
async createRegions(
data: CreateRegionDTO,
sharedContext?: Context
): Promise<RegionDTO>
@InjectManager("baseRepository_")
async create(
async createRegions(
data: CreateRegionDTO | CreateRegionDTO[],
@MedusaContext() sharedContext: Context = {}
): Promise<RegionDTO | RegionDTO[]> {
const input = Array.isArray(data) ? data : [data]
const result = await this.create_(input, sharedContext)
const result = await this.createRegions_(input, sharedContext)
return await this.baseRepository_.serialize<RegionDTO[]>(
Array.isArray(data) ? result : result[0]
@@ -94,7 +91,7 @@ export default class RegionModuleService<
}
@InjectTransactionManager("baseRepository_")
async create_(
async createRegions_(
data: CreateRegionDTO[],
@MedusaContext() sharedContext: Context = {}
): Promise<Region[]> {
@@ -132,16 +129,17 @@ export default class RegionModuleService<
return result
}
async upsert(
async upsertRegions(
data: UpsertRegionDTO[],
sharedContext?: Context
): Promise<RegionDTO[]>
async upsert(
async upsertRegions(
data: UpsertRegionDTO,
sharedContext?: Context
): Promise<RegionDTO>
@InjectTransactionManager("baseRepository_")
async upsert(
async upsertRegions(
data: UpsertRegionDTO | UpsertRegionDTO[],
@MedusaContext() sharedContext: Context = {}
): Promise<RegionDTO | RegionDTO[]> {
@@ -156,10 +154,10 @@ export default class RegionModuleService<
const operations: Promise<Region[]>[] = []
if (forCreate.length) {
operations.push(this.create_(forCreate, sharedContext))
operations.push(this.createRegions_(forCreate, sharedContext))
}
if (forUpdate.length) {
operations.push(this.update_(forUpdate, sharedContext))
operations.push(this.updateRegions_(forUpdate, sharedContext))
}
const result = (await promiseAll(operations)).flat()
@@ -168,18 +166,20 @@ export default class RegionModuleService<
)
}
async update(
//@ts-expect-error
async updateRegions(
id: string,
data: UpdateRegionDTO,
sharedContext?: Context
): Promise<RegionDTO>
async update(
async updateRegions(
selector: FilterableRegionProps,
data: UpdateRegionDTO,
sharedContext?: Context
): Promise<RegionDTO[]>
@InjectManager("baseRepository_")
async update(
async updateRegions(
idOrSelector: string | FilterableRegionProps,
data: UpdateRegionDTO,
@MedusaContext() sharedContext: Context = {}
@@ -200,7 +200,10 @@ export default class RegionModuleService<
}))
}
const updateResult = await this.update_(normalizedInput, sharedContext)
const updateResult = await this.updateRegions_(
normalizedInput,
sharedContext
)
const regions = await this.baseRepository_.serialize<
RegionDTO[] | RegionDTO
@@ -210,7 +213,7 @@ export default class RegionModuleService<
}
@InjectTransactionManager("baseRepository_")
protected async update_(
protected async updateRegions_(
data: UpdateRegionInput[],
@MedusaContext() sharedContext: Context = {}
): Promise<Region[]> {
@@ -282,7 +285,7 @@ export default class RegionModuleService<
private async validateCountries(
countries: string[] | undefined,
sharedContext: Context
): Promise<TCountry[]> {
): Promise<Country[]> {
if (!countries?.length) {
return []
}
@@ -1,5 +1,4 @@
import { Logger, UpdateRegionDTO } from "@medusajs/types"
import { Country } from "@models"
export type InitializeModuleInjectableDependencies = {
logger?: Logger