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

View File

@@ -0,0 +1,14 @@
import { moduleDefinition } from "./module-definition"
import { initializeFactory, Modules } from "@medusajs/modules-sdk"
export * from "./types"
export * from "./models"
export * from "./services"
export const initialize = initializeFactory({
moduleName: Modules.CURRENCY,
moduleDefinition,
})
export const runMigrations = moduleDefinition.runMigrations
export const revertMigration = moduleDefinition.revertMigration
export default moduleDefinition

View File

@@ -0,0 +1,33 @@
import { Modules } from "@medusajs/modules-sdk"
import { ModuleJoinerConfig } from "@medusajs/types"
import { MapToConfig } from "@medusajs/utils"
import Currency from "./models/currency"
export const LinkableKeys: Record<string, string> = {
code: Currency.name,
currency_code: Currency.name,
default_currency_code: Currency.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.CURRENCY,
primaryKeys: ["code"],
linkableKeys: LinkableKeys,
alias: [
{
name: ["currency", "currencies"],
args: { entity: Currency.name },
},
],
} as ModuleJoinerConfig

View File

@@ -0,0 +1,33 @@
import { ModuleRegistrationName } from "@medusajs/modules-sdk"
import { ModulesSdkTypes, LoaderOptions, Logger } from "@medusajs/types"
import { ContainerRegistrationKeys, defaultCurrencies } from "@medusajs/utils"
import { Currency } from "@models"
export default async ({
container,
options,
}: LoaderOptions<
| ModulesSdkTypes.ModuleServiceInitializeOptions
| ModulesSdkTypes.ModuleServiceInitializeCustomDataLayerOptions
>): Promise<void> => {
// TODO: Add default logger to the container when running tests
const logger =
container.resolve<Logger>(ContainerRegistrationKeys.LOGGER) ?? console
const {
currencyService_,
}: { currencyService_: ModulesSdkTypes.InternalModuleService<Currency> } =
container.resolve(ModuleRegistrationName.CURRENCY)
try {
const normalizedCurrencies = Object.values(defaultCurrencies).map((c) => ({
...c,
code: c.code.toLowerCase(),
}))
const resp = await currencyService_.upsert(normalizedCurrencies)
logger.info(`Loaded ${resp.length} currencies`)
} catch (error) {
logger.warn(
`Failed to load currencies, skipping loader. Original error: ${error.message}`
)
}
}

View File

@@ -0,0 +1,110 @@
{
"namespaces": ["public"],
"name": "public",
"tables": [
{
"columns": {
"code": {
"name": "code",
"type": "text",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": false,
"mappedType": "text"
},
"symbol": {
"name": "symbol",
"type": "text",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": false,
"mappedType": "text"
},
"symbol_native": {
"name": "symbol_native",
"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"
},
"decimal_digits": {
"name": "decimal_digits",
"type": "int",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": false,
"default": "0",
"mappedType": "integer"
},
"rounding": {
"name": "rounding",
"type": "numeric",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": false,
"default": "0",
"mappedType": "decimal"
},
"raw_rounding": {
"name": "raw_rounding",
"type": "jsonb",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": false,
"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"
}
},
"name": "currency",
"schema": "public",
"indexes": [
{
"keyName": "currency_pkey",
"columnNames": ["code"],
"composite": false,
"primary": true,
"unique": true
}
],
"checks": [],
"foreignKeys": {}
}
]
}

View File

@@ -0,0 +1,28 @@
import { Migration } from "@mikro-orm/migrations"
export class InitialSetup20240228133303 extends Migration {
async up(): Promise<void> {
this.addSql(`
create table if not exists "currency"
(
"code" text not null,
"symbol" text not null,
"symbol_native" text not null,
"decimal_digits" int not null default 0,
"rounding" numeric not null default 0,
"raw_rounding" jsonb not null,
"name" text not null,
"created_at" timestamptz NOT NULL DEFAULT now(),
"updated_at" timestamptz NOT NULL DEFAULT now(),
constraint "currency_pkey" primary key ("code")
);
ALTER TABLE "currency" ADD COLUMN IF NOT EXISTS "created_at" TIMESTAMPTZ NOT NULL DEFAULT now();
ALTER TABLE "currency" ADD COLUMN IF NOT EXISTS "updated_at" TIMESTAMPTZ NULL DEFAULT now();
ALTER TABLE "currency" ADD COLUMN IF NOT EXISTS "decimal_digits" int not null default 0;
ALTER TABLE "currency" ADD COLUMN IF NOT EXISTS "rounding" numeric not null default 0;
ALTER TABLE "currency" ADD COLUMN IF NOT EXISTS "raw_rounding" jsonb;
`)
}
}

