chore(): Reorganize modules (#7210)

**What**
Move all modules to the modules directory
This commit is contained in:
Adrien de Peretti
2024-05-02 17:33:34 +02:00
committed by GitHub
parent 7a351eef09
commit 4eae25e1ef
870 changed files with 91 additions and 62 deletions
@@ -0,0 +1,27 @@
import { Modules } from "@medusajs/modules-sdk"
import { ModulesSdkUtils } from "@medusajs/utils"
import * as SalesChannelModels from "@models"
import { moduleDefinition } from "./module-definition"
export default moduleDefinition
const migrationScriptOptions = {
moduleName: Modules.SALES_CHANNEL,
models: SalesChannelModels,
pathToMigrations: __dirname + "/migrations",
}
export const runMigrations = ModulesSdkUtils.buildMigrationScript(
migrationScriptOptions
)
export const revertMigration = ModulesSdkUtils.buildRevertMigrationScript(
migrationScriptOptions
)
export * from "./initialize"
export * from "./types"
export * from "./loaders"
export * from "./models"
export * from "./services"
@@ -0,0 +1,34 @@
import {
ExternalModuleDeclaration,
InternalModuleDeclaration,
MedusaModule,
MODULE_PACKAGE_NAMES,
Modules,
} from "@medusajs/modules-sdk"
import { ModulesSdkTypes, ISalesChannelModuleService } 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<ISalesChannelModuleService> => {
const serviceKey = Modules.SALES_CHANNEL
const loaded = await MedusaModule.bootstrap<ISalesChannelModuleService>({
moduleKey: serviceKey,
defaultPath: MODULE_PACKAGE_NAMES[Modules.SALES_CHANNEL],
declaration: options as
| InternalModuleDeclaration
| ExternalModuleDeclaration,
injectedDependencies,
moduleExports: moduleDefinition,
})
return loaded[serviceKey]
}
@@ -0,0 +1,31 @@
import { Modules } from "@medusajs/modules-sdk"
import { ModuleJoinerConfig } from "@medusajs/types"
import { MapToConfig } from "@medusajs/utils"
import { SalesChannel } from "@models"
export const LinkableKeys = {
sales_channel_id: SalesChannel.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.SALES_CHANNEL,
primaryKeys: ["id"],
linkableKeys: LinkableKeys,
alias: [
{
name: ["sales_channel", "sales_channels"],
args: { entity: "SalesChannel" },
},
],
} as ModuleJoinerConfig
@@ -0,0 +1,37 @@
import {
InternalModuleDeclaration,
LoaderOptions,
Modules,
} from "@medusajs/modules-sdk"
import { ModulesSdkTypes } from "@medusajs/types"
import { ModulesSdkUtils } from "@medusajs/utils"
import { EntitySchema } from "@mikro-orm/core"
import * as SalesChannelModels from "@models"
export default async (
{
options,
container,
logger,
}: LoaderOptions<
| ModulesSdkTypes.ModuleServiceInitializeOptions
| ModulesSdkTypes.ModuleServiceInitializeCustomDataLayerOptions
>,
moduleDeclaration?: InternalModuleDeclaration
): Promise<void> => {
const entities = Object.values(
SalesChannelModels
) as unknown as EntitySchema[]
const pathToMigrations = __dirname + "/../migrations"
await ModulesSdkUtils.mikroOrmConnectionLoader({
moduleName: Modules.SALES_CHANNEL,
entities,
container,
options,
moduleDeclaration,
logger,
pathToMigrations,
})
}
@@ -0,0 +1,10 @@
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,
})
@@ -0,0 +1,2 @@
export * from "./connection"
export * from "./container"
@@ -0,0 +1,114 @@
{
"namespaces": [
"public"
],
"name": "public",
"tables": [
{
"columns": {
"id": {
"name": "id",
"type": "text",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": false,
"mappedType": "text"
},
"name": {
"name": "name",
"type": "text",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": false,
"mappedType": "text"
},
"description": {
"name": "description",
"type": "text",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": true,
"mappedType": "text"
},
"is_disabled": {
"name": "is_disabled",
"type": "boolean",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": false,
"default": "false",
"mappedType": "boolean"
},
"metadata": {
"name": "metadata",
"type": "jsonb",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": true,
"mappedType": "json"
},
"created_at": {
"name": "created_at",
"type": "timestamptz",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": false,
"length": 6,
"default": "now()",
"mappedType": "datetime"
},
"updated_at": {
"name": "updated_at",
"type": "timestamptz",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": false,
"length": 6,
"default": "now()",
"mappedType": "datetime"
},
"deleted_at": {
"name": "deleted_at",
"type": "timestamptz",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": true,
"length": 6,
"mappedType": "datetime"
}
},
"name": "sales_channel",
"schema": "public",
"indexes": [
{
"columnNames": [
"deleted_at"
],
"composite": false,
"keyName": "IDX_sales_channel_deleted_at",
"primary": false,
"unique": false
},
{
"keyName": "sales_channel_pkey",
"columnNames": [
"id"
],
"composite": false,
"primary": true,
"unique": true
}
],
"checks": [],
"foreignKeys": {}
}
]
}
@@ -0,0 +1,12 @@
import { Migration } from "@mikro-orm/migrations"
export class Migration20240115152146 extends Migration {
async up(): Promise<void> {
this.addSql(
'create table if not exists "sales_channel" ("id" text not null, "name" text not null, "description" text null, "is_disabled" boolean not null default false, "metadata" jsonb NULL, "created_at" timestamptz not null default now(), "updated_at" timestamptz not null default now(), "deleted_at" timestamptz null, constraint "sales_channel_pkey" primary key ("id"));'
)
this.addSql(
'create index "IDX_sales_channel_deleted_at" on "sales_channel" ("deleted_at");'
)
}
}
@@ -0,0 +1 @@
export { default as SalesChannel } from "./sales-channel"
@@ -0,0 +1,67 @@
import { DALUtils, Searchable, generateEntityId } from "@medusajs/utils"
import { DAL } from "@medusajs/types"
import {
BeforeCreate,
Entity,
Filter,
Index,
OnInit,
OptionalProps,
PrimaryKey,
Property,
} from "@mikro-orm/core"
type SalesChannelOptionalProps = "is_disabled" | DAL.EntityDateColumns
@Entity()
@Filter(DALUtils.mikroOrmSoftDeletableFilterOptions)
export default class SalesChannel {
[OptionalProps]?: SalesChannelOptionalProps
@PrimaryKey({ columnType: "text" })
id!: string
@Searchable()
@Property({ columnType: "text" })
name!: string
@Searchable()
@Property({ columnType: "text", nullable: true })
description: string | null = null
@Property({ columnType: "boolean", default: false })
is_disabled = false
@Property({
onCreate: () => new Date(),
columnType: "timestamptz",
defaultRaw: "now()",
})
created_at: Date
@Property({ columnType: "jsonb", nullable: true })
metadata: Record<string, unknown> | null = null
@Property({
onCreate: () => new Date(),
onUpdate: () => new Date(),
columnType: "timestamptz",
defaultRaw: "now()",
})
updated_at: Date
@Index({ name: "IDX_sales_channel_deleted_at" })
@Property({ columnType: "timestamptz", nullable: true })
deleted_at: Date | null = null
@BeforeCreate()
onCreate() {
this.id = generateEntityId(this.id, "sc")
}
@OnInit()
onInit() {
this.id = generateEntityId(this.id, "sc")
}
}
@@ -0,0 +1,13 @@
import { ModuleExports } from "@medusajs/types"
import { SalesChannelModuleService } from "@services"
import loadConnection from "./loaders/connection"
import loadContainer from "./loaders/container"
const service = SalesChannelModuleService
const loaders = [loadContainer, loadConnection] as any
export const moduleDefinition: ModuleExports = {
service,
loaders,
}
@@ -0,0 +1 @@
export { MikroOrmBaseRepository as BaseRepository } from "@medusajs/utils"
@@ -0,0 +1,31 @@
#!/usr/bin/env node
import { ModulesSdkUtils } from "@medusajs/utils"
import { Modules } from "@medusajs/modules-sdk"
import * as ProductModels from "@models"
import { createSalesChannels } from "../seed-utils"
import { EOL } from "os"
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-product-seed <filePath>`
)
}
const run = ModulesSdkUtils.buildSeedScript({
moduleName: Modules.PRODUCT,
models: ProductModels,
pathToMigrations: __dirname + "/../../migrations",
seedHandler: async ({ manager, data }) => {
const { salesChannelData } = data
await createSalesChannels(manager, salesChannelData)
},
})
await run({ path })
})()
@@ -0,0 +1,16 @@
import { SalesChannel } from "@models"
import { RequiredEntityData } from "@mikro-orm/core"
import { SqlEntityManager } from "@mikro-orm/postgresql"
export async function createSalesChannels(
manager: SqlEntityManager,
data: RequiredEntityData<SalesChannel>[]
) {
const channels = data.map((channel) => {
return manager.create(SalesChannel, channel)
})
await manager.persistAndFlush(channels)
return channels
}
@@ -0,0 +1,11 @@
import { asValue } from "awilix"
export const salesChannelRepositoryMock = {
salesChannelRepository: asValue({
find: jest.fn().mockImplementation(async ({ where: { code } }) => {
return [{}]
}),
findAndCount: jest.fn().mockResolvedValue([[], 0]),
getFreshManager: jest.fn().mockResolvedValue({}),
}),
}
@@ -0,0 +1,47 @@
import { createMedusaContainer } from "@medusajs/utils"
import { asValue } from "awilix"
import ContainerLoader from "../../loaders/container"
import { salesChannelRepositoryMock } from "../__fixtures__/sales-channel"
describe("Sales channel service", function () {
let container
beforeEach(async function () {
jest.clearAllMocks()
container = createMedusaContainer()
container.register("manager", asValue({}))
await ContainerLoader({ container })
container.register(salesChannelRepositoryMock)
})
it("should list sales channels with filters and relations", async function () {
const salesChannelRepository = container.resolve("salesChannelRepository")
const salesChannelService = container.resolve("salesChannelService")
const config = {
select: ["id", "name"],
}
await salesChannelService.list({}, config)
expect(salesChannelRepository.find).toHaveBeenCalledWith(
{
where: {},
options: {
fields: ["id", "name"],
limit: 15,
offset: 0,
orderBy: {
id: "ASC",
},
withDeleted: undefined,
populate: [],
},
},
expect.any(Object)
)
})
})
@@ -0,0 +1 @@
export { default as SalesChannelModuleService } from "./sales-channel-module"
@@ -0,0 +1,175 @@
import {
Context,
CreateSalesChannelDTO,
DAL,
FilterableSalesChannelProps,
InternalModuleDeclaration,
ISalesChannelModuleService,
ModuleJoinerConfig,
ModulesSdkTypes,
SalesChannelDTO,
UpdateSalesChannelDTO,
} from "@medusajs/types"
import {
InjectManager,
InjectTransactionManager,
isString,
MedusaContext,
ModulesSdkUtils,
promiseAll,
} from "@medusajs/utils"
import { SalesChannel } from "@models"
import { UpsertSalesChannelDTO } from "@medusajs/types"
import { UpdateSalesChanneInput } from "@types"
import { entityNameToLinkableKeysMap, joinerConfig } from "../joiner-config"
type InjectedDependencies = {
baseRepository: DAL.RepositoryService
salesChannelService: ModulesSdkTypes.InternalModuleService<any>
}
export default class SalesChannelModuleService<
TEntity extends SalesChannel = SalesChannel
>
extends ModulesSdkUtils.abstractModuleServiceFactory<
InjectedDependencies,
SalesChannelDTO,
{}
>(SalesChannel, [], entityNameToLinkableKeysMap)
implements ISalesChannelModuleService
{
protected baseRepository_: DAL.RepositoryService
protected readonly salesChannelService_: ModulesSdkTypes.InternalModuleService<TEntity>
constructor(
{ baseRepository, salesChannelService }: InjectedDependencies,
protected readonly moduleDeclaration: InternalModuleDeclaration
) {
// @ts-ignore
super(...arguments)
this.baseRepository_ = baseRepository
this.salesChannelService_ = salesChannelService
}
__joinerConfig(): ModuleJoinerConfig {
return joinerConfig
}
async create(
data: CreateSalesChannelDTO[],
sharedContext?: Context
): Promise<SalesChannelDTO[]>
async create(
data: CreateSalesChannelDTO,
sharedContext?: Context
): Promise<SalesChannelDTO>
@InjectManager("baseRepository_")
async create(
data: CreateSalesChannelDTO | CreateSalesChannelDTO[],
@MedusaContext() sharedContext: Context = {}
): Promise<SalesChannelDTO | SalesChannelDTO[]> {
const input = Array.isArray(data) ? data : [data]
const result = await this.create_(input, sharedContext)
return await this.baseRepository_.serialize<SalesChannelDTO[]>(
Array.isArray(data) ? result : result[0],
{
populate: true,
}
)
}
@InjectTransactionManager("baseRepository_")
async create_(
data: CreateSalesChannelDTO[],
@MedusaContext() sharedContext: Context
): Promise<SalesChannel[]> {
return await this.salesChannelService_.create(data, sharedContext)
}
async update(
id: string,
data: UpdateSalesChannelDTO,
sharedContext?: Context
): Promise<SalesChannelDTO>
async update(
selector: FilterableSalesChannelProps,
data: UpdateSalesChannelDTO,
sharedContext?: Context
): Promise<SalesChannelDTO[]>
@InjectManager("baseRepository_")
async update(
idOrSelector: string | FilterableSalesChannelProps,
data: UpdateSalesChannelDTO | UpdateSalesChannelDTO[],
@MedusaContext() sharedContext: Context = {}
): Promise<SalesChannelDTO | SalesChannelDTO[]> {
let normalizedInput: UpdateSalesChanneInput[] = []
if (isString(idOrSelector)) {
normalizedInput = [{ id: idOrSelector, ...data }]
} else {
const channels = await this.salesChannelService_.list(
idOrSelector,
{},
sharedContext
)
normalizedInput = channels.map((channel) => ({
id: channel.id,
...data,
}))
}
const result = await this.update_(normalizedInput, sharedContext)
return await this.baseRepository_.serialize<SalesChannelDTO[]>(
Array.isArray(data) ? result : result[0],
{
populate: true,
}
)
}
@InjectTransactionManager("baseRepository_")
async update_(data: UpdateSalesChannelDTO[], sharedContext: Context) {
return await this.salesChannelService_.update(data, sharedContext)
}
async upsert(
data: UpsertSalesChannelDTO[],
sharedContext?: Context
): Promise<SalesChannelDTO[]>
async upsert(
data: UpsertSalesChannelDTO,
sharedContext?: Context
): Promise<SalesChannelDTO>
@InjectTransactionManager("baseRepository_")
async upsert(
data: UpsertSalesChannelDTO | UpsertSalesChannelDTO[],
@MedusaContext() sharedContext: Context = {}
): Promise<SalesChannelDTO | SalesChannelDTO[]> {
const input = Array.isArray(data) ? data : [data]
const forUpdate = input.filter(
(channel): channel is UpdateSalesChannelDTO => !!channel.id
)
const forCreate = input.filter(
(channel): channel is CreateSalesChannelDTO => !channel.id
)
const operations: Promise<SalesChannel[]>[] = []
if (forCreate.length) {
operations.push(this.create_(forCreate, sharedContext))
}
if (forUpdate.length) {
operations.push(this.update_(forUpdate, sharedContext))
}
const result = (await promiseAll(operations)).flat()
return await this.baseRepository_.serialize<
SalesChannelDTO[] | SalesChannelDTO
>(Array.isArray(data) ? result : result[0])
}
}
@@ -0,0 +1,7 @@
import { Logger, UpdateSalesChannelDTO } from "@medusajs/types"
export type InitializeModuleInjectableDependencies = {
logger?: Logger
}
export type UpdateSalesChanneInput = UpdateSalesChannelDTO & { id: string }