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,10 @@
import {
moduleDefinition,
revertMigration,
runMigrations,
} from "./module-definition"
export default moduleDefinition
export { revertMigration, runMigrations }
export * from "./initialize"

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]
}

View File

@@ -0,0 +1,36 @@
import { Modules } from "@medusajs/modules-sdk"
import { ModuleJoinerConfig } from "@medusajs/types"
import { MapToConfig } from "@medusajs/utils"
import { Country, Region } from "@models"
export const LinkableKeys = {
region_id: Region.name,
country_iso: Country.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: ["country", "countries"],
args: { entity: Country.name, methodSuffix: "Countries" },
},
],
} as ModuleJoinerConfig

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,
})
}

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,
})

View File

@@ -0,0 +1,30 @@
import { Logger } from "@medusajs/types"
import { LoaderOptions, ModulesSdkTypes } from "@medusajs/types"
import { ContainerRegistrationKeys } from "@medusajs/utils"
import { DefaultsUtils } from "@medusajs/utils"
import { Country } from "@models"
export default async ({ container }: LoaderOptions): Promise<void> => {
// TODO: Add default logger to the container when running tests
const logger =
container.resolve<Logger>(ContainerRegistrationKeys.LOGGER) ?? console
const countryService_: ModulesSdkTypes.InternalModuleService<Country> =
container.resolve("countryService")
try {
const normalizedCountries = DefaultsUtils.defaultCountries.map((c) => ({
iso_2: c.alpha2.toLowerCase(),
iso_3: c.alpha3.toLowerCase(),
num_code: c.numeric,
name: c.name.toUpperCase(),
display_name: c.name,
}))
const resp = await countryService_.upsert(normalizedCountries)
logger.info(`Loaded ${resp.length} countries`)
} catch (error) {
logger.warn(
`Failed to load countries, skipping loader. Original error: ${error.message}`
)
}
}

View File

@@ -0,0 +1,4 @@
export * from "./connection"
export * from "./container"
export * from "./defaults"

View File

@@ -0,0 +1,200 @@
{
"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"
},
"currency_code": {
"name": "currency_code",
"type": "text",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": false,
"mappedType": "text"
},
"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": "region",
"schema": "public",
"indexes": [
{
"columnNames": [
"deleted_at"
],
"composite": false,
"keyName": "IDX_region_deleted_at",
"primary": false,
"unique": false
},
{
"keyName": "region_pkey",
"columnNames": [
"id"
],
"composite": false,
"primary": true,
"unique": true
}
],
"checks": [],
"foreignKeys": {}
},
{
"columns": {
"id": {
"name": "id",
"type": "text",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": false,
"mappedType": "text"
},
"iso_2": {
"name": "iso_2",
"type": "text",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": false,
"mappedType": "text"
},
"iso_3": {
"name": "iso_3",
"type": "text",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": false,
"mappedType": "text"
},
"num_code": {
"name": "num_code",
"type": "int",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": false,
"mappedType": "integer"
},
"name": {
"name": "name",
"type": "text",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": false,
"mappedType": "text"
},
"display_name": {
"name": "display_name",
"type": "text",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": false,
"mappedType": "text"
},
"region_id": {
"name": "region_id",
"type": "text",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": true,
"mappedType": "text"
}
},
"name": "region_country",
"schema": "public",
"indexes": [
{
"keyName": "region_country_pkey",
"columnNames": [
"id"
],
"composite": false,
"primary": true,
"unique": true
}
],
"checks": [],
"foreignKeys": {
"region_country_region_id_foreign": {
"constraintName": "region_country_region_id_foreign",
"columnNames": [
"region_id"
],
"localTableName": "public.region_country",
"referencedColumnNames": [
"id"
],
"referencedTableName": "public.region",
"deleteRule": "set null",
"updateRule": "cascade"
}
}
}
]
}

View File