View File

@@ -0,0 +1,50 @@
import { BigNumberRawValue } from "@medusajs/types"
import {
BigNumber,
MikroOrmBigNumberProperty,
Searchable,
} from "@medusajs/utils"
import { Entity, PrimaryKey, Property } from "@mikro-orm/core"
@Entity({ tableName: "currency" })
class Currency {
@Searchable()
@PrimaryKey({ columnType: "text" })
code!: string
@Property({ columnType: "text" })
symbol: string
@Property({ columnType: "text" })
symbol_native: string
@Searchable()
@Property({ columnType: "text" })
name: string
@Property({ columnType: "int", default: 0 })
decimal_digits: number
@MikroOrmBigNumberProperty({ default: 0 })
rounding: BigNumber | number
@Property({ columnType: "jsonb" })
raw_rounding: BigNumberRawValue
@Property({
onCreate: () => new Date(),
columnType: "timestamptz",
defaultRaw: "now()",
})
created_at: Date
@Property({
onCreate: () => new Date(),
onUpdate: () => new Date(),
columnType: "timestamptz",
defaultRaw: "now()",
})
updated_at: Date
}
export default Currency

View File

@@ -0,0 +1 @@
export { default as Currency } from "./currency"

View File

@@ -0,0 +1,45 @@
import { ModuleExports } from "@medusajs/types"
import * as ModuleServices from "@services"
import { CurrencyModuleService } from "@services"
import { Modules } from "@medusajs/modules-sdk"
import * as Models from "@models"
import * as ModuleModels from "@models"
import { ModulesSdkUtils } from "@medusajs/utils"
import * as ModuleRepositories from "@repositories"
import initialDataLoader from "./loaders/initial-data"
const migrationScriptOptions = {
moduleName: Modules.CURRENCY,
models: Models,
pathToMigrations: __dirname + "/migrations",
}
const runMigrations = ModulesSdkUtils.buildMigrationScript(
migrationScriptOptions
)
const revertMigration = ModulesSdkUtils.buildRevertMigrationScript(
migrationScriptOptions
)
const containerLoader = ModulesSdkUtils.moduleContainerLoaderFactory({
moduleModels: ModuleModels,
moduleRepositories: ModuleRepositories,
moduleServices: ModuleServices,
})
const connectionLoader = ModulesSdkUtils.mikroOrmConnectionLoaderFactory({
moduleName: Modules.CURRENCY,
moduleModels: Object.values(Models),
migrationsPath: __dirname + "/migrations",
})
const service = CurrencyModuleService
const loaders = [containerLoader, connectionLoader, initialDataLoader] as any
export const moduleDefinition: ModuleExports = {
service,
loaders,
revertMigration,
runMigrations,
}

View File

@@ -0,0 +1 @@
export { MikroOrmBaseRepository as BaseRepository } from "@medusajs/utils"

View File

