chore(): Autoload module resources (#7291)

**What**
- automatically build and consume connection and container loader if not exported by the module
- therefore load the services and repositories automatically, including baseRepository
- automatically build run and revert migrations if not provided
- cleaup modules to remove extra unnecessary bits and pieces
- remove the `initializeFactory` in favor of using `medusaApp`

Should drastically improve the module building DX by removing a lot of boilerplate to handle by the user, that plus the base entity should simplify quite a lot the flow cc @shahednasser 

**Note**
I had to choose a way to identify connection and container loader from the exported loader from the module. I decided to go with named function `connectionLoader` and `containerLoader`, also, now the factories will return named function so if the user use the factories we are providing to build those loaders, the function will also be named and identified
This commit is contained in:
Adrien de Peretti
2024-05-13 12:12:36 +00:00
committed by GitHub
parent 728c5ee53c
commit 63623422fe
112 changed files with 520 additions and 2320 deletions
+1 -8
View File
@@ -1,14 +1,7 @@
import {
moduleDefinition,
revertMigration,
runMigrations,
} from "./module-definition"
import { moduleDefinition } from "./module-definition"
export default moduleDefinition
export { revertMigration, runMigrations }
export * from "./initialize"
// TODO: remove export from models and services
export * from "./models"
export * from "./services"
export * from "./types"
@@ -1,34 +0,0 @@
import {
ExternalModuleDeclaration,
InternalModuleDeclaration,
MedusaModule,
MODULE_PACKAGE_NAMES,
Modules,
} from "@medusajs/modules-sdk"
import { IProductModuleService, ModulesSdkTypes } from "@medusajs/types"
import { InitializeModuleInjectableDependencies } from "@types"
import { moduleDefinition } from "../module-definition"
export const initialize = async (
options?:
| ModulesSdkTypes.ModuleServiceInitializeOptions
| ModulesSdkTypes.ModuleServiceInitializeCustomDataLayerOptions
| ExternalModuleDeclaration
| InternalModuleDeclaration,
injectedDependencies?: InitializeModuleInjectableDependencies
): Promise<IProductModuleService> => {
const serviceKey = Modules.PRODUCT
const loaded = await MedusaModule.bootstrap<IProductModuleService>({
moduleKey: serviceKey,
defaultPath: MODULE_PACKAGE_NAMES[Modules.PRODUCT],
declaration: options as
| InternalModuleDeclaration
| ExternalModuleDeclaration,
injectedDependencies,
moduleExports: moduleDefinition,
})
return loaded[serviceKey]
}
@@ -1,30 +0,0 @@
import { InternalModuleDeclaration, LoaderOptions } from "@medusajs/modules-sdk"
import { ModulesSdkTypes } from "@medusajs/types"
import { ModulesSdkUtils } from "@medusajs/utils"
import { EntitySchema } from "@mikro-orm/core"
import * as ProductModels from "../models"
export default async (
{
options,
container,
logger,
}: LoaderOptions<
| ModulesSdkTypes.ModuleServiceInitializeOptions
| ModulesSdkTypes.ModuleServiceInitializeCustomDataLayerOptions
>,
moduleDeclaration?: InternalModuleDeclaration
): Promise<void> => {
const entities = Object.values(ProductModels) as unknown as EntitySchema[]
const pathToMigrations = __dirname + "/../migrations"
await ModulesSdkUtils.mikroOrmConnectionLoader({
moduleName: "product",
entities,
container,
options,
moduleDeclaration,
logger,
pathToMigrations,
})
}
@@ -1,10 +0,0 @@
import { ModulesSdkUtils } from "@medusajs/utils"
import * as ModuleModels from "@models"
import * as ModuleRepositories from "@repositories"
import * as ModuleServices from "@services"
export default ModulesSdkUtils.moduleContainerLoaderFactory({
moduleModels: ModuleModels,
moduleRepositories: ModuleRepositories,
moduleServices: ModuleServices,
})
@@ -1,2 +0,0 @@
export * from "./connection"
export * from "./container"
@@ -1,31 +1,8 @@
import { ModuleExports } from "@medusajs/types"
import { ProductModuleService } from "@services"
import loadConnection from "./loaders/connection"
import loadContainer from "./loaders/container"
import { Modules } from "@medusajs/modules-sdk"
import { ModulesSdkUtils } from "@medusajs/utils"
import * as ProductModels from "@models"
const migrationScriptOptions = {
moduleName: Modules.PRODUCT,
models: ProductModels,
pathToMigrations: __dirname + "/migrations",
}
export const runMigrations = ModulesSdkUtils.buildMigrationScript(
migrationScriptOptions
)
export const revertMigration = ModulesSdkUtils.buildRevertMigrationScript(
migrationScriptOptions
)
const service = ProductModuleService
const loaders = [loadContainer, loadConnection] as any
export const moduleDefinition: ModuleExports = {
service,
loaders,
runMigrations,
revertMigration,
}
@@ -1,3 +1,2 @@
export { MikroOrmBaseRepository as BaseRepository } from "@medusajs/utils"
export { ProductRepository } from "./product"
export { ProductCategoryRepository } from "./product-category"
@@ -1,17 +0,0 @@
import { asValue } from "awilix"
export const nonExistingProductId = "non-existing-id"
export const productRepositoryMock = {
productRepository: asValue({
find: jest.fn().mockImplementation(async ({ where: { id } }) => {
if (id === nonExistingProductId) {
return []
}
return [{}]
}),
findAndCount: jest.fn().mockResolvedValue([[], 0]),
getFreshManager: jest.fn().mockResolvedValue({}),
}),
}
@@ -0,0 +1 @@
it("noop", () => {})
@@ -1,227 +0,0 @@
import {
nonExistingProductId,
productRepositoryMock,
} from "../__fixtures__/product"
import { createMedusaContainer } from "@medusajs/utils"
import { asValue } from "awilix"
import ContainerLoader from "../../loaders/container"
describe("Product service", function () {
let container
beforeEach(async function () {
jest.clearAllMocks()
container = createMedusaContainer()
container.register("manager", asValue({}))
await ContainerLoader({ container })
container.register(productRepositoryMock)
})
it("should retrieve a product", async function () {
const productService = container.resolve("productService")
const productRepository = container.resolve("productRepository")
const productId = "existing-product"
await productService.retrieve(productId)
expect(productRepository.find).toHaveBeenCalledWith(
{
where: {
id: productId,
},
options: {
fields: undefined,
limit: undefined,
offset: 0,
populate: [],
withDeleted: undefined,
},
},
expect.any(Object)
)
})
it("should fail to retrieve a product", async function () {
const productService = container.resolve("productService")
const productRepository = container.resolve("productRepository")
const err = await productService
.retrieve(nonExistingProductId)
.catch((e) => e)
expect(productRepository.find).toHaveBeenCalledWith(
{
where: {
id: nonExistingProductId,
},
options: {
fields: undefined,
limit: undefined,
offset: 0,
populate: [],
withDeleted: undefined,
},
},
expect.any(Object)
)
expect(err.message).toBe(
`Product with id: ${nonExistingProductId} was not found`
)
})
it("should list products", async function () {
const productService = container.resolve("productService")
const productRepository = container.resolve("productRepository")
const filters = {}
const config = {
relations: [],
}
await productService.list(filters, config)
expect(productRepository.find).toHaveBeenCalledWith(
{
where: {},
options: {
fields: undefined,
limit: 15,
offset: 0,
orderBy: {
id: "ASC",
},
populate: [],
withDeleted: undefined,
},
},
expect.any(Object)
)
})
it("should list products with filters", async function () {
const productService = container.resolve("productService")
const productRepository = container.resolve("productRepository")
const filters = {
tags: {
value: {
$in: ["test"],
},
},
}
const config = {
relations: [],
}
await productService.list(filters, config)
expect(productRepository.find).toHaveBeenCalledWith(
{
where: {
tags: {
value: {
$in: ["test"],
},
},
},
options: {
fields: undefined,
limit: 15,
offset: 0,
orderBy: {
id: "ASC",
},
populate: [],
withDeleted: undefined,
},
},
expect.any(Object)
)
})
it("should list products with filters and relations", async function () {
const productService = container.resolve("productService")
const productRepository = container.resolve("productRepository")
const filters = {
tags: {
value: {
$in: ["test"],
},
},
}
const config = {
relations: ["tags"],
}
await productService.list(filters, config)
expect(productRepository.find).toHaveBeenCalledWith(
{
where: {
tags: {
value: {
$in: ["test"],
},
},
},
options: {
fields: undefined,
limit: 15,
offset: 0,
orderBy: {
id: "ASC",
},
withDeleted: undefined,
populate: ["tags"],
},
},
expect.any(Object)
)
})
it("should list and count the products with filters and relations", async function () {
const productService = container.resolve("productService")
const productRepository = container.resolve("productRepository")
const filters = {
tags: {
value: {
$in: ["test"],
},
},
}
const config = {
relations: ["tags"],
}
await productService.listAndCount(filters, config)
expect(productRepository.findAndCount).toHaveBeenCalledWith(
{
where: {
tags: {
value: {
$in: ["test"],
},
},
},
options: {
fields: undefined,
limit: 15,
offset: 0,
orderBy: {
id: "ASC",
},
withDeleted: undefined,
populate: ["tags"],
},
},
expect.any(Object)
)
})
})