@@ -0,0 +1,44 @@
import { generatePostgresAlterColummnIfExistStatement } from "@medusajs/utils"
import { Migration } from "@mikro-orm/migrations"
export class RegionModuleSetup20240205173216 extends Migration {
async up(): Promise<void> {
this.addSql(`
-- Create or update "region" table
CREATE TABLE IF NOT EXISTS "region" (
"id" text NOT NULL,
"name" text NOT NULL,
"currency_code" text NOT NULL,
"metadata" jsonb NULL,
"created_at" timestamptz NOT NULL DEFAULT now(),
"updated_at" timestamptz NOT NULL DEFAULT now(),
"deleted_at" timestamptz NULL,
CONSTRAINT "region_pkey" PRIMARY KEY ("id")
);
-- Adjust "region" table
ALTER TABLE "region" DROP CONSTRAINT IF EXISTS "FK_3bdd5896ec93be2f1c62a3309a5";
ALTER TABLE "region" DROP CONSTRAINT IF EXISTS "FK_91f88052197680f9790272aaf5b";
${generatePostgresAlterColummnIfExistStatement(
"region",
["tax_rate", "gift_cards_taxable", "includes_tax"],
"DROP NOT NULL"
)}
ALTER TABLE "region" ADD COLUMN IF NOT EXISTS "automatic_taxes" BOOLEAN NOT NULL DEFAULT TRUE;
CREATE INDEX IF NOT EXISTS "IDX_region_deleted_at" ON "region" ("deleted_at") WHERE "deleted_at" IS NOT NULL;
-- Create or update "region_country" table
CREATE TABLE IF NOT EXISTS "region_country" (
"iso_2" text NOT NULL,
"iso_3" text NOT NULL,
"num_code" int NOT NULL,
"name" text NOT NULL,
"display_name" text NOT NULL,
"region_id" text NULL,
CONSTRAINT "region_country_pkey" PRIMARY KEY ("iso_2")
);
CREATE UNIQUE INDEX IF NOT EXISTS "IDX_region_country_region_id_iso_2_unique" ON "region_country" (region_id, iso_2);
-- Adjust foreign keys for "region_country"
ALTER TABLE "region_country" DROP CONSTRAINT IF EXISTS "FK_91f88052197680f9790272aaf5b";
ALTER TABLE "region_country" ADD CONSTRAINT "region_country_region_id_foreign" FOREIGN KEY ("region_id") REFERENCES "region" ("id") ON UPDATE CASCADE ON DELETE SET NULL;
`)
}
}

View File

@@ -0,0 +1,44 @@
import { Entity, ManyToOne, PrimaryKey, Property } from "@mikro-orm/core"
import { createPsqlIndexStatementHelper } from "@medusajs/utils"
import Region from "./region"
// We don't need a partial index on deleted_at here since we don't support soft deletes on countries
const regionIdIsoIndexName = "IDX_region_country_region_id_iso_2_unique"
const RegionIdIsoIndexStatement = createPsqlIndexStatementHelper({
name: regionIdIsoIndexName,
tableName: "region_country",
columns: ["region_id", "iso_2"],
unique: true,
})
RegionIdIsoIndexStatement.MikroORMIndex()
@Entity({ tableName: "region_country" })
export default class Country {
@PrimaryKey({ columnType: "text" })
@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,
fieldName: "region_id",
nullable: true,
onDelete: "set null",
})
region?: Region | null
}

View File

@@ -0,0 +1,2 @@
export { default as Country } from "./country"
export { default as Region } from "./region"

View File

@@ -0,0 +1,72 @@
import { DAL } from "@medusajs/types"
import { DALUtils, Searchable, generateEntityId } from "@medusajs/utils"
import {
BeforeCreate,
Collection,
Entity,
Filter,
Index,
OnInit,
OneToMany,
OptionalProps,
PrimaryKey,
Property,
} from "@mikro-orm/core"
import Country from "./country"
type RegionOptionalProps = "countries" | DAL.SoftDeletableEntityDateColumns
@Entity({ tableName: "region" })
@Filter(DALUtils.mikroOrmSoftDeletableFilterOptions)
export default class Region {
[OptionalProps]?: RegionOptionalProps
@PrimaryKey({ columnType: "text" })
id: string
@Searchable()
@Property({ columnType: "text" })
name: string
@Searchable()
@Property({ columnType: "text" })
currency_code: string
@Property({ columnType: "boolean" })
automatic_taxes = true
@OneToMany(() => Country, (country) => country.region)
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")
}
@OnInit()
onInit() {
this.id = generateEntityId(this.id, "reg")
}
}

View File

@@ -0,0 +1,32 @@
import { ModuleExports } from "@medusajs/types"
import { RegionModuleService } from "./services"
import { Modules } from "@medusajs/modules-sdk"
import { ModulesSdkUtils } from "@medusajs/utils"
import * as RegionModels from "@models"
import loadConnection from "./loaders/connection"
import loadContainer from "./loaders/container"
import loadDefaults from "./loaders/defaults"
const migrationScriptOptions = {
moduleName: Modules.REGION,
models: RegionModels,
pathToMigrations: __dirname + "/migrations",
}
export const runMigrations = ModulesSdkUtils.buildMigrationScript(
migrationScriptOptions
)
export const revertMigration = ModulesSdkUtils.buildRevertMigrationScript(
migrationScriptOptions
)
const service = RegionModuleService
const loaders = [loadContainer, loadConnection, loadDefaults] as any
export const moduleDefinition: ModuleExports = {
service,
loaders,
runMigrations,
revertMigration,
}