@@ -0,0 +1,29 @@
#!/usr/bin/env node
import { ModulesSdkUtils } from "@medusajs/utils"
import { Modules } from "@medusajs/modules-sdk"
import * as Models from "@models"
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-currency-seed <filePath>`
)
}
const run = ModulesSdkUtils.buildSeedScript({
moduleName: Modules.CURRENCY,
models: Models,
pathToMigrations: __dirname + "/../../migrations",
seedHandler: async ({ manager, data }) => {
// TODO: Add seed logic
},
})
await run({ path })
})()

View File

@@ -0,0 +1,5 @@
describe("noop", function () {
it("should run", function () {
expect(true).toBe(true)
})
})

View File

@@ -0,0 +1,131 @@
import {
DAL,
InternalModuleDeclaration,
ModuleJoinerConfig,
ModulesSdkTypes,
ICurrencyModuleService,
CurrencyTypes,
Context,
FindConfig,
FilterableCurrencyProps,
BaseFilterable,
} from "@medusajs/types"
import { ModulesSdkUtils } from "@medusajs/utils"
import { Currency } from "@models"
import { entityNameToLinkableKeysMap, joinerConfig } from "../joiner-config"
const generateMethodForModels = []
type InjectedDependencies = {
baseRepository: DAL.RepositoryService
currencyService: ModulesSdkTypes.InternalModuleService<any>
}
export default class CurrencyModuleService<TEntity extends Currency = Currency>
extends ModulesSdkUtils.abstractModuleServiceFactory<
InjectedDependencies,
CurrencyTypes.CurrencyDTO,
{
Currency: { dto: CurrencyTypes.CurrencyDTO }
}
>(Currency, generateMethodForModels, entityNameToLinkableKeysMap)
implements ICurrencyModuleService
{
protected baseRepository_: DAL.RepositoryService
protected readonly currencyService_: ModulesSdkTypes.InternalModuleService<TEntity>
constructor(
{ baseRepository, currencyService }: InjectedDependencies,
protected readonly moduleDeclaration: InternalModuleDeclaration
) {
// @ts-ignore
super(...arguments)
this.baseRepository_ = baseRepository
this.currencyService_ = currencyService
}
__joinerConfig(): ModuleJoinerConfig {
return joinerConfig
}
retrieve(
code: string,
config?: FindConfig<CurrencyTypes.CurrencyDTO>,
sharedContext?: Context
): Promise<CurrencyTypes.CurrencyDTO> {
return this.currencyService_.retrieve(
code?.toLowerCase(),
config,
sharedContext
)
}
list(
filters?: FilterableCurrencyProps,
config?: FindConfig<CurrencyTypes.CurrencyDTO>,
sharedContext?: Context
): Promise<CurrencyTypes.CurrencyDTO[]> {
return this.currencyService_.list(
CurrencyModuleService.normalizeFilters(filters),
config,
sharedContext
)
}
listAndCount(
filters?: FilterableCurrencyProps,
config?: FindConfig<CurrencyTypes.CurrencyDTO>,
sharedContext?: Context
): Promise<[CurrencyTypes.CurrencyDTO[], number]> {
return this.currencyService_.listAndCount(
CurrencyModuleService.normalizeFilters(filters),
config,
sharedContext
)
}
protected static normalizeFilters(
filters: FilterableCurrencyProps | undefined
): FilterableCurrencyProps | undefined {
return normalizeFilterable<
CurrencyTypes.CurrencyDTO,
FilterableCurrencyProps
>(filters, (fieldName, value) => {
if (fieldName === "code" && !!value) {
return value.toLowerCase()
}
return value
})
}
}
// TODO: Move normalizer support to `buildQuery` so we don't even need to override the list/retrieve methods just for normalization
const normalizeFilterable = <TModel, TFilter extends BaseFilterable<TFilter>>(
filters: TFilter | undefined,
normalizer: (fieldName: keyof TModel, value: any) => any
): TFilter | undefined => {
if (!filters) {
return filters
}
const normalizedFilters = {} as TFilter
for (const key in filters) {
if (key === "$and" || key === "$or") {
normalizedFilters[key] = (filters[key] as any).map((filter) =>
normalizeFilterable(filter, normalizer)
)
} else if (filters[key] !== undefined) {
if (Array.isArray(filters[key])) {
normalizedFilters[key] = (filters[key] as any).map((val) =>
normalizer(key as any, val)
)
} else {
normalizedFilters[key] = normalizer(key as any, filters[key])
}
}
}
return normalizedFilters
}

View File

@@ -0,0 +1 @@
export { default as CurrencyModuleService } from "./currency-module-service"

View File

@@ -0,0 +1,6 @@
import { IEventBusModuleService, Logger } from "@medusajs/types"
export type InitializeModuleInjectableDependencies = {
logger?: Logger
eventBusService?: IEventBusModuleService
}