feat: Region Module (basic CRUD) (#6315)
This commit is contained in:
1 parent
ede221d4f7
commit
823b98aaa1
49 files changed
+2716
-13
No files matched your search
@@ -0,0 +1,6 @@
|
||||
/dist
|
||||
node_modules
|
||||
.DS_store
|
||||
.env*
|
||||
.env
|
||||
*.sql
|
||||
@@ -0,0 +1 @@
|
||||
# Region Module
|
||||
@@ -0,0 +1,101 @@
|
||||
import { Modules } from "@medusajs/modules-sdk"
|
||||
import { IRegionModuleService } from "@medusajs/types"
|
||||
import { DefaultsUtils } from "@medusajs/utils"
|
||||
import { initModules } from "medusa-test-utils"
|
||||
import { MikroOrmWrapper } from "../utils"
|
||||
import { getInitModuleConfig } from "../utils/get-init-module-config"
|
||||
|
||||
jest.setTimeout(30000)
|
||||
|
||||
describe("Region Module Service", () => {
|
||||
let service: IRegionModuleService
|
||||
let shutdownFunc: () => Promise<void>
|
||||
|
||||
beforeEach(async () => {
|
||||
await MikroOrmWrapper.setupDatabase()
|
||||
|
||||
const initModulesConfig = getInitModuleConfig()
|
||||
const { medusaApp, shutdown } = await initModules(initModulesConfig)
|
||||
service = medusaApp.modules[Modules.REGION]
|
||||
|
||||
shutdownFunc = shutdown
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
await MikroOrmWrapper.clearDatabase()
|
||||
await shutdownFunc()
|
||||
})
|
||||
|
||||
it("should create countries and currencies on application start", async () => {
|
||||
const countries = await service.listCountries()
|
||||
const currencies = await service.listCurrencies()
|
||||
|
||||
expect(countries.length).toBeGreaterThan(0)
|
||||
expect(currencies.length).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it("should create countries added to default ones", async () => {
|
||||
const [, count] = await service.listAndCountCountries()
|
||||
const initialCountries = DefaultsUtils.defaultCountries.length
|
||||
|
||||
expect(count).toEqual(initialCountries)
|
||||
|
||||
DefaultsUtils.defaultCountries.push({
|
||||
name: "Dogecoin",
|
||||
alpha2: "DOGE",
|
||||
alpha3: "DOGE",
|
||||
numeric: "420",
|
||||
})
|
||||
|
||||
await service.createDefaultCountriesAndCurrencies()
|
||||
|
||||
const [, newCount] = await service.listAndCountCountries()
|
||||
expect(newCount).toEqual(initialCountries + 1)
|
||||
})
|
||||
|
||||
it("should create and list a region", async () => {
|
||||
const createdRegion = await service.create({
|
||||
name: "Europe",
|
||||
currency_code: "EUR",
|
||||
})
|
||||
|
||||
expect(createdRegion).toEqual(
|
||||
expect.objectContaining({
|
||||
id: createdRegion.id,
|
||||
name: "Europe",
|
||||
currency_code: "EUR",
|
||||
currency: expect.objectContaining({
|
||||
code: "eur",
|
||||
name: "Euro",
|
||||
}),
|
||||
countries: [],
|
||||
})
|
||||
)
|
||||
|
||||
const region = await service.retrieve(createdRegion.id, {
|
||||
relations: ["currency", "countries"],
|
||||
})
|
||||
|
||||
expect(region).toEqual(
|
||||
expect.objectContaining({
|
||||
id: region.id,
|
||||
name: "Europe",
|
||||
currency_code: "EUR",
|
||||
currency: expect.objectContaining({
|
||||
code: "eur",
|
||||
name: "Euro",
|
||||
}),
|
||||
countries: [],
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
it("should fail when currency does not exist", async () => {
|
||||
await expect(
|
||||
service.create({
|
||||
name: "Europe",
|
||||
currency_code: "DOGECOIN",
|
||||
})
|
||||
).rejects.toThrowError("Currency with code: DOGECOIN was not found")
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,6 @@
|
||||
if (typeof process.env.DB_TEMP_NAME === "undefined") {
|
||||
const tempName = parseInt(process.env.JEST_WORKER_ID || "1")
|
||||
process.env.DB_TEMP_NAME = `medusa-region-integration-${tempName}`
|
||||
}
|
||||
|
||||
process.env.MEDUSA_REGION_DB_SCHEMA = "public"
|
||||
@@ -0,0 +1,3 @@
|
||||
import { JestUtils } from "medusa-test-utils"
|
||||
|
||||
JestUtils.afterAllHookDropDatabase()
|
||||
@@ -0,0 +1,6 @@
|
||||
import { ModuleServiceInitializeOptions } from "@medusajs/types"
|
||||
|
||||
export const databaseOptions: ModuleServiceInitializeOptions["database"] = {
|
||||
schema: "public",
|
||||
clientUrl: "medusa-region-test",
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { TestDatabaseUtils } from "medusa-test-utils"
|
||||
|
||||
import * as RegionModels from "@models"
|
||||
|
||||
const pathToMigrations = "../../src/migrations"
|
||||
const mikroOrmEntities = RegionModels as unknown as any[]
|
||||
|
||||
export const MikroOrmWrapper = TestDatabaseUtils.getMikroOrmWrapper(
|
||||
mikroOrmEntities,
|
||||
pathToMigrations
|
||||
)
|
||||
|
||||
export const MikroOrmConfig = TestDatabaseUtils.getMikroOrmConfig(
|
||||
mikroOrmEntities,
|
||||
pathToMigrations
|
||||
)
|
||||
|
||||
export const DB_URL = TestDatabaseUtils.getDatabaseURL()
|
||||
@@ -0,0 +1,33 @@
|
||||
import { Modules, ModulesDefinition } from "@medusajs/modules-sdk"
|
||||
|
||||
import { DB_URL } from "./database"
|
||||
|
||||
export function getInitModuleConfig() {
|
||||
const moduleOptions = {
|
||||
defaultAdapterOptions: {
|
||||
database: {
|
||||
clientUrl: DB_URL,
|
||||
schema: process.env.MEDUSA_REGION_DB_SCHEMA,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
const injectedDependencies = {}
|
||||
|
||||
const modulesConfig_ = {
|
||||
[Modules.REGION]: {
|
||||
definition: ModulesDefinition[Modules.REGION],
|
||||
options: moduleOptions,
|
||||
},
|
||||
}
|
||||
|
||||
return {
|
||||
injectedDependencies,
|
||||
modulesConfig: modulesConfig_,
|
||||
databaseConfig: {
|
||||
clientUrl: DB_URL,
|
||||
schema: process.env.MEDUSA_REGION_DB_SCHEMA,
|
||||
},
|
||||
joinerConfig: [],
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
export * from "./config"
|
||||
export * from "./database"
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
module.exports = {
|
||||
moduleNameMapper: {
|
||||
"^@models": "<rootDir>/src/models",
|
||||
"^@services": "<rootDir>/src/services",
|
||||
"^@repositories": "<rootDir>/src/repositories",
|
||||
"^@types": "<rootDir>/src/types",
|
||||
},
|
||||
transform: {
|
||||
"^.+\\.[jt]s?$": [
|
||||
"ts-jest",
|
||||
{
|
||||
tsConfig: "tsconfig.spec.json",
|
||||
isolatedModules: true,
|
||||
},
|
||||
],
|
||||
},
|
||||
testEnvironment: `node`,
|
||||
moduleFileExtensions: [`js`, `ts`],
|
||||
modulePathIgnorePatterns: ["dist/"],
|
||||
setupFiles: ["<rootDir>/integration-tests/setup-env.js"],
|
||||
setupFilesAfterEnv: ["<rootDir>/integration-tests/setup.js"],
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import * as entities from "./src/models"
|
||||
|
||||
module.exports = {
|
||||
entities: Object.values(entities),
|
||||
schema: "public",
|
||||
clientUrl: "postgres://postgres@localhost/medusa-region",
|
||||
type: "postgresql",
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
{
|
||||
"name": "@medusajs/region",
|
||||
"version": "0.1.0",
|
||||
"description": "Medusa Region module",
|
||||
"main": "dist/index.js",
|
||||
"types": "dist/index.d.ts",
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=16"
|
||||
},
|
||||
"bin": {
|
||||
"medusa-region-seed": "dist/scripts/bin/run-seed.js"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/medusajs/medusa",
|
||||
"directory": "packages/region"
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"author": "Medusa",
|
||||
"license": "MIT",
|
||||
"scripts": {
|
||||
"watch": "tsc --build --watch",
|
||||
"watch:test": "tsc --build tsconfig.spec.json --watch",
|
||||
"prepublishOnly": "cross-env NODE_ENV=production tsc --build && tsc-alias -p tsconfig.json",
|
||||
"build": "rimraf dist && tsc --build && tsc-alias -p tsconfig.json",
|
||||
"test": "jest --runInBand --bail --forceExit -- src/**/__tests__/**/*.ts",
|
||||
"test:integration": "jest --runInBand --forceExit -- integration-tests/**/__tests__/**/*.ts",
|
||||
"migration:generate": " MIKRO_ORM_CLI=./mikro-orm.config.dev.ts mikro-orm migration:generate",
|
||||
"migration:initial": " MIKRO_ORM_CLI=./mikro-orm.config.dev.ts mikro-orm migration:create --initial",
|
||||
"migration:create": " MIKRO_ORM_CLI=./mikro-orm.config.dev.ts mikro-orm migration:create",
|
||||
"migration:up": " MIKRO_ORM_CLI=./mikro-orm.config.dev.ts mikro-orm migration:up",
|
||||
"orm:cache:clear": " MIKRO_ORM_CLI=./mikro-orm.config.dev.ts mikro-orm cache:clear"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@mikro-orm/cli": "5.9.7",
|
||||
"cross-env": "^5.2.1",
|
||||
"jest": "^29.6.3",
|
||||
"medusa-test-utils": "workspace:^",
|
||||
"rimraf": "^3.0.2",
|
||||
"ts-jest": "^29.1.1",
|
||||
"ts-node": "^10.9.1",
|
||||
"tsc-alias": "^1.8.6",
|
||||
"typescript": "^5.1.6"
|
||||
},
|
||||
"dependencies": {
|
||||
"@medusajs/modules-sdk": "^1.12.4",
|
||||
"@medusajs/types": "^1.11.8",
|
||||
"@medusajs/utils": "^1.11.1",
|
||||
"@mikro-orm/core": "5.9.7",
|
||||
"@mikro-orm/migrations": "5.9.7",
|
||||
"@mikro-orm/postgresql": "5.9.7",
|
||||
"awilix": "^8.0.0",
|
||||
"dotenv": "^16.1.4",
|
||||
"knex": "2.4.2"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { Modules } from "@medusajs/modules-sdk"
|
||||
import { ModulesSdkUtils } from "@medusajs/utils"
|
||||
|
||||
import * as RegionModels from "@models"
|
||||
|
||||
import { moduleDefinition } from "./module-definition"
|
||||
|
||||
export default moduleDefinition
|
||||
|
||||
const migrationScriptOptions = {
|
||||
moduleName: Modules.REGION,
|
||||
models: RegionModels,
|
||||
pathToMigrations: __dirname + "/migrations",
|
||||
}
|
||||
|
||||
export const runMigrations = ModulesSdkUtils.buildMigrationScript(
|
||||
migrationScriptOptions
|
||||
)
|
||||
export const revertMigration = ModulesSdkUtils.buildRevertMigrationScript(
|
||||
migrationScriptOptions
|
||||
)
|
||||
|
||||
export * from "./initialize"
|
||||
export * from "./loaders"
|
||||
export * from "./models"
|
||||
export * from "./services"
|
||||
export * from "./types"
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import {
|
||||
ExternalModuleDeclaration,
|
||||
InternalModuleDeclaration,
|
||||
MedusaModule,
|
||||
MODULE_PACKAGE_NAMES,
|
||||
Modules,
|
||||
} from "@medusajs/modules-sdk"
|
||||
import { IRegionModuleService, 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<IRegionModuleService> => {
|
||||
const serviceKey = Modules.REGION
|
||||
|
||||
const loaded = await MedusaModule.bootstrap<IRegionModuleService>({
|
||||
moduleKey: serviceKey,
|
||||
defaultPath: MODULE_PACKAGE_NAMES[Modules.REGION],
|
||||
declaration: options as
|
||||
| InternalModuleDeclaration
|
||||
| ExternalModuleDeclaration,
|
||||
injectedDependencies,
|
||||
moduleExports: moduleDefinition,
|
||||
})
|
||||
|
||||
return loaded[serviceKey]
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { Modules } from "@medusajs/modules-sdk"
|
||||
import { ModuleJoinerConfig } from "@medusajs/types"
|
||||
import { MapToConfig } from "@medusajs/utils"
|
||||
import { Country, Currency, Region } from "@models"
|
||||
|
||||
export const LinkableKeys = {
|
||||
region_id: Region.name,
|
||||
currency_code: Country.name,
|
||||
country_id: Region.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.REGION,
|
||||
primaryKeys: ["id"],
|
||||
linkableKeys: LinkableKeys,
|
||||
alias: [
|
||||
{
|
||||
name: ["region", "regions"],
|
||||
args: { entity: Region.name },
|
||||
},
|
||||
{
|
||||
name: ["currency", "currencies"],
|
||||
args: { entity: Currency.name },
|
||||
},
|
||||
{
|
||||
name: ["country", "countries"],
|
||||
args: { entity: Country.name },
|
||||
},
|
||||
],
|
||||
} as ModuleJoinerConfig
|
||||
@@ -0,0 +1,35 @@
|
||||
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 RegionModels from "@models"
|
||||
|
||||
export default async (
|
||||
{
|
||||
options,
|
||||
container,
|
||||
logger,
|
||||
}: LoaderOptions<
|
||||
| ModulesSdkTypes.ModuleServiceInitializeOptions
|
||||
| ModulesSdkTypes.ModuleServiceInitializeCustomDataLayerOptions
|
||||
>,
|
||||
moduleDeclaration?: InternalModuleDeclaration
|
||||
): Promise<void> => {
|
||||
const entities = Object.values(RegionModels) as unknown as EntitySchema[]
|
||||
const pathToMigrations = __dirname + "/../migrations"
|
||||
|
||||
await ModulesSdkUtils.mikroOrmConnectionLoader({
|
||||
moduleName: Modules.REGION,
|
||||
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,7 @@
|
||||
import { ModuleRegistrationName } from "@medusajs/modules-sdk"
|
||||
import { IRegionModuleService, LoaderOptions } from "@medusajs/types"
|
||||
|
||||
export default async ({ container }: LoaderOptions): Promise<void> => {
|
||||
const service: IRegionModuleService = container.resolve(ModuleRegistrationName.REGION)
|
||||
await service.createDefaultCountriesAndCurrencies()
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
export * from "./connection"
|
||||
export * from "./container"
|
||||
export * from "./defaults"
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import {
|
||||
BeforeCreate,
|
||||
Cascade,
|
||||
Entity,
|
||||
ManyToOne,
|
||||
OnInit,
|
||||
PrimaryKey,
|
||||
Property,
|
||||
} from "@mikro-orm/core"
|
||||
|
||||
import { generateEntityId } from "@medusajs/utils"
|
||||
import Region from "./region"
|
||||
|
||||
@Entity({ tableName: "region_country" })
|
||||
export default class Country {
|
||||
@PrimaryKey({ columnType: "text" })
|
||||
id: string
|
||||
|
||||
@Property({ columnType: "text" })
|
||||
iso_2: string
|
||||
|
||||
@Property({ columnType: "text" })
|
||||
iso_3: string
|
||||
|
||||
@Property({ columnType: "int" })
|
||||
num_code: number
|
||||
|
||||
@Property({ columnType: "text" })
|
||||
name: string
|
||||
|
||||
@Property({ columnType: "text" })
|
||||
display_name: string
|
||||
|
||||
@Property({ columnType: "text", nullable: true })
|
||||
region_id: string | null = null
|
||||
|
||||
@ManyToOne({
|
||||
entity: () => Region,
|
||||
onDelete: "cascade",
|
||||
index: "IDX_country_region_id",
|
||||
cascade: [Cascade.REMOVE, Cascade.PERSIST],
|
||||
})
|
||||
region: Region
|
||||
|
||||
@BeforeCreate()
|
||||
onCreate() {
|
||||
this.id = generateEntityId(this.id, "reg_ctry")
|
||||
}
|
||||
|
||||
@OnInit()
|
||||
onInit() {
|
||||
this.id = generateEntityId(this.id, "reg_ctry")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { generateEntityId } from "@medusajs/utils"
|
||||
import {
|
||||
BeforeCreate,
|
||||
Entity,
|
||||
OnInit,
|
||||
PrimaryKey,
|
||||
Property,
|
||||
} from "@mikro-orm/core"
|
||||
|
||||
@Entity({ tableName: "region_currency" })
|
||||
export default class Currency {
|
||||
@PrimaryKey({ columnType: "text" })
|
||||
id: string
|
||||
|
||||
@Property({ columnType: "text" })
|
||||
code: string
|
||||
|
||||
@Property({ columnType: "text" })
|
||||
symbol: string
|
||||
|
||||
@Property({ columnType: "text" })
|
||||
symbol_native: string
|
||||
|
||||
@Property({ columnType: "text" })
|
||||
name: string
|
||||
|
||||
@BeforeCreate()
|
||||
onCreate() {
|
||||
this.id = generateEntityId(this.id, "reg_curr")
|
||||
}
|
||||
|
||||
@OnInit()
|
||||
onInit() {
|
||||
this.id = generateEntityId(this.id, "reg_curr")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
export { default as Country } from "./country"
|
||||
export { default as Currency } from "./currency"
|
||||
export { default as Region } from "./region"
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
import { DAL } from "@medusajs/types"
|
||||
import { DALUtils, generateEntityId } from "@medusajs/utils"
|
||||
import {
|
||||
BeforeCreate,
|
||||
Cascade,
|
||||
Collection,
|
||||
Entity,
|
||||
Filter,
|
||||
Index,
|
||||
ManyToOne,
|
||||
OneToMany,
|
||||
OptionalProps,
|
||||
PrimaryKey,
|
||||
Property,
|
||||
} from "@mikro-orm/core"
|
||||
import Country from "./country"
|
||||
import Currency from "./currency"
|
||||
|
||||
type RegionOptionalProps =
|
||||
| "currency"
|
||||
| "countries"
|
||||
| DAL.SoftDeletableEntityDateColumns
|
||||
|
||||
@Entity({ tableName: "region" })
|
||||
@Filter(DALUtils.mikroOrmSoftDeletableFilterOptions)
|
||||
export default class Region {
|
||||
[OptionalProps]?: RegionOptionalProps
|
||||
|
||||
@PrimaryKey({ columnType: "text" })
|
||||
id: string
|
||||
|
||||
@Property({ columnType: "text" })
|
||||
name: string
|
||||
|
||||
@Property({ columnType: "text" })
|
||||
currency_code: string
|
||||
|
||||
@ManyToOne({
|
||||
entity: () => Currency,
|
||||
onDelete: "cascade",
|
||||
index: "IDX_region_currency_code",
|
||||
cascade: [Cascade.PERSIST],
|
||||
})
|
||||
currency: Currency
|
||||
|
||||
@OneToMany(() => Country, (country) => country.region, {
|
||||
cascade: [Cascade.REMOVE],
|
||||
})
|
||||
countries = new Collection<Country>(this)
|
||||
|
||||
@Property({ columnType: "jsonb", nullable: true })
|
||||
metadata: Record<string, unknown> | null = null
|
||||
|
||||
@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
|
||||
|
||||
@Index({ name: "IDX_region_deleted_at" })
|
||||
@Property({ columnType: "timestamptz", nullable: true })
|
||||
deleted_at: Date | null = null
|
||||
|
||||
@BeforeCreate()
|
||||
onCreate() {
|
||||
this.id = generateEntityId(this.id, "reg")
|
||||
}
|
||||
|
||||
@BeforeCreate()
|
||||
onInit() {
|
||||
this.id = generateEntityId(this.id, "reg")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { ModuleExports } from "@medusajs/types"
|
||||
import { RegionModuleService } from "@services"
|
||||
|
||||
import loadConnection from "./loaders/connection"
|
||||
import loadContainer from "./loaders/container"
|
||||
import loadDefaults from "./loaders/defaults"
|
||||
|
||||
const service = RegionModuleService
|
||||
const loaders = [loadContainer, loadConnection, loadDefaults] 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 { 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 })
|
||||
})()
|
||||
@@ -0,0 +1,16 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
describe("Noop test", () => {
|
||||
it("noop check", async () => {
|
||||
expect(true).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
export { default as RegionModuleService } from "./region-module";
|
||||
|
||||
@@ -0,0 +1,230 @@
|
||||
import {
|
||||
Context,
|
||||
CreateRegionDTO,
|
||||
DAL,
|
||||
InternalModuleDeclaration,
|
||||
IRegionModuleService,
|
||||
ModuleJoinerConfig,
|
||||
ModulesSdkTypes,
|
||||
RegionCountryDTO,
|
||||
RegionCurrencyDTO,
|
||||
RegionDTO,
|
||||
UpdateRegionDTO,
|
||||
} from "@medusajs/types"
|
||||
import {
|
||||
InjectManager,
|
||||
InjectTransactionManager,
|
||||
MedusaContext,
|
||||
MedusaError,
|
||||
ModulesSdkUtils,
|
||||
promiseAll,
|
||||
} from "@medusajs/utils"
|
||||
|
||||
import { Country, Currency, Region } from "@models"
|
||||
|
||||
import { DefaultsUtils } from "@medusajs/utils"
|
||||
import { CreateCountryDTO, CreateCurrencyDTO } from "@types"
|
||||
import { entityNameToLinkableKeysMap, joinerConfig } from "../joiner-config"
|
||||
|
||||
const COUNTRIES_LIMIT = 1000
|
||||
|
||||
type InjectedDependencies = {
|
||||
baseRepository: DAL.RepositoryService
|
||||
regionService: ModulesSdkTypes.InternalModuleService<any>
|
||||
countryService: ModulesSdkTypes.InternalModuleService<any>
|
||||
currencyService: ModulesSdkTypes.InternalModuleService<any>
|
||||
}
|
||||
|
||||
const generateMethodForModels = [Country, Currency]
|
||||
|
||||
export default class RegionModuleService<
|
||||
TRegion extends Region = Region,
|
||||
TCountry extends Country = Country,
|
||||
TCurrency extends Currency = Currency
|
||||
>
|
||||
extends ModulesSdkUtils.abstractModuleServiceFactory<
|
||||
InjectedDependencies,
|
||||
RegionDTO,
|
||||
{
|
||||
Country: {
|
||||
dto: RegionCountryDTO
|
||||
}
|
||||
Currency: {
|
||||
dto: RegionCurrencyDTO
|
||||
}
|
||||
}
|
||||
>(Region, generateMethodForModels, entityNameToLinkableKeysMap)
|
||||
implements IRegionModuleService
|
||||
{
|
||||
protected baseRepository_: DAL.RepositoryService
|
||||
protected readonly regionService_: ModulesSdkTypes.InternalModuleService<TRegion>
|
||||
protected readonly countryService_: ModulesSdkTypes.InternalModuleService<TCountry>
|
||||
protected readonly currencyService_: ModulesSdkTypes.InternalModuleService<TCurrency>
|
||||
|
||||
constructor(
|
||||
{
|
||||
baseRepository,
|
||||
regionService,
|
||||
countryService,
|
||||
currencyService,
|
||||
}: InjectedDependencies,
|
||||
protected readonly moduleDeclaration: InternalModuleDeclaration
|
||||
) {
|
||||
// @ts-ignore
|
||||
super(...arguments)
|
||||
this.baseRepository_ = baseRepository
|
||||
this.regionService_ = regionService
|
||||
this.countryService_ = countryService
|
||||
this.currencyService_ = currencyService
|
||||
}
|
||||
|
||||
__joinerConfig(): ModuleJoinerConfig {
|
||||
return joinerConfig
|
||||
}
|
||||
|
||||
async create(
|
||||
data: CreateRegionDTO[],
|
||||
sharedContext?: Context
|
||||
): Promise<RegionDTO[]>
|
||||
async create(
|
||||
data: CreateRegionDTO,
|
||||
sharedContext?: Context
|
||||
): Promise<RegionDTO>
|
||||
@InjectManager("baseRepository_")
|
||||
async create(
|
||||
data: CreateRegionDTO | CreateRegionDTO[],
|
||||
@MedusaContext() sharedContext: Context = {}
|
||||
): Promise<RegionDTO | RegionDTO[]> {
|
||||
const input = Array.isArray(data) ? data : [data]
|
||||
|
||||
const result = await this.create_(input, sharedContext)
|
||||
|
||||
return await this.baseRepository_.serialize<RegionDTO[]>(
|
||||
Array.isArray(data) ? result : result[0],
|
||||
{
|
||||
populate: true,
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
@InjectTransactionManager("baseRepository_")
|
||||
async create_(
|
||||
data: CreateRegionDTO[],
|
||||
@MedusaContext() sharedContext: Context = {}
|
||||
): Promise<Region[]> {
|
||||
let currencies = await this.currencyService_.list(
|
||||
{ code: data.map((d) => d.currency_code.toLowerCase()) },
|
||||
{},
|
||||
sharedContext
|
||||
)
|
||||
|
||||
let currencyMap = new Map(currencies.map((c) => [c.code.toLowerCase(), c]))
|
||||
for (const reg of data) {
|
||||
const lowerCasedCurrency = reg.currency_code.toLowerCase()
|
||||
if (!currencyMap.has(lowerCasedCurrency)) {
|
||||
throw new MedusaError(
|
||||
MedusaError.Types.INVALID_DATA,
|
||||
`Currency with code: ${reg.currency_code} was not found`
|
||||
)
|
||||
}
|
||||
|
||||
reg.currency = currencyMap.get(lowerCasedCurrency) as RegionCurrencyDTO
|
||||
}
|
||||
|
||||
const result = await this.regionService_.create(data, sharedContext)
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
async update(
|
||||
data: UpdateRegionDTO[],
|
||||
sharedContext?: Context
|
||||
): Promise<RegionDTO[]>
|
||||
async update(
|
||||
data: UpdateRegionDTO,
|
||||
sharedContext?: Context
|
||||
): Promise<RegionDTO>
|
||||
@InjectTransactionManager("baseRepository_")
|
||||
async update(
|
||||
data: UpdateRegionDTO | UpdateRegionDTO[],
|
||||
@MedusaContext() sharedContext: Context = {}
|
||||
): Promise<RegionDTO | RegionDTO[]> {
|
||||
const result = await this.regionService_.update(data, sharedContext)
|
||||
|
||||
return await this.baseRepository_.serialize<RegionDTO[]>(
|
||||
Array.isArray(data) ? result : result[0],
|
||||
{
|
||||
populate: true,
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
@InjectManager("baseRepository_")
|
||||
public async createDefaultCountriesAndCurrencies(
|
||||
@MedusaContext() sharedContext: Context = {}
|
||||
): Promise<void> {
|
||||
await promiseAll([
|
||||
await this.maybeCreateCountries(sharedContext),
|
||||
await this.maybeCreateCurrencies(sharedContext),
|
||||
])
|
||||
}
|
||||
|
||||
@InjectTransactionManager("baseRepository_")
|
||||
private async maybeCreateCountries(
|
||||
@MedusaContext() sharedContext: Context
|
||||
): Promise<void> {
|
||||
const [countries, count] = await this.countryService_.listAndCount(
|
||||
{},
|
||||
{ select: ["id", "iso_2"], take: COUNTRIES_LIMIT },
|
||||
sharedContext
|
||||
)
|
||||
|
||||
let countsToCreate: CreateCountryDTO[] = []
|
||||
if (count !== DefaultsUtils.defaultCountries.length) {
|
||||
const countriesInDb = new Set(countries.map((c) => c.iso_2))
|
||||
|
||||
const countriesToAdd = DefaultsUtils.defaultCountries.filter(
|
||||
(c) => !countriesInDb.has(c.alpha2.toLowerCase())
|
||||
)
|
||||
|
||||
countsToCreate = countriesToAdd.map((c) => ({
|
||||
iso_2: c.alpha2.toLowerCase(),
|
||||
iso_3: c.alpha3.toLowerCase(),
|
||||
num_code: c.numeric,
|
||||
name: c.name.toUpperCase(),
|
||||
display_name: c.name,
|
||||
}))
|
||||
}
|
||||
|
||||
if (countsToCreate.length) {
|
||||
await this.countryService_.create(countsToCreate, sharedContext)
|
||||
}
|
||||
}
|
||||
|
||||
@InjectTransactionManager("baseRepository_")
|
||||
private async maybeCreateCurrencies(
|
||||
@MedusaContext() sharedContext: Context
|
||||
): Promise<void> {
|
||||
const [currency] = await this.currencyService_.list(
|
||||
{},
|
||||
{ select: ["id"], take: 1 },
|
||||
sharedContext
|
||||
)
|
||||
|
||||
let currsToCreate: CreateCurrencyDTO[] = []
|
||||
if (!currency) {
|
||||
currsToCreate = Object.entries(DefaultsUtils.defaultCurrencies).map(
|
||||
([code, currency]) => ({
|
||||
code: code.toLowerCase(),
|
||||
symbol: currency.symbol,
|
||||
symbol_native: currency.symbol_native,
|
||||
name: currency.name,
|
||||
})
|
||||
)
|
||||
}
|
||||
|
||||
if (currsToCreate.length) {
|
||||
await this.currencyService_.create(currsToCreate, sharedContext)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { Logger } from "@medusajs/types"
|
||||
|
||||
export type InitializeModuleInjectableDependencies = {
|
||||
logger?: Logger
|
||||
}
|
||||
|
||||
export type UpdateCountryRegion = {
|
||||
id: string
|
||||
region_id: string
|
||||
}
|
||||
|
||||
export type CreateCurrencyDTO = {
|
||||
code: string
|
||||
symbol: string
|
||||
name: string
|
||||
symbol_native: string
|
||||
}
|
||||
|
||||
export type CreateCountryDTO = {
|
||||
iso_2: string
|
||||
iso_3: string
|
||||
num_code: string
|
||||
name: string
|
||||
display_name: string
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"lib": ["es2020"],
|
||||
"target": "es2020",
|
||||
"outDir": "./dist",
|
||||
"esModuleInterop": true,
|
||||
"declaration": true,
|
||||
"module": "commonjs",
|
||||
"moduleResolution": "node",
|
||||
"emitDecoratorMetadata": true,
|
||||
"experimentalDecorators": true,
|
||||
"sourceMap": false,
|
||||
"noImplicitReturns": true,
|
||||
"strictNullChecks": true,
|
||||
"strictFunctionTypes": true,
|
||||
"noImplicitThis": true,
|
||||
"allowJs": true,
|
||||
"skipLibCheck": true,
|
||||
"downlevelIteration": true, // to use ES5 specific tooling
|
||||
"baseUrl": ".",
|
||||
"resolveJsonModule": true,
|
||||
"paths": {
|
||||
"@models": ["./src/models"],
|
||||
"@services": ["./src/services"],
|
||||
"@repositories": ["./src/repositories"],
|
||||
"@types": ["./src/types"]
|
||||
}
|
||||
},
|
||||
"include": ["src"],
|
||||
"exclude": [
|
||||
"dist",
|
||||
"./src/**/__tests__",
|
||||
"./src/**/__mocks__",
|
||||
"./src/**/__fixtures__",
|
||||
"node_modules"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"include": ["src", "integration-tests"],
|
||||
"exclude": ["node_modules", "dist"],
|
||||
"compilerOptions": {
|
||||
"sourceMap": true
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user