chore(): Reorganize modules (#7210)
**What** Move all modules to the modules directory
This commit is contained in:
committed by
GitHub
parent
7a351eef09
commit
4eae25e1ef
6
packages/modules/region/.gitignore
vendored
Normal file
6
packages/modules/region/.gitignore
vendored
Normal file
@@ -0,0 +1,6 @@
|
||||
/dist
|
||||
node_modules
|
||||
.DS_store
|
||||
.env*
|
||||
.env
|
||||
*.sql
|
||||
12
packages/modules/region/CHANGELOG.md
Normal file
12
packages/modules/region/CHANGELOG.md
Normal file
@@ -0,0 +1,12 @@
|
||||
# @medusajs/region
|
||||
|
||||
## 0.1.1
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- [#6700](https://github.com/medusajs/medusa/pull/6700) [`8f8a4f9b13`](https://github.com/medusajs/medusa/commit/8f8a4f9b1353087d98f6cc75346d43a7f49901a8) Thanks [@olivermrbl](https://github.com/olivermrbl)! - chore: Version all modules to allow for initial testing
|
||||
|
||||
- Updated dependencies [[`1fd0457c15`](https://github.com/medusajs/medusa/commit/1fd0457c153b2ef7657c052878d8e5364e1b324a), [`9288f53327`](https://github.com/medusajs/medusa/commit/9288f53327b8ce617af92ed8d14d9459cbfeb13c), [`d4b921f3db`](https://github.com/medusajs/medusa/commit/d4b921f3dbe0a38f1565a8de759996c70798d58e), [`ac86362e81`](https://github.com/medusajs/medusa/commit/ac86362e81d8523cb8e3dfad026fc94658513018), [`e4acde1aa2`](https://github.com/medusajs/medusa/commit/e4acde1aa2eb57f07e6692fe8b61f728948b9a96), [`1a661adf3e`](https://github.com/medusajs/medusa/commit/1a661adf3ef4991aa6e237dd894b6a5c47cd4aca), [`56cbf88115`](https://github.com/medusajs/medusa/commit/56cbf88115994adea7037c3f2814f0c96af3cfc0), [`36a61658f9`](https://github.com/medusajs/medusa/commit/36a61658f969a7b19c84a1e621ad1464927cafb1), [`04a532e5ef`](https://github.com/medusajs/medusa/commit/04a532e5efabbf75b1e4155520b1da175b686ffc), [`c319edb8e0`](https://github.com/medusajs/medusa/commit/c319edb8e0ecd13d086652147667916e5abab2d8), [`0b9fcb6324`](https://github.com/medusajs/medusa/commit/0b9fcb6324eee9f2556c7e6317775fae93b12a47), [`586df9da25`](https://github.com/medusajs/medusa/commit/586df9da250e492442769f5bac2f8b3de1d46f05), [`b3d826497b`](https://github.com/medusajs/medusa/commit/b3d826497b3dae5e1b26b7924706c24fd5e87ca5), [`a86c87fe14`](https://github.com/medusajs/medusa/commit/a86c87fe1442afce9285e39255914e01012b4449), [`640eccd5dd`](https://github.com/medusajs/medusa/commit/640eccd5ddbb163e0f987ce6c772f1129c2e2632), [`8ea37d03c9`](https://github.com/medusajs/medusa/commit/8ea37d03c914a5004a3e42770668b2d1f7f8f564), [`339a946f38`](https://github.com/medusajs/medusa/commit/339a946f389033c21e05338f9dbf07d88e140533), [`ac829fc67f`](https://github.com/medusajs/medusa/commit/ac829fc67f7495b08f28e55923c59f0fd6320311), [`d9d5afc3cf`](https://github.com/medusajs/medusa/commit/d9d5afc3cfc29221d0e65bff7b78474a8fb8f31f), [`c3c4f49fc2`](https://github.com/medusajs/medusa/commit/c3c4f49fc2126f950e69e291ca939ca88a15afd3), [`9288f53327`](https://github.com/medusajs/medusa/commit/9288f53327b8ce617af92ed8d14d9459cbfeb13c), [`0d46abf0ff`](https://github.com/medusajs/medusa/commit/0d46abf0ffa4c5e03bf7d2a9cdf1db828a76bea8), [`fafde4f54d`](https://github.com/medusajs/medusa/commit/fafde4f54d3ef75a7d382e6cbf94e38b3deae99b), [`8dad2b51a2`](https://github.com/medusajs/medusa/commit/8dad2b51a26c4c3c14a6c95f70424c8bef2ad63e), [`0c705d7bd4`](https://github.com/medusajs/medusa/commit/0c705d7bd41a768c48017ae95b3c8414d96c6acb), [`a6d7070dd6`](https://github.com/medusajs/medusa/commit/a6d7070dd669c21ea19d70434d42c2f8167dc309), [`1d91b7429b`](https://github.com/medusajs/medusa/commit/1d91b7429beebd6f09d5027f7f7e1fe74ce3a8ff), [`168f02f138`](https://github.com/medusajs/medusa/commit/168f02f138ad101e1013f2c8c3f8dc19de12accf), [`1ed5f918c3`](https://github.com/medusajs/medusa/commit/1ed5f918c31794a70aca4a4e4cd83cf456593baa), [`c20eb15cd9`](https://github.com/medusajs/medusa/commit/c20eb15cd9b1bd90c8d01f68eca6f0f181cd902d), [`e5945479e0`](https://github.com/medusajs/medusa/commit/e5945479e091d9560ae3e7240306a31031ef4584), [`f5c2256286`](https://github.com/medusajs/medusa/commit/f5c22562867f412040f8bc6c55ab5de3a3735e62), [`000eb61e33`](https://github.com/medusajs/medusa/commit/000eb61e33e0302db95ee6ad1656ea9b430ed471), [`d550be3685`](https://github.com/medusajs/medusa/commit/d550be3685423218d47a20c57a5e06758f4a961a), [`62a7bcc30c`](https://github.com/medusajs/medusa/commit/62a7bcc30cbc7b234b2b51d7858439951a84edeb), [`8f8a4f9b13`](https://github.com/medusajs/medusa/commit/8f8a4f9b1353087d98f6cc75346d43a7f49901a8), [`6500f18b9b`](https://github.com/medusajs/medusa/commit/6500f18b9b80c5c9c473489e7e740d55dca74303), [`ce39b9b66e`](https://github.com/medusajs/medusa/commit/ce39b9b66e8c277ec0691ea6d0a950003be09cc1), [`a6a4b3f01a`](https://github.com/medusajs/medusa/commit/a6a4b3f01a6d2bd97b1580c59134279a1b033a5d), [`4d51f095b3`](https://github.com/medusajs/medusa/commit/4d51f095b3f98f468cefb760512563f7b77bb9cf), [`4625bd1241`](https://github.com/medusajs/medusa/commit/4625bd12416275b09c22cde4a09cb0f68df5d7c1), [`56b0b45304`](https://github.com/medusajs/medusa/commit/56b0b4530401a6ec5aa155874d371e45bb388fe2), [`cc1b66842c`](https://github.com/medusajs/medusa/commit/cc1b66842cbb37c6eab84e2d8b74844c214f38d7), [`24fb102a56`](https://github.com/medusajs/medusa/commit/24fb102a564b1253d1f8b039bb1e435cc5312fbb), [`e85463b2a7`](https://github.com/medusajs/medusa/commit/e85463b2a717751de2e21c39a4c745449b31affe)]:
|
||||
- @medusajs/types@1.11.14
|
||||
- @medusajs/utils@1.11.7
|
||||
- @medusajs/modules-sdk@1.12.9
|
||||
1
packages/modules/region/README.md
Normal file
1
packages/modules/region/README.md
Normal file
@@ -0,0 +1 @@
|
||||
# Region Module
|
||||
@@ -0,0 +1,376 @@
|
||||
import { Modules } from "@medusajs/modules-sdk"
|
||||
import { IRegionModuleService } from "@medusajs/types"
|
||||
import { moduleIntegrationTestRunner, SuiteOptions } from "medusa-test-utils"
|
||||
|
||||
jest.setTimeout(30000)
|
||||
|
||||
moduleIntegrationTestRunner({
|
||||
moduleName: Modules.REGION,
|
||||
testSuite: ({
|
||||
MikroOrmWrapper,
|
||||
service,
|
||||
}: SuiteOptions<IRegionModuleService>) => {
|
||||
describe("Region Module Service", () => {
|
||||
it("should create countries on application start", async () => {
|
||||
const countries = await service.listCountries({}, { take: null })
|
||||
expect(countries.length).toEqual(250)
|
||||
})
|
||||
|
||||
it("should create and list a region", async () => {
|
||||
const createdRegion = await service.create({
|
||||
name: "Europe",
|
||||
currency_code: "EUR",
|
||||
automatic_taxes: false,
|
||||
})
|
||||
|
||||
expect(createdRegion).toEqual(
|
||||
expect.objectContaining({
|
||||
id: createdRegion.id,
|
||||
name: "Europe",
|
||||
currency_code: "eur",
|
||||
countries: [],
|
||||
automatic_taxes: false,
|
||||
})
|
||||
)
|
||||
|
||||
const region = await service.retrieve(createdRegion.id, {
|
||||
relations: ["countries"],
|
||||
})
|
||||
|
||||
expect(region).toEqual(
|
||||
expect.objectContaining({
|
||||
id: region.id,
|
||||
name: "Europe",
|
||||
currency_code: "eur",
|
||||
countries: [],
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
it("should create a region with countries", async () => {
|
||||
const createdRegion = await service.create({
|
||||
name: "North America",
|
||||
currency_code: "USD",
|
||||
countries: ["us", "ca"],
|
||||
})
|
||||
|
||||
const region = await service.retrieve(createdRegion.id, {
|
||||
relations: ["countries"],
|
||||
})
|
||||
|
||||
expect(region).toEqual(
|
||||
expect.objectContaining({
|
||||
id: region.id,
|
||||
name: "North America",
|
||||
currency_code: "usd",
|
||||
automatic_taxes: true,
|
||||
countries: [
|
||||
expect.objectContaining({
|
||||
display_name: "Canada",
|
||||
iso_2: "ca",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
display_name: "United States",
|
||||
iso_2: "us",
|
||||
}),
|
||||
],
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
it("should throw when country doesn't exist", async () => {
|
||||
await expect(
|
||||
service.create({
|
||||
name: "North America",
|
||||
currency_code: "USD",
|
||||
countries: ["neverland"],
|
||||
})
|
||||
).rejects.toThrowError('Countries with codes: "neverland" do not exist')
|
||||
})
|
||||
|
||||
it("should throw when country is already assigned to a region", async () => {
|
||||
await service.create({
|
||||
name: "North America",
|
||||
currency_code: "USD",
|
||||
countries: ["us"],
|
||||
})
|
||||
|
||||
await expect(
|
||||
service.create({
|
||||
name: "United States",
|
||||
currency_code: "USD",
|
||||
countries: ["us"],
|
||||
})
|
||||
).rejects.toThrowError(
|
||||
'Countries with codes: "us" are already assigned to a region'
|
||||
)
|
||||
})
|
||||
|
||||
it("should throw when country is being assigned to multiple regions", async () => {
|
||||
await expect(
|
||||
service.create([
|
||||
{
|
||||
name: "United States",
|
||||
currency_code: "USD",
|
||||
countries: ["us"],
|
||||
},
|
||||
{
|
||||
name: "North America",
|
||||
currency_code: "USD",
|
||||
countries: ["us"],
|
||||
},
|
||||
])
|
||||
).rejects.toThrowError(
|
||||
'Countries with codes: "us" are already assigned to a region'
|
||||
)
|
||||
})
|
||||
|
||||
it("should upsert the region successfully", async () => {
|
||||
const createdRegion = await service.upsert({
|
||||
name: "North America",
|
||||
currency_code: "USD",
|
||||
countries: ["us", "ca"],
|
||||
})
|
||||
|
||||
await service.upsert({
|
||||
id: createdRegion.id,
|
||||
name: "Americas",
|
||||
currency_code: "MXN",
|
||||
countries: ["us", "mx"],
|
||||
automatic_taxes: false,
|
||||
})
|
||||
|
||||
const latestRegion = await service.retrieve(createdRegion.id, {
|
||||
relations: ["countries"],
|
||||
})
|
||||
|
||||
expect(latestRegion).toMatchObject({
|
||||
id: createdRegion.id,
|
||||
name: "Americas",
|
||||
currency_code: "mxn",
|
||||
automatic_taxes: false,
|
||||
})
|
||||
expect(latestRegion.countries.map((c) => c.iso_2)).toEqual(["mx", "us"])
|
||||
})
|
||||
|
||||
it("should allow mixing create and update operations in upsert", async () => {
|
||||
const createdRegion = await service.upsert({
|
||||
name: "North America",
|
||||
currency_code: "USD",
|
||||
countries: ["us", "ca"],
|
||||
})
|
||||
|
||||
const upserted = await service.upsert([
|
||||
{
|
||||
id: createdRegion.id,
|
||||
name: "Americas",
|
||||
currency_code: "USD",
|
||||
countries: ["us", "ca"],
|
||||
},
|
||||
{
|
||||
name: "Central America",
|
||||
currency_code: "MXN",
|
||||
countries: ["mx"],
|
||||
},
|
||||
])
|
||||
|
||||
expect(upserted).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
id: createdRegion.id,
|
||||
name: "Americas",
|
||||
currency_code: "usd",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
name: "Central America",
|
||||
currency_code: "mxn",
|
||||
}),
|
||||
])
|
||||
)
|
||||
})
|
||||
|
||||
it("should update the region successfully", async () => {
|
||||
const createdRegion = await service.create({
|
||||
name: "North America",
|
||||
currency_code: "USD",
|
||||
countries: ["us", "ca"],
|
||||
})
|
||||
|
||||
const shouldNotBeChangedRegion = await service.create({
|
||||
name: "Europe",
|
||||
currency_code: "EUR",
|
||||
countries: ["hr"],
|
||||
})
|
||||
|
||||
await service.update(createdRegion.id, {
|
||||
name: "Americas",
|
||||
currency_code: "MXN",
|
||||
countries: ["us", "mx"],
|
||||
})
|
||||
|
||||
const latestRegion = await service.retrieve(createdRegion.id, {
|
||||
relations: ["countries"],
|
||||
})
|
||||
|
||||
const shouldNotBeChangedRegionAfter = await service.retrieve(
|
||||
shouldNotBeChangedRegion.id,
|
||||
{
|
||||
relations: ["countries"],
|
||||
}
|
||||
)
|
||||
|
||||
expect(latestRegion).toMatchObject({
|
||||
id: createdRegion.id,
|
||||
name: "Americas",
|
||||
currency_code: "mxn",
|
||||
})
|
||||
|
||||
expect(
|
||||
shouldNotBeChangedRegionAfter.countries.map((c) => c.iso_2)
|
||||
).toEqual(["hr"])
|
||||
|
||||
expect(latestRegion.countries.map((c) => c.iso_2)).toEqual(
|
||||
expect.arrayContaining(["mx", "us"])
|
||||
)
|
||||
})
|
||||
|
||||
it("should update the region without affecting countries if countries are undefined", async () => {
|
||||
const createdRegion = await service.create({
|
||||
name: "North America",
|
||||
currency_code: "USD",
|
||||
countries: ["us", "ca"],
|
||||
})
|
||||
|
||||
await service.update(createdRegion.id, {
|
||||
name: "Americas",
|
||||
currency_code: "MXN",
|
||||
})
|
||||
|
||||
const updatedRegion = await service.retrieve(createdRegion.id, {
|
||||
relations: ["countries"],
|
||||
})
|
||||
|
||||
expect(updatedRegion).toMatchObject({
|
||||
id: createdRegion.id,
|
||||
name: "Americas",
|
||||
currency_code: "mxn",
|
||||
})
|
||||
|
||||
expect(updatedRegion.countries.map((c) => c.iso_2)).toEqual([
|
||||
"ca",
|
||||
"us",
|
||||
])
|
||||
})
|
||||
|
||||
it("should remove the countries in a region successfully", async () => {
|
||||
const createdRegion = await service.create({
|
||||
name: "North America",
|
||||
currency_code: "USD",
|
||||
countries: ["us", "ca"],
|
||||
})
|
||||
|
||||
await service.update(createdRegion.id, {
|
||||
name: "Americas",
|
||||
currency_code: "MXN",
|
||||
countries: [],
|
||||
})
|
||||
|
||||
const updatedRegion = await service.retrieve(createdRegion.id, {
|
||||
relations: ["countries"],
|
||||
})
|
||||
|
||||
expect(updatedRegion).toMatchObject({
|
||||
id: createdRegion.id,
|
||||
name: "Americas",
|
||||
currency_code: "mxn",
|
||||
})
|
||||
|
||||
expect(updatedRegion.countries).toHaveLength(0)
|
||||
})
|
||||
|
||||
it("should fail updating the region countries to non-existent ones", async () => {
|
||||
const createdRegion = await service.create({
|
||||
name: "North America",
|
||||
currency_code: "USD",
|
||||
countries: ["us", "ca"],
|
||||
})
|
||||
|
||||
await expect(
|
||||
service.update(
|
||||
{ id: createdRegion.id },
|
||||
{
|
||||
countries: ["us", "neverland"],
|
||||
}
|
||||
)
|
||||
).rejects.toThrowError('Countries with codes: "neverland" do not exist')
|
||||
})
|
||||
|
||||
it("should fail updating the region if there are duplicate countries", async () => {
|
||||
const createdRegion = await service.create({
|
||||
name: "North America",
|
||||
currency_code: "USD",
|
||||
countries: ["us", "ca"],
|
||||
})
|
||||
|
||||
await expect(
|
||||
service.update(
|
||||
{ id: createdRegion.id },
|
||||
{
|
||||
countries: ["us", "us"],
|
||||
}
|
||||
)
|
||||
).rejects.toThrowError(
|
||||
'Countries with codes: "us" are already assigned to a region'
|
||||
)
|
||||
})
|
||||
|
||||
it("should fail updating the region if country is already used", async () => {
|
||||
const [createdRegion] = await service.create([
|
||||
{
|
||||
name: "North America",
|
||||
currency_code: "USD",
|
||||
countries: ["us", "ca"],
|
||||
},
|
||||
{
|
||||
name: "Americas",
|
||||
currency_code: "USD",
|
||||
countries: ["mx"],
|
||||
},
|
||||
])
|
||||
|
||||
await expect(
|
||||
service.update(
|
||||
{ id: createdRegion.id },
|
||||
{
|
||||
countries: ["us", "mx"],
|
||||
}
|
||||
)
|
||||
).rejects.toThrowError(
|
||||
'Countries with codes: "mx" are already assigned to a region'
|
||||
)
|
||||
})
|
||||
|
||||
it("should unset the region ID on the country when deleting a region", async () => {
|
||||
const createdRegion = await service.create({
|
||||
name: "North America",
|
||||
currency_code: "USD",
|
||||
countries: ["us", "ca"],
|
||||
})
|
||||
|
||||
await service.delete(createdRegion.id)
|
||||
|
||||
const newRegion = await service.create({
|
||||
name: "North America",
|
||||
currency_code: "USD",
|
||||
countries: ["us", "ca"],
|
||||
})
|
||||
|
||||
const resp = await service.retrieve(newRegion.id, {
|
||||
relations: ["countries"],
|
||||
})
|
||||
|
||||
expect(resp.countries).toHaveLength(2)
|
||||
})
|
||||
})
|
||||
},
|
||||
})
|
||||
20
packages/modules/region/jest.config.js
Normal file
20
packages/modules/region/jest.config.js
Normal file
@@ -0,0 +1,20 @@
|
||||
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/"],
|
||||
}
|
||||
12
packages/modules/region/mikro-orm.config.dev.ts
Normal file
12
packages/modules/region/mikro-orm.config.dev.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import * as entities from "./src/models"
|
||||
import { TSMigrationGenerator } from "@medusajs/utils"
|
||||
|
||||
module.exports = {
|
||||
entities: Object.values(entities),
|
||||
schema: "public",
|
||||
clientUrl: "postgres://postgres@localhost/medusa-region",
|
||||
type: "postgresql",
|
||||
migrations: {
|
||||
generator: TSMigrationGenerator,
|
||||
},
|
||||
}
|
||||
61
packages/modules/region/package.json
Normal file
61
packages/modules/region/package.json
Normal file
@@ -0,0 +1,61 @@
|
||||
{
|
||||
"name": "@medusajs/region",
|
||||
"version": "0.1.1",
|
||||
"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 --passWithNoTests --bail --forceExit -- src",
|
||||
"test:integration": "jest --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.11",
|
||||
"@medusajs/types": "^1.11.16",
|
||||
"@medusajs/utils": "^1.11.9",
|
||||
"@mikro-orm/core": "5.9.7",
|
||||
"@mikro-orm/migrations": "5.9.7",
|
||||
"@mikro-orm/postgresql": "5.9.7",
|
||||
"awilix": "^8.0.0",
|
||||
"dotenv": "^16.4.5",
|
||||
"knex": "2.4.2"
|
||||
}
|
||||
}
|
||||
10
packages/modules/region/src/index.ts
Normal file
10
packages/modules/region/src/index.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
import {
|
||||
moduleDefinition,
|
||||
revertMigration,
|
||||
runMigrations,
|
||||
} from "./module-definition"
|
||||
|
||||
export default moduleDefinition
|
||||
export { revertMigration, runMigrations }
|
||||
|
||||
export * from "./initialize"
|
||||
34
packages/modules/region/src/initialize/index.ts
Normal file
34
packages/modules/region/src/initialize/index.ts
Normal 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]
|
||||
}
|
||||
36
packages/modules/region/src/joiner-config.ts
Normal file
36
packages/modules/region/src/joiner-config.ts
Normal 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
|
||||
35
packages/modules/region/src/loaders/connection.ts
Normal file
35
packages/modules/region/src/loaders/connection.ts
Normal 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
packages/modules/region/src/loaders/container.ts
Normal file
10
packages/modules/region/src/loaders/container.ts
Normal 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,
|
||||
})
|
||||
30
packages/modules/region/src/loaders/defaults.ts
Normal file
30
packages/modules/region/src/loaders/defaults.ts
Normal 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}`
|
||||
)
|
||||
}
|
||||
}
|
||||
4
packages/modules/region/src/loaders/index.ts
Normal file
4
packages/modules/region/src/loaders/index.ts
Normal file
@@ -0,0 +1,4 @@
|
||||
export * from "./connection"
|
||||
export * from "./container"
|
||||
export * from "./defaults"
|
||||
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -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;
|
||||
`)
|
||||
}
|
||||
}
|
||||
44
packages/modules/region/src/models/country.ts
Normal file
44
packages/modules/region/src/models/country.ts
Normal 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
|
||||
}
|
||||
2
packages/modules/region/src/models/index.ts
Normal file
2
packages/modules/region/src/models/index.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
export { default as Country } from "./country"
|
||||
export { default as Region } from "./region"
|
||||
72
packages/modules/region/src/models/region.ts
Normal file
72
packages/modules/region/src/models/region.ts
Normal 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")
|
||||
}
|
||||
}
|
||||
32
packages/modules/region/src/module-definition.ts
Normal file
32
packages/modules/region/src/module-definition.ts
Normal 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,
|
||||
}
|
||||
1
packages/modules/region/src/repositories/index.ts
Normal file
1
packages/modules/region/src/repositories/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export { MikroOrmBaseRepository as BaseRepository } from "@medusajs/utils"
|
||||
31
packages/modules/region/src/scripts/bin/run-seed.ts
Normal file
31
packages/modules/region/src/scripts/bin/run-seed.ts
Normal 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 })
|
||||
})()
|
||||
16
packages/modules/region/src/scripts/seed-utils.ts
Normal file
16
packages/modules/region/src/scripts/seed-utils.ts
Normal 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
|
||||
}
|
||||
2
packages/modules/region/src/services/index.ts
Normal file
2
packages/modules/region/src/services/index.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
export { default as RegionModuleService } from "./region-module";
|
||||
|
||||
335
packages/modules/region/src/services/region-module.ts
Normal file
335
packages/modules/region/src/services/region-module.ts
Normal 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
|
||||
}
|
||||
}
|
||||
21
packages/modules/region/src/types/index.ts
Normal file
21
packages/modules/region/src/types/index.ts
Normal 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 }
|
||||
37
packages/modules/region/tsconfig.json
Normal file
37
packages/modules/region/tsconfig.json
Normal file
@@ -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"
|
||||
]
|
||||
}
|
||||
8
packages/modules/region/tsconfig.spec.json
Normal file
8
packages/modules/region/tsconfig.spec.json
Normal file
@@ -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