feat: Region Module (basic CRUD) (#6315)

This commit is contained in:
Oli Juhl
2024-02-05 16:03:26 +00:00
committed by GitHub
parent ede221d4f7
commit 823b98aaa1
49 changed files with 2716 additions and 13 deletions
+28
View File
@@ -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"
+34
View File
@@ -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]
}
+41
View File
@@ -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
+35
View File
@@ -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,
})
}
+10
View File
@@ -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,
})
+7
View File
@@ -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()
}
+4
View File
@@ -0,0 +1,4 @@
export * from "./connection"
export * from "./container"
export * from "./defaults"
+54
View File
@@ -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")
}
}
+36
View File
@@ -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")
}
}
+4
View File
@@ -0,0 +1,4 @@
export { default as Country } from "./country"
export { default as Currency } from "./currency"
export { default as Region } from "./region"
+82
View File
@@ -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")
}
}
+14
View File
@@ -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 })
})()
+16
View File
@@ -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)
})
})
+2
View File
@@ -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)
}
}
}
+25
View File
@@ -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
}