View File

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

View File

@@ -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 })
})()

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
}

View File

@@ -0,0 +1,2 @@
export { default as RegionModuleService } from "./region-module";

View File

@@ -0,0 +1,335 @@
import {
Context,
CreateRegionDTO,
DAL,
FilterableRegionProps,
InternalModuleDeclaration,
IRegionModuleService,
ModuleJoinerConfig,
ModulesSdkTypes,
RegionCountryDTO,
RegionDTO,
UpdateRegionDTO,
UpsertRegionDTO,
} from "@medusajs/types"
import {
arrayDifference,
InjectManager,
InjectTransactionManager,
isString,
MedusaContext,
MedusaError,
ModulesSdkUtils,
promiseAll,
removeUndefined,
getDuplicates,
} from "@medusajs/utils"
import { Country, Region } from "@models"
import { UpdateRegionInput } from "@types"
import { entityNameToLinkableKeysMap, joinerConfig } from "../joiner-config"
type InjectedDependencies = {
baseRepository: DAL.RepositoryService
regionService: ModulesSdkTypes.InternalModuleService<any>
countryService: ModulesSdkTypes.InternalModuleService<any>
}
const generateMethodForModels = [Country]
export default class RegionModuleService<
TRegion extends Region = Region,
TCountry extends Country = Country
>
extends ModulesSdkUtils.abstractModuleServiceFactory<
InjectedDependencies,
RegionDTO,
{
Country: {
dto: RegionCountryDTO
}
}
>(Region, generateMethodForModels, entityNameToLinkableKeysMap)
implements IRegionModuleService
{
protected baseRepository_: DAL.RepositoryService
protected readonly regionService_: ModulesSdkTypes.InternalModuleService<TRegion>
protected readonly countryService_: ModulesSdkTypes.InternalModuleService<TCountry>
constructor(
{ baseRepository, regionService, countryService }: InjectedDependencies,
protected readonly moduleDeclaration: InternalModuleDeclaration
) {
// @ts-ignore
super(...arguments)
this.baseRepository_ = baseRepository
this.regionService_ = regionService
this.countryService_ = countryService
}
__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]
)
}
@InjectTransactionManager("baseRepository_")
async create_(
data: CreateRegionDTO[],
@MedusaContext() sharedContext: Context = {}
): Promise<Region[]> {
let normalizedInput = RegionModuleService.normalizeInput(data)
let normalizedDbRegions = normalizedInput.map((region) =>
removeUndefined({
...region,
countries: undefined,
})
)
const result = await this.regionService_.create(
normalizedDbRegions,
sharedContext
)
if (data.some((input) => input.countries?.length)) {
await this.validateCountries(
normalizedInput.map((r) => r.countries ?? []).flat(),
sharedContext
)
await this.countryService_.update(
normalizedInput.map((region, i) => ({
selector: { iso_2: region.countries },
data: {
region_id: result[i].id,
},
})),
sharedContext
)
}
return result
}
async upsert(
data: UpsertRegionDTO[],
sharedContext?: Context
): Promise<RegionDTO[]>
async upsert(
data: UpsertRegionDTO,
sharedContext?: Context
): Promise<RegionDTO>
@InjectTransactionManager("baseRepository_")
async upsert(
data: UpsertRegionDTO | UpsertRegionDTO[],
@MedusaContext() sharedContext: Context = {}
): Promise<RegionDTO | RegionDTO[]> {
const input = Array.isArray(data) ? data : [data]
const forUpdate = input.filter(
(region): region is UpdateRegionInput => !!region.id
)
const forCreate = input.filter(
(region): region is CreateRegionDTO => !region.id
)
const operations: Promise<Region[]>[] = []
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<RegionDTO[] | RegionDTO>(
Array.isArray(data) ? result : result[0]
)
}
async update(
id: string,
data: UpdateRegionDTO,
sharedContext?: Context
): Promise<RegionDTO>
async update(
selector: FilterableRegionProps,
data: UpdateRegionDTO,
sharedContext?: Context
): Promise<RegionDTO[]>
@InjectManager("baseRepository_")
async update(
idOrSelector: string | FilterableRegionProps,
data: UpdateRegionDTO,
@MedusaContext() sharedContext: Context = {}
): Promise<RegionDTO | RegionDTO[]> {
let normalizedInput: UpdateRegionInput[] = []
if (isString(idOrSelector)) {
normalizedInput = [{ id: idOrSelector, ...data }]
} else {
const regions = await this.regionService_.list(
idOrSelector,
{},
sharedContext
)
normalizedInput = regions.map((region) => ({
id: region.id,
...data,
}))
}
const updateResult = await this.update_(normalizedInput, sharedContext)
const regions = await this.baseRepository_.serialize<
RegionDTO[] | RegionDTO
>(updateResult)
return isString(idOrSelector) ? regions[0] : regions
}
@InjectTransactionManager("baseRepository_")
protected async update_(
data: UpdateRegionInput[],
@MedusaContext() sharedContext: Context = {}
): Promise<Region[]> {
const normalizedInput = RegionModuleService.normalizeInput(data)
// If countries are being updated for a region, first make previously set countries' region to null to get to a clean slate.
// Somewhat less efficient, but region operations will be very rare, so it is better to go with a simple solution
const regionsWithCountryUpdate = normalizedInput
.filter((region) => !!region.countries)
.map((region) => region.id)
.flat()
let normalizedDbRegions = normalizedInput.map((region) =>
removeUndefined({
...region,
countries: undefined, // -> delete countries if passed because we want to do update "manually"
})
)
if (regionsWithCountryUpdate.length) {
await this.countryService_.update(
{
selector: {
region_id: regionsWithCountryUpdate,
},
data: { region_id: null },
},
sharedContext
)
await this.validateCountries(
normalizedInput.map((d) => d.countries ?? []).flat(),
sharedContext
)
await this.countryService_.update(
normalizedInput.map((region) => ({
selector: { iso_2: region.countries },
data: {
region_id: region.id,
},
})),
sharedContext
)
}
return await this.regionService_.update(normalizedDbRegions, sharedContext)
}
private static normalizeInput<T extends UpdateRegionDTO>(regions: T[]): T[] {
return regions.map((region) =>
removeUndefined({
...region,
currency_code: region.currency_code?.toLowerCase(),
name: region.name?.trim(),
countries: region.countries?.map((country) => country.toLowerCase()),
})
)
}
/**
* Validate that countries can be assigned to a region.
*
* NOTE: this method relies on countries of the regions that we are assigning to need to be unassigned first.
* @param countries
* @param sharedContext
* @private
*/
private async validateCountries(
countries: string[] | undefined,
sharedContext: Context
): Promise<TCountry[]> {
if (!countries?.length) {
return []
}
// The new regions being created have a country conflict
const uniqueCountries = Array.from(new Set(countries))
if (uniqueCountries.length !== countries.length) {
throw new MedusaError(
MedusaError.Types.INVALID_DATA,
`Countries with codes: "${getDuplicates(countries).join(
", "
)}" are already assigned to a region`
)
}
const countriesInDb = await this.countryService_.list(
{ iso_2: uniqueCountries },
{ select: ["iso_2", "region_id"], take: null },
sharedContext
)
const countryCodesInDb = countriesInDb.map((c) => c.iso_2.toLowerCase())
// Countries missing in the database
if (countriesInDb.length !== uniqueCountries.length) {
const missingCountries = arrayDifference(
uniqueCountries,
countryCodesInDb
)
throw new MedusaError(
MedusaError.Types.INVALID_DATA,
`Countries with codes: "${missingCountries.join(", ")}" do not exist`
)
}
// Countries that already have a region already assigned to them
const countriesWithRegion = countriesInDb.filter((c) => !!c.region_id)
if (countriesWithRegion.length) {
throw new MedusaError(
MedusaError.Types.INVALID_DATA,
`Countries with codes: "${countriesWithRegion
.map((c) => c.iso_2)
.join(", ")}" are already assigned to a region`
)
}
return countriesInDb
}
}

View File

@@ -0,0 +1,21 @@
import { Logger, UpdateRegionDTO } from "@medusajs/types"
import { Country } from "@models"
export type InitializeModuleInjectableDependencies = {
logger?: Logger
}
export type UpdateCountryRegion = {
id: string
region_id: string
}
export type CreateCountryDTO = {
iso_2: string
iso_3: string
num_code: string
name: string
display_name: string
}
export type UpdateRegionInput = UpdateRegionDTO & { id: string }