chore(tests): Try to use the api integration tests for v2 (#6588)

Few things to keep in mind:
1. You need to set MEDUSA_FF_MEDUSA_V2 to true before running the tests to run with the v2 API
2. You can use the `breaking` function to differentiate between v1 and v2 differences. This can help us identify what was breaking pretty quickly afterwards
3. You will need to run specific tests for now instead of all if you want to target v2. I think that's fine though, as we don't really need these to run on every PR until we have feature parity (and by then, all tests would be both v1 and v2 compatible)


**note: Adrien** 
- add a new way to load modules only to run their loaders comparable to the way to run the migrations only
- improve tests runner to cleanup the data properly as well as re running all loaders and core defaults

Co-authored-by: Adrien de Peretti <25098370+adrien2p@users.noreply.github.com>
This commit is contained in:
Stevche RadevskiandAdrien de Peretti authored and GitHub committed 2024-03-07 08:05:43 +00:00
1 parent 000eb61e33
commit 12b035cb18
76 files changed
+659 -257

No files matched your search

@@ -1,8 +0,0 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`/admin/store POST /admin/store fails to update default currency if not in store currencies 1`] = `
Object {
"message": "Store does not have currency: eur",
"type": "invalid_data",
}
`;
+114 -106
View File
@@ -1,57 +1,69 @@
const { Store } = require("@medusajs/medusa") const {
const path = require("path") createAdminUser,
adminHeaders,
} = require("../../../helpers/create-admin-user")
const { breaking } = require("../../../helpers/breaking")
const { ModuleRegistrationName } = require("@medusajs/modules-sdk")
const { medusaIntegrationTestRunner } = require("medusa-test-utils")
const setupServer = require("../../../environment-helpers/setup-server") jest.setTimeout(90000)
const { useApi } = require("../../../environment-helpers/use-api")
const { initDb, useDb } = require("../../../environment-helpers/use-db")
const adminSeeder = require("../../../helpers/admin-seeder")
jest.setTimeout(30000)
medusaIntegrationTestRunner({
testSuite: ({ dbConnection, getContainer, api }) => {
describe("/admin/store", () => { describe("/admin/store", () => {
let dbConnection let dbStore
const cwd = path.resolve(path.join(__dirname, "..", "..")) let container
beforeAll(async () => { // Note: The tests rely on the loader running and populating clean data before and after the test, so we have to do this in a beforeEach
dbConnection = await initDb({ cwd }) beforeEach(async () => {
container = getContainer()
await createAdminUser(dbConnection, adminHeaders, container)
await breaking(
async () => {
const { Store } = require("@medusajs/medusa/dist/models/store")
const manager = dbConnection.manager
dbStore = await manager.findOne(Store, {
where: { name: "Medusa Store" },
}) })
await manager.query(
afterAll(async () => { `INSERT INTO store_currencies (store_id, currency_code)
const db = useDb() VALUES ('${dbStore.id}', 'dkk')`
await db.shutdown() )
},
async () => {
const service = container.resolve(ModuleRegistrationName.STORE)
dbStore = await service.create({
supported_currency_codes: ["usd", "dkk"],
default_currency_code: "usd",
default_sales_channel_id: "sc_12345",
})
}
)
}) })
describe("Store creation", () => { describe("Store creation", () => {
let medusaProcess
beforeEach(async () => {
await adminSeeder(dbConnection)
medusaProcess = await setupServer({ cwd })
})
afterEach(async () => {
const db = useDb()
await db.teardown({ forceDelete: ["store"] })
await medusaProcess.kill()
})
it("has created store with default currency", async () => { it("has created store with default currency", async () => {
const api = useApi() const store = await breaking(
() =>
api.get("/admin/store", adminHeaders).then((r) => r.data.store),
() =>
api
.get("/admin/stores", adminHeaders)
.then((r) => r.data.stores[0])
)
const response = await api.get("/admin/store", { expect(store).toEqual(
headers: { "x-medusa-access-token": "test_token " },
})
expect(response.status).toEqual(200)
expect(response.data.store).toEqual(
expect.objectContaining({ expect.objectContaining({
id: expect.any(String), id: expect.any(String),
name: "Medusa Store",
default_currency_code: "usd",
default_sales_channel_id: expect.any(String), default_sales_channel_id: expect.any(String),
...breaking(
() => ({
default_sales_channel: expect.objectContaining({ default_sales_channel: expect.objectContaining({
id: expect.any(String), id: expect.any(String),
}), }),
name: "Medusa Store",
currencies: expect.arrayContaining([ currencies: expect.arrayContaining([
expect.objectContaining({ expect.objectContaining({
code: "usd", code: "usd",
@@ -59,7 +71,11 @@ describe("/admin/store", () => {
]), ]),
modules: expect.any(Array), modules: expect.any(Array),
feature_flags: expect.any(Array), feature_flags: expect.any(Array),
default_currency_code: "usd", }),
() => ({
supported_currency_codes: ["usd", "dkk"],
})
),
created_at: expect.any(String), created_at: expect.any(String),
updated_at: expect.any(String), updated_at: expect.any(String),
}) })
@@ -68,84 +84,67 @@ describe("/admin/store", () => {
}) })
describe("POST /admin/store", () => { describe("POST /admin/store", () => {
let medusaProcess
beforeEach(async () => {
await adminSeeder(dbConnection)
medusaProcess = await setupServer({ cwd })
const manager = dbConnection.manager
const store = await manager.findOne(Store, {
where: { name: "Medusa Store" },
})
await manager.query(
`INSERT INTO store_currencies (store_id, currency_code) VALUES ('${store.id}', 'dkk')`
)
})
afterEach(async () => {
const db = useDb()
await db.teardown({ forceDelete: ["store"] })
await medusaProcess.kill()
})
it("fails to update default currency if not in store currencies", async () => { it("fails to update default currency if not in store currencies", async () => {
const api = useApi()
try { try {
await api.post( await api.post(
"/admin/store", breaking(
() => "/admin/store",
() => `/admin/stores/${dbStore.id}`
),
{ {
default_currency_code: "eur", default_currency_code: "eur",
}, },
{ adminHeaders
headers: { "x-medusa-access-token": "test_token " },
}
) )
} catch (e) { } catch (e) {
expect(e.response.data).toMatchSnapshot({ expect(e.response.data).toEqual(
expect.objectContaining({
type: "invalid_data", type: "invalid_data",
message: "Store does not have currency: eur", message: "Store does not have currency: eur",
}) })
)
expect(e.response.status).toBe(400) expect(e.response.status).toBe(400)
} }
}) })
it("fails to remove default currency from currencies without replacing it", async () => { it("fails to remove default currency from currencies without replacing it", async () => {
const api = useApi()
try { try {
await api.post( await api.post(
"/admin/store", breaking(
{ () => "/admin/store",
() => `/admin/stores/${dbStore.id}`
),
breaking(
() => ({
currencies: ["usd"], currencies: ["usd"],
}, }),
{ () => ({ supported_currency_codes: ["dkk"] })
headers: { "x-medusa-access-token": "test_token " }, ),
} adminHeaders
) )
} catch (e) { } catch (e) {
expect(e.response.data).toMatchSnapshot({ expect(e.response.data).toEqual(
expect.objectContaining({
type: "invalid_data", type: "invalid_data",
message: message:
"You are not allowed to remove default currency from store currencies without replacing it as well", "You are not allowed to remove default currency from store currencies without replacing it as well",
}) })
)
expect(e.response.status).toBe(400) expect(e.response.status).toBe(400)
} }
}) })
it("successfully updates default currency code", async () => { it("successfully updates default currency code", async () => {
const api = useApi()
const response = await api const response = await api
.post( .post(
"/admin/store", breaking(
() => "/admin/store",
() => `/admin/stores/${dbStore.id}`
),
{ {
default_currency_code: "dkk", default_currency_code: "dkk",
}, },
{ adminHeaders
headers: { "x-medusa-access-token": "test_token " },
}
) )
.catch((err) => console.log(err)) .catch((err) => console.log(err))
@@ -154,15 +153,6 @@ describe("/admin/store", () => {
expect.objectContaining({ expect.objectContaining({
id: expect.any(String), id: expect.any(String),
name: "Medusa Store", name: "Medusa Store",
default_sales_channel_id: expect.any(String),
currencies: expect.arrayContaining([
expect.objectContaining({
code: "usd",
}),
expect.objectContaining({
code: "dkk",
}),
]),
default_currency_code: "dkk", default_currency_code: "dkk",
created_at: expect.any(String), created_at: expect.any(String),
updated_at: expect.any(String), updated_at: expect.any(String),
@@ -171,17 +161,19 @@ describe("/admin/store", () => {
}) })
it("successfully updates default currency and store currencies", async () => { it("successfully updates default currency and store currencies", async () => {
const api = useApi()
const response = await api.post( const response = await api.post(
"/admin/store", breaking(
() => "/admin/store",
() => `/admin/stores/${dbStore.id}`
),
{ {
default_currency_code: "jpy", default_currency_code: "jpy",
currencies: ["jpy", "usd"], ...breaking(
() => ({ currencies: ["jpy", "usd"] }),
() => ({ supported_currency_codes: ["jpy", "usd"] })
),
}, },
{ adminHeaders
headers: { "x-medusa-access-token": "test_token " },
}
) )
expect(response.status).toEqual(200) expect(response.status).toEqual(200)
@@ -190,6 +182,8 @@ describe("/admin/store", () => {
id: expect.any(String), id: expect.any(String),
name: "Medusa Store", name: "Medusa Store",
default_sales_channel_id: expect.any(String), default_sales_channel_id: expect.any(String),
...breaking(
() => ({
currencies: expect.arrayContaining([ currencies: expect.arrayContaining([
expect.objectContaining({ expect.objectContaining({
code: "jpy", code: "jpy",
@@ -198,6 +192,9 @@ describe("/admin/store", () => {
code: "usd", code: "usd",
}), }),
]), ]),
}),
() => ({ supported_currency_codes: ["jpy", "usd"] })
),
default_currency_code: "jpy", default_currency_code: "jpy",
created_at: expect.any(String), created_at: expect.any(String),
updated_at: expect.any(String), updated_at: expect.any(String),
@@ -206,16 +203,20 @@ describe("/admin/store", () => {
}) })
it("successfully updates and store currencies", async () => { it("successfully updates and store currencies", async () => {
const api = useApi()
const response = await api.post( const response = await api.post(
"/admin/store", breaking(
{ () => "/admin/store",
() => `/admin/stores/${dbStore.id}`
),
breaking(
() => ({
currencies: ["jpy", "usd"], currencies: ["jpy", "usd"],
}, }),
{ () => ({
headers: { "x-medusa-access-token": "test_token " }, supported_currency_codes: ["jpy", "usd"],
} })
),
adminHeaders
) )
expect(response.status).toEqual(200) expect(response.status).toEqual(200)
@@ -224,6 +225,8 @@ describe("/admin/store", () => {
id: expect.any(String), id: expect.any(String),
default_sales_channel_id: expect.any(String), default_sales_channel_id: expect.any(String),
name: "Medusa Store", name: "Medusa Store",
...breaking(
() => ({
currencies: expect.arrayContaining([ currencies: expect.arrayContaining([
expect.objectContaining({ expect.objectContaining({
code: "jpy", code: "jpy",
@@ -232,6 +235,9 @@ describe("/admin/store", () => {
code: "usd", code: "usd",
}), }),
]), ]),
}),
() => ({ supported_currency_codes: ["jpy", "usd"] })
),
default_currency_code: "usd", default_currency_code: "usd",
created_at: expect.any(String), created_at: expect.any(String),
updated_at: expect.any(String), updated_at: expect.any(String),
@@ -240,3 +246,5 @@ describe("/admin/store", () => {
}) })
}) })
}) })
},
})
+60 -2
View File
@@ -1,18 +1,25 @@
const { Modules } = require("@medusajs/modules-sdk")
const DB_HOST = process.env.DB_HOST const DB_HOST = process.env.DB_HOST
const DB_USERNAME = process.env.DB_USERNAME const DB_USERNAME = process.env.DB_USERNAME
const DB_PASSWORD = process.env.DB_PASSWORD const DB_PASSWORD = process.env.DB_PASSWORD
const DB_NAME = process.env.DB_TEMP_NAME const DB_NAME = process.env.DB_TEMP_NAME
const DB_URL = `postgres://${DB_USERNAME}:${DB_PASSWORD}@${DB_HOST}/${DB_NAME}`
const redisUrl = process.env.REDIS_URL || "redis://localhost:6379" const redisUrl = process.env.REDIS_URL
const cacheTTL = process.env.CACHE_TTL ?? 15 const cacheTTL = process.env.CACHE_TTL ?? 15
const enableResponseCompression = const enableResponseCompression =
process.env.ENABLE_RESPONSE_COMPRESSION || true process.env.ENABLE_RESPONSE_COMPRESSION || true
const enableMedusaV2 = process.env.MEDUSA_FF_MEDUSA_V2 == "true"
process.env.POSTGRES_URL = DB_URL
process.env.LOG_LEVEL = "error"
module.exports = { module.exports = {
plugins: [], plugins: [],
projectConfig: { projectConfig: {
redis_url: redisUrl, redis_url: redisUrl,
database_url: `postgres://${DB_USERNAME}:${DB_PASSWORD}@${DB_HOST}/${DB_NAME}`, database_url: DB_URL,
database_type: "postgres", database_type: "postgres",
jwt_secret: "test", jwt_secret: "test",
cookie_secret: "test", cookie_secret: "test",
@@ -20,11 +27,62 @@ module.exports = {
enabled: enableResponseCompression, enabled: enableResponseCompression,
}, },
}, },
featureFlags: {
medusa_v2: enableMedusaV2,
},
modules: { modules: {
cacheService: { cacheService: {
resolve: "@medusajs/cache-inmemory", resolve: "@medusajs/cache-inmemory",
options: { ttl: cacheTTL }, options: { ttl: cacheTTL },
}, },
workflows: true, workflows: true,
// We don't want to load the modules if v2 is not enabled, as they run data operations and migrations on load.
...(enableMedusaV2
? {
[Modules.AUTH]: {
scope: "internal",
resources: "shared",
resolve: "@medusajs/auth",
options: {
providers: [
{
name: "emailpass",
scopes: {
admin: {},
store: {},
},
},
],
},
},
[Modules.USER]: {
scope: "internal",
resources: "shared",
resolve: "@medusajs/user",
options: {
jwt_secret: "test",
},
},
[Modules.CACHE]: {
resolve: "@medusajs/cache-inmemory",
options: { ttl: 0 }, // Cache disabled
},
[Modules.STOCK_LOCATION]: true,
[Modules.INVENTORY]: true,
[Modules.PRODUCT]: true,
[Modules.PRICING]: true,
[Modules.PROMOTION]: true,
[Modules.CUSTOMER]: true,
[Modules.SALES_CHANNEL]: true,
[Modules.CART]: true,
[Modules.WORKFLOW_ENGINE]: true,
[Modules.REGION]: true,
[Modules.API_KEY]: true,
[Modules.STORE]: true,
[Modules.TAX]: true,
[Modules.CURRENCY]: true,
[Modules.PAYMENT]: true,
}
: {}),
}, },
} }
+16 -1
View File
@@ -5,16 +5,31 @@
"license": "MIT", "license": "MIT",
"private": true, "private": true,
"scripts": { "scripts": {
"test:integration": "jest --silent=false --maxWorkers=50% --bail --detectOpenHandles --forceExit --logHeapUsage", "test:integration": "jest --silent --maxWorkers=50% --bail --detectOpenHandles --forceExit --logHeapUsage",
"build": "babel src -d dist --extensions \".ts,.js\"" "build": "babel src -d dist --extensions \".ts,.js\""
}, },
"dependencies": { "dependencies": {
"@medusajs/api-key": "workspace:^",
"@medusajs/auth": "workspace:*",
"@medusajs/cache-inmemory": "workspace:*", "@medusajs/cache-inmemory": "workspace:*",
"@medusajs/customer": "workspace:^",
"@medusajs/event-bus-local": "workspace:*", "@medusajs/event-bus-local": "workspace:*",
"@medusajs/inventory": "workspace:^",
"@medusajs/medusa": "workspace:*", "@medusajs/medusa": "workspace:*",
"@medusajs/modules-sdk": "workspace:^",
"@medusajs/pricing": "workspace:^",
"@medusajs/product": "workspace:^",
"@medusajs/promotion": "workspace:^",
"@medusajs/region": "workspace:^",
"@medusajs/store": "workspace:^",
"@medusajs/tax": "workspace:^",
"@medusajs/user": "workspace:^",
"@medusajs/utils": "workspace:^",
"@medusajs/workflow-engine-inmemory": "workspace:*", "@medusajs/workflow-engine-inmemory": "workspace:*",
"faker": "^5.5.3", "faker": "^5.5.3",
"medusa-fulfillment-webshipper": "workspace:*",
"medusa-interfaces": "workspace:*", "medusa-interfaces": "workspace:*",
"medusa-plugin-sendgrid": "workspace:*",
"pg": "^8.11.0", "pg": "^8.11.0",
"typeorm": "^0.3.16" "typeorm": "^0.3.16"
}, },
+10
View File
@@ -0,0 +1,10 @@
export const breaking = (
v1Fn: (() => any) | null,
v2Fn?: (() => any) | null
) => {
if (process.env.MEDUSA_FF_MEDUSA_V2 === "true") {
return v2Fn?.()
}
return v1Fn?.()
}
@@ -0,0 +1,35 @@
import { ModuleRegistrationName } from "@medusajs/modules-sdk"
import { IAuthModuleService } from "@medusajs/types"
import jwt from "jsonwebtoken"
import { getContainer } from "../environment-helpers/use-container"
import adminSeeder from "./admin-seeder"
export const adminHeaders = {
headers: { "x-medusa-access-token": "test_token" },
}
export const createAdminUser = async (
dbConnection,
adminHeaders,
container?
) => {
await adminSeeder(dbConnection)
const appContainer = container ?? getContainer()!
const authModule: IAuthModuleService = appContainer.resolve(
ModuleRegistrationName.AUTH
)
if (authModule) {
const authUser = await authModule.create({
provider: "emailpass",
entity_id: "admin@medusa.js",
scope: "admin",
app_metadata: {
user_id: "admin_user",
},
})
const token = jwt.sign(authUser, "test")
adminHeaders.headers["authorization"] = `Bearer ${token}`
}
}
@@ -1,7 +1,7 @@
import { ApiKeyType } from "@medusajs/utils" import { ApiKeyType } from "@medusajs/utils"
import { IRegionModuleService } from "@medusajs/types" import { IRegionModuleService } from "@medusajs/types"
import { ModuleRegistrationName } from "@medusajs/modules-sdk" import { ModuleRegistrationName } from "@medusajs/modules-sdk"
import { createAdminUser } from "../../../helpers/create-admin-user" import { createAdminUser } from "../../../../helpers/create-admin-user"
import { medusaIntegrationTestRunner } from "medusa-test-utils" import { medusaIntegrationTestRunner } from "medusa-test-utils"
jest.setTimeout(50000) jest.setTimeout(50000)
@@ -1,4 +1,4 @@
import { createAdminUser } from "../../../helpers/create-admin-user" import { createAdminUser } from "../../../../helpers/create-admin-user"
import { medusaIntegrationTestRunner } from "medusa-test-utils" import { medusaIntegrationTestRunner } from "medusa-test-utils"
jest.setTimeout(50000) jest.setTimeout(50000)
@@ -1,6 +1,6 @@
import { ICustomerModuleService } from "@medusajs/types" import { ICustomerModuleService } from "@medusajs/types"
import { ModuleRegistrationName } from "@medusajs/modules-sdk" import { ModuleRegistrationName } from "@medusajs/modules-sdk"
import { createAdminUser } from "../../../helpers/create-admin-user" import { createAdminUser } from "../../../../helpers/create-admin-user"
import { medusaIntegrationTestRunner } from "medusa-test-utils" import { medusaIntegrationTestRunner } from "medusa-test-utils"
jest.setTimeout(50000) jest.setTimeout(50000)
@@ -1,6 +1,6 @@
import { ICustomerModuleService } from "@medusajs/types" import { ICustomerModuleService } from "@medusajs/types"
import { ModuleRegistrationName } from "@medusajs/modules-sdk" import { ModuleRegistrationName } from "@medusajs/modules-sdk"
import { createAdminUser } from "../../../helpers/create-admin-user" import { createAdminUser } from "../../../../helpers/create-admin-user"
import { medusaIntegrationTestRunner } from "medusa-test-utils" import { medusaIntegrationTestRunner } from "medusa-test-utils"
jest.setTimeout(50000) jest.setTimeout(50000)
@@ -1,6 +1,6 @@
import { ICustomerModuleService } from "@medusajs/types" import { ICustomerModuleService } from "@medusajs/types"
import { ModuleRegistrationName } from "@medusajs/modules-sdk" import { ModuleRegistrationName } from "@medusajs/modules-sdk"
import { createAdminUser } from "../../../helpers/create-admin-user" import { createAdminUser } from "../../../../helpers/create-admin-user"
import { medusaIntegrationTestRunner } from "medusa-test-utils" import { medusaIntegrationTestRunner } from "medusa-test-utils"
jest.setTimeout(50000) jest.setTimeout(50000)
@@ -1,6 +1,6 @@
import { ICustomerModuleService } from "@medusajs/types" import { ICustomerModuleService } from "@medusajs/types"
import { ModuleRegistrationName } from "@medusajs/modules-sdk" import { ModuleRegistrationName } from "@medusajs/modules-sdk"
import { createAdminUser } from "../../../helpers/create-admin-user" import { createAdminUser } from "../../../../helpers/create-admin-user"
import { medusaIntegrationTestRunner } from "medusa-test-utils" import { medusaIntegrationTestRunner } from "medusa-test-utils"
jest.setTimeout(50000) jest.setTimeout(50000)
@@ -1,6 +1,6 @@
import { ICustomerModuleService } from "@medusajs/types" import { ICustomerModuleService } from "@medusajs/types"
import { ModuleRegistrationName } from "@medusajs/modules-sdk" import { ModuleRegistrationName } from "@medusajs/modules-sdk"
import { createAdminUser } from "../../../helpers/create-admin-user" import { createAdminUser } from "../../../../helpers/create-admin-user"
import { medusaIntegrationTestRunner } from "medusa-test-utils" import { medusaIntegrationTestRunner } from "medusa-test-utils"
jest.setTimeout(50000) jest.setTimeout(50000)
@@ -1,6 +1,6 @@
import { ICustomerModuleService } from "@medusajs/types" import { ICustomerModuleService } from "@medusajs/types"
import { ModuleRegistrationName } from "@medusajs/modules-sdk" import { ModuleRegistrationName } from "@medusajs/modules-sdk"
import { createAdminUser } from "../../../helpers/create-admin-user" import { createAdminUser } from "../../../../helpers/create-admin-user"
import { medusaIntegrationTestRunner } from "medusa-test-utils" import { medusaIntegrationTestRunner } from "medusa-test-utils"
jest.setTimeout(50000) jest.setTimeout(50000)
@@ -1,6 +1,6 @@
import { ICustomerModuleService } from "@medusajs/types" import { ICustomerModuleService } from "@medusajs/types"
import { ModuleRegistrationName } from "@medusajs/modules-sdk" import { ModuleRegistrationName } from "@medusajs/modules-sdk"
import { createAdminUser } from "../../../helpers/create-admin-user" import { createAdminUser } from "../../../../helpers/create-admin-user"
import { medusaIntegrationTestRunner } from "medusa-test-utils" import { medusaIntegrationTestRunner } from "medusa-test-utils"
jest.setTimeout(50000) jest.setTimeout(50000)
@@ -1,6 +1,6 @@
import { ICustomerModuleService } from "@medusajs/types" import { ICustomerModuleService } from "@medusajs/types"
import { ModuleRegistrationName } from "@medusajs/modules-sdk" import { ModuleRegistrationName } from "@medusajs/modules-sdk"
import { createAdminUser } from "../../../helpers/create-admin-user" import { createAdminUser } from "../../../../helpers/create-admin-user"
import { medusaIntegrationTestRunner } from "medusa-test-utils" import { medusaIntegrationTestRunner } from "medusa-test-utils"
jest.setTimeout(50000) jest.setTimeout(50000)
@@ -1,6 +1,6 @@
import { ICustomerModuleService } from "@medusajs/types" import { ICustomerModuleService } from "@medusajs/types"
import { ModuleRegistrationName } from "@medusajs/modules-sdk" import { ModuleRegistrationName } from "@medusajs/modules-sdk"
import { createAdminUser } from "../../../helpers/create-admin-user" import { createAdminUser } from "../../../../helpers/create-admin-user"
import { medusaIntegrationTestRunner } from "medusa-test-utils" import { medusaIntegrationTestRunner } from "medusa-test-utils"
jest.setTimeout(50000) jest.setTimeout(50000)
@@ -1,6 +1,6 @@
import { ICustomerModuleService } from "@medusajs/types" import { ICustomerModuleService } from "@medusajs/types"
import { ModuleRegistrationName } from "@medusajs/modules-sdk" import { ModuleRegistrationName } from "@medusajs/modules-sdk"
import { createAdminUser } from "../../../helpers/create-admin-user" import { createAdminUser } from "../../../../helpers/create-admin-user"
import { medusaIntegrationTestRunner } from "medusa-test-utils" import { medusaIntegrationTestRunner } from "medusa-test-utils"
jest.setTimeout(50000) jest.setTimeout(50000)
@@ -1,6 +1,6 @@
import { ICustomerModuleService } from "@medusajs/types" import { ICustomerModuleService } from "@medusajs/types"
import { ModuleRegistrationName } from "@medusajs/modules-sdk" import { ModuleRegistrationName } from "@medusajs/modules-sdk"
import { createAdminUser } from "../../../helpers/create-admin-user" import { createAdminUser } from "../../../../helpers/create-admin-user"
import { medusaIntegrationTestRunner } from "medusa-test-utils" import { medusaIntegrationTestRunner } from "medusa-test-utils"
jest.setTimeout(50000) jest.setTimeout(50000)
@@ -1,6 +1,6 @@
import { ICustomerModuleService } from "@medusajs/types" import { ICustomerModuleService } from "@medusajs/types"
import { ModuleRegistrationName } from "@medusajs/modules-sdk" import { ModuleRegistrationName } from "@medusajs/modules-sdk"
import { createAdminUser } from "../../../helpers/create-admin-user" import { createAdminUser } from "../../../../helpers/create-admin-user"
import { medusaIntegrationTestRunner } from "medusa-test-utils" import { medusaIntegrationTestRunner } from "medusa-test-utils"
jest.setTimeout(50000) jest.setTimeout(50000)
@@ -1,6 +1,6 @@
import { ICustomerModuleService } from "@medusajs/types" import { ICustomerModuleService } from "@medusajs/types"
import { ModuleRegistrationName } from "@medusajs/modules-sdk" import { ModuleRegistrationName } from "@medusajs/modules-sdk"
import { createAdminUser } from "../../../helpers/create-admin-user" import { createAdminUser } from "../../../../helpers/create-admin-user"
import { medusaIntegrationTestRunner } from "medusa-test-utils" import { medusaIntegrationTestRunner } from "medusa-test-utils"
jest.setTimeout(50000) jest.setTimeout(50000)
@@ -1,6 +1,6 @@
import { ICustomerModuleService } from "@medusajs/types" import { ICustomerModuleService } from "@medusajs/types"
import { ModuleRegistrationName } from "@medusajs/modules-sdk" import { ModuleRegistrationName } from "@medusajs/modules-sdk"
import { createAdminUser } from "../../../helpers/create-admin-user" import { createAdminUser } from "../../../../helpers/create-admin-user"
import { medusaIntegrationTestRunner } from "medusa-test-utils" import { medusaIntegrationTestRunner } from "medusa-test-utils"
jest.setTimeout(50000) jest.setTimeout(50000)
@@ -1,6 +1,6 @@
import { ICustomerModuleService } from "@medusajs/types" import { ICustomerModuleService } from "@medusajs/types"
import { ModuleRegistrationName } from "@medusajs/modules-sdk" import { ModuleRegistrationName } from "@medusajs/modules-sdk"
import { createAdminUser } from "../../../helpers/create-admin-user" import { createAdminUser } from "../../../../helpers/create-admin-user"
import { medusaIntegrationTestRunner } from "medusa-test-utils" import { medusaIntegrationTestRunner } from "medusa-test-utils"
jest.setTimeout(50000) jest.setTimeout(50000)
@@ -1,6 +1,6 @@
import { ICustomerModuleService } from "@medusajs/types" import { ICustomerModuleService } from "@medusajs/types"
import { ModuleRegistrationName } from "@medusajs/modules-sdk" import { ModuleRegistrationName } from "@medusajs/modules-sdk"
import { createAdminUser } from "../../../helpers/create-admin-user" import { createAdminUser } from "../../../../helpers/create-admin-user"
import { medusaIntegrationTestRunner } from "medusa-test-utils" import { medusaIntegrationTestRunner } from "medusa-test-utils"
jest.setTimeout(50000) jest.setTimeout(50000)
@@ -1,6 +1,6 @@
import { IUserModuleService } from "@medusajs/types" import { IUserModuleService } from "@medusajs/types"
import { ModuleRegistrationName } from "@medusajs/modules-sdk" import { ModuleRegistrationName } from "@medusajs/modules-sdk"
import { createAdminUser } from "../../helpers/create-admin-user" import { createAdminUser } from "../../../helpers/create-admin-user"
import { medusaIntegrationTestRunner } from "medusa-test-utils" import { medusaIntegrationTestRunner } from "medusa-test-utils"
jest.setTimeout(50000) jest.setTimeout(50000)
@@ -1,4 +1,4 @@
import { createAdminUser } from "../../helpers/create-admin-user" import { createAdminUser } from "../../../helpers/create-admin-user"
import { medusaIntegrationTestRunner } from "medusa-test-utils" import { medusaIntegrationTestRunner } from "medusa-test-utils"
jest.setTimeout(50000) jest.setTimeout(50000)
@@ -1,6 +1,6 @@
import { IUserModuleService } from "@medusajs/types" import { IUserModuleService } from "@medusajs/types"
import { ModuleRegistrationName } from "@medusajs/modules-sdk" import { ModuleRegistrationName } from "@medusajs/modules-sdk"
import { createAdminUser } from "../../helpers/create-admin-user" import { createAdminUser } from "../../../helpers/create-admin-user"
import { medusaIntegrationTestRunner } from "medusa-test-utils" import { medusaIntegrationTestRunner } from "medusa-test-utils"
jest.setTimeout(50000) jest.setTimeout(50000)
@@ -1,6 +1,6 @@
import { IUserModuleService } from "@medusajs/types" import { IUserModuleService } from "@medusajs/types"
import { ModuleRegistrationName } from "@medusajs/modules-sdk" import { ModuleRegistrationName } from "@medusajs/modules-sdk"
import { createAdminUser } from "../../helpers/create-admin-user" import { createAdminUser } from "../../../helpers/create-admin-user"
import { medusaIntegrationTestRunner } from "medusa-test-utils" import { medusaIntegrationTestRunner } from "medusa-test-utils"
jest.setTimeout(50000) jest.setTimeout(50000)
@@ -1,6 +1,6 @@
import { IUserModuleService } from "@medusajs/types" import { IUserModuleService } from "@medusajs/types"
import { ModuleRegistrationName } from "@medusajs/modules-sdk" import { ModuleRegistrationName } from "@medusajs/modules-sdk"
import { createAdminUser } from "../../helpers/create-admin-user" import { createAdminUser } from "../../../helpers/create-admin-user"
import { medusaIntegrationTestRunner } from "medusa-test-utils" import { medusaIntegrationTestRunner } from "medusa-test-utils"
jest.setTimeout(50000) jest.setTimeout(50000)
@@ -1,6 +1,6 @@
import { IUserModuleService } from "@medusajs/types" import { IUserModuleService } from "@medusajs/types"
import { ModuleRegistrationName } from "@medusajs/modules-sdk" import { ModuleRegistrationName } from "@medusajs/modules-sdk"
import { createAdminUser } from "../../helpers/create-admin-user" import { createAdminUser } from "../../../helpers/create-admin-user"
import { medusaIntegrationTestRunner } from "medusa-test-utils" import { medusaIntegrationTestRunner } from "medusa-test-utils"
jest.setTimeout(50000) jest.setTimeout(50000)
@@ -56,7 +56,22 @@ medusaIntegrationTestRunner({
} }
jest.spyOn(MedusaModule, "getLoadedModules").mockImplementation((() => { jest.spyOn(MedusaModule, "getLoadedModules").mockImplementation((() => {
return [{ moduleA: [{}] }, { moduleB: [{}] }] return [
{
moduleA: {
__definition: {
key: "moduleA",
},
},
},
{
moduleB: {
__definition: {
key: "moduleB",
},
},
},
]
}) as any) }) as any)
await runMigrations({ options: dbConfig }, linkDefinition) await runMigrations({ options: dbConfig }, linkDefinition)
@@ -1,4 +1,4 @@
import { createAdminUser } from "../../../helpers/create-admin-user" import { createAdminUser } from "../../../../helpers/create-admin-user"
import { medusaIntegrationTestRunner } from "medusa-test-utils/dist" import { medusaIntegrationTestRunner } from "medusa-test-utils/dist"
jest.setTimeout(50000) jest.setTimeout(50000)
@@ -1,6 +1,6 @@
import { IPromotionModuleService } from "@medusajs/types" import { IPromotionModuleService } from "@medusajs/types"
import { ModuleRegistrationName } from "@medusajs/modules-sdk" import { ModuleRegistrationName } from "@medusajs/modules-sdk"
import { createAdminUser } from "../../../helpers/create-admin-user" import { createAdminUser } from "../../../../helpers/create-admin-user"
import { medusaIntegrationTestRunner } from "medusa-test-utils" import { medusaIntegrationTestRunner } from "medusa-test-utils"
jest.setTimeout(50000) jest.setTimeout(50000)
@@ -1,7 +1,7 @@
import { IPromotionModuleService } from "@medusajs/types" import { IPromotionModuleService } from "@medusajs/types"
import { ModuleRegistrationName } from "@medusajs/modules-sdk" import { ModuleRegistrationName } from "@medusajs/modules-sdk"
import { PromotionType } from "@medusajs/utils" import { PromotionType } from "@medusajs/utils"
import { createAdminUser } from "../../../helpers/create-admin-user" import { createAdminUser } from "../../../../helpers/create-admin-user"
import { medusaIntegrationTestRunner } from "medusa-test-utils" import { medusaIntegrationTestRunner } from "medusa-test-utils"
jest.setTimeout(50000) jest.setTimeout(50000)
@@ -1,6 +1,6 @@
import { IPromotionModuleService } from "@medusajs/types" import { IPromotionModuleService } from "@medusajs/types"
import { ModuleRegistrationName } from "@medusajs/modules-sdk" import { ModuleRegistrationName } from "@medusajs/modules-sdk"
import { createAdminUser } from "../../../helpers/create-admin-user" import { createAdminUser } from "../../../../helpers/create-admin-user"
import { medusaIntegrationTestRunner } from "medusa-test-utils" import { medusaIntegrationTestRunner } from "medusa-test-utils"
jest.setTimeout(50000) jest.setTimeout(50000)
@@ -1,6 +1,6 @@
import { IPromotionModuleService } from "@medusajs/types" import { IPromotionModuleService } from "@medusajs/types"
import { ModuleRegistrationName } from "@medusajs/modules-sdk" import { ModuleRegistrationName } from "@medusajs/modules-sdk"
import { createAdminUser } from "../../../helpers/create-admin-user" import { createAdminUser } from "../../../../helpers/create-admin-user"
import { medusaIntegrationTestRunner } from "medusa-test-utils" import { medusaIntegrationTestRunner } from "medusa-test-utils"
jest.setTimeout(50000) jest.setTimeout(50000)
@@ -1,7 +1,7 @@
import { ModuleRegistrationName } from "@medusajs/modules-sdk" import { ModuleRegistrationName } from "@medusajs/modules-sdk"
import { IPromotionModuleService } from "@medusajs/types" import { IPromotionModuleService } from "@medusajs/types"
import { CampaignBudgetType } from "@medusajs/utils" import { CampaignBudgetType } from "@medusajs/utils"
import { createAdminUser } from "../../../helpers/create-admin-user" import { createAdminUser } from "../../../../helpers/create-admin-user"
import { medusaIntegrationTestRunner } from "medusa-test-utils" import { medusaIntegrationTestRunner } from "medusa-test-utils"
jest.setTimeout(50000) jest.setTimeout(50000)
@@ -1,7 +1,7 @@
import { IPromotionModuleService } from "@medusajs/types" import { IPromotionModuleService } from "@medusajs/types"
import { ModuleRegistrationName } from "@medusajs/modules-sdk" import { ModuleRegistrationName } from "@medusajs/modules-sdk"
import { PromotionType } from "@medusajs/utils" import { PromotionType } from "@medusajs/utils"
import { createAdminUser } from "../../../helpers/create-admin-user" import { createAdminUser } from "../../../../helpers/create-admin-user"
import { medusaIntegrationTestRunner } from "medusa-test-utils" import { medusaIntegrationTestRunner } from "medusa-test-utils"
jest.setTimeout(50000) jest.setTimeout(50000)
@@ -1,7 +1,7 @@
import { ModuleRegistrationName } from "@medusajs/modules-sdk" import { ModuleRegistrationName } from "@medusajs/modules-sdk"
import { IPromotionModuleService } from "@medusajs/types" import { IPromotionModuleService } from "@medusajs/types"
import { CampaignBudgetType } from "@medusajs/utils" import { CampaignBudgetType } from "@medusajs/utils"
import { createAdminUser } from "../../../helpers/create-admin-user" import { createAdminUser } from "../../../../helpers/create-admin-user"
import { medusaIntegrationTestRunner } from "medusa-test-utils" import { medusaIntegrationTestRunner } from "medusa-test-utils"
jest.setTimeout(50000) jest.setTimeout(50000)
@@ -1,7 +1,7 @@
import { IPromotionModuleService } from "@medusajs/types" import { IPromotionModuleService } from "@medusajs/types"
import { ModuleRegistrationName } from "@medusajs/modules-sdk" import { ModuleRegistrationName } from "@medusajs/modules-sdk"
import { PromotionType } from "@medusajs/utils" import { PromotionType } from "@medusajs/utils"
import { createAdminUser } from "../../../helpers/create-admin-user" import { createAdminUser } from "../../../../helpers/create-admin-user"
import { medusaIntegrationTestRunner } from "medusa-test-utils" import { medusaIntegrationTestRunner } from "medusa-test-utils"
jest.setTimeout(50000) jest.setTimeout(50000)
@@ -1,6 +1,6 @@
import { IPromotionModuleService } from "@medusajs/types" import { IPromotionModuleService } from "@medusajs/types"
import { ModuleRegistrationName } from "@medusajs/modules-sdk" import { ModuleRegistrationName } from "@medusajs/modules-sdk"
import { createAdminUser } from "../../../helpers/create-admin-user" import { createAdminUser } from "../../../../helpers/create-admin-user"
import { medusaIntegrationTestRunner } from "medusa-test-utils" import { medusaIntegrationTestRunner } from "medusa-test-utils"
jest.setTimeout(50000) jest.setTimeout(50000)
@@ -1,7 +1,7 @@
import { IPromotionModuleService } from "@medusajs/types" import { IPromotionModuleService } from "@medusajs/types"
import { ModuleRegistrationName } from "@medusajs/modules-sdk" import { ModuleRegistrationName } from "@medusajs/modules-sdk"
import { PromotionType } from "@medusajs/utils" import { PromotionType } from "@medusajs/utils"
import { createAdminUser } from "../../../helpers/create-admin-user" import { createAdminUser } from "../../../../helpers/create-admin-user"
import { medusaIntegrationTestRunner } from "medusa-test-utils" import { medusaIntegrationTestRunner } from "medusa-test-utils"
jest.setTimeout(50000) jest.setTimeout(50000)
@@ -1,6 +1,6 @@
import { ModuleRegistrationName } from "@medusajs/modules-sdk" import { ModuleRegistrationName } from "@medusajs/modules-sdk"
import { IRegionModuleService } from "@medusajs/types" import { IRegionModuleService } from "@medusajs/types"
import { createAdminUser } from "../../../helpers/create-admin-user" import { createAdminUser } from "../../../../helpers/create-admin-user"
import { medusaIntegrationTestRunner } from "medusa-test-utils" import { medusaIntegrationTestRunner } from "medusa-test-utils"
jest.setTimeout(50000) jest.setTimeout(50000)
@@ -26,12 +26,6 @@ medusaIntegrationTestRunner({
await createAdminUser(dbConnection, adminHeaders, appContainer) await createAdminUser(dbConnection, adminHeaders, appContainer)
}) })
afterEach(async () => {
// TODO: Once teardown doesn't skip constraint checks and cascades, we can remove this
const existingRegions = await service.list({})
await service.delete(existingRegions.map((r) => r.id))
})
it("should create, update, and delete a region", async () => { it("should create, update, and delete a region", async () => {
const created = await api.post( const created = await api.post(
`/admin/regions`, `/admin/regions`,
@@ -1,6 +1,6 @@
import { ModuleRegistrationName } from "@medusajs/modules-sdk" import { ModuleRegistrationName } from "@medusajs/modules-sdk"
import { IStoreModuleService } from "@medusajs/types" import { IStoreModuleService } from "@medusajs/types"
import { createAdminUser } from "../../../helpers/create-admin-user" import { createAdminUser } from "../../../../helpers/create-admin-user"
import { medusaIntegrationTestRunner } from "medusa-test-utils" import { medusaIntegrationTestRunner } from "medusa-test-utils"
jest.setTimeout(50000) jest.setTimeout(50000)
@@ -1,7 +1,7 @@
import { ITaxModuleService } from "@medusajs/types" import { ITaxModuleService } from "@medusajs/types"
import { ModuleRegistrationName } from "@medusajs/modules-sdk" import { ModuleRegistrationName } from "@medusajs/modules-sdk"
import { createAdminUser } from "../../../helpers/create-admin-user" import { createAdminUser } from "../../../../helpers/create-admin-user"
import { medusaIntegrationTestRunner } from "medusa-test-utils" import { medusaIntegrationTestRunner } from "medusa-test-utils"
jest.setTimeout(50000) jest.setTimeout(50000)
@@ -1,7 +1,7 @@
import { ITaxModuleService } from "@medusajs/types" import { ITaxModuleService } from "@medusajs/types"
import { ModuleRegistrationName } from "@medusajs/modules-sdk" import { ModuleRegistrationName } from "@medusajs/modules-sdk"
import { createAdminUser } from "../../../helpers/create-admin-user" import { createAdminUser } from "../../../../helpers/create-admin-user"
import { import {
createTaxRateRulesStepId, createTaxRateRulesStepId,
updateTaxRatesWorkflow, updateTaxRatesWorkflow,
@@ -1,4 +1,4 @@
import { createAdminUser } from "../../helpers/create-admin-user" import { createAdminUser } from "../../../helpers/create-admin-user"
import { medusaIntegrationTestRunner } from "medusa-test-utils" import { medusaIntegrationTestRunner } from "medusa-test-utils"
jest.setTimeout(50000) jest.setTimeout(50000)
@@ -1,6 +1,6 @@
import { IUserModuleService } from "@medusajs/types" import { IUserModuleService } from "@medusajs/types"
import { ModuleRegistrationName } from "@medusajs/modules-sdk" import { ModuleRegistrationName } from "@medusajs/modules-sdk"
import { createAdminUser } from "../../helpers/create-admin-user" import { createAdminUser } from "../../../helpers/create-admin-user"
import { medusaIntegrationTestRunner } from "medusa-test-utils" import { medusaIntegrationTestRunner } from "medusa-test-utils"
jest.setTimeout(50000) jest.setTimeout(50000)
@@ -1,4 +1,4 @@
import { createAdminUser } from "../../helpers/create-admin-user" import { createAdminUser } from "../../../helpers/create-admin-user"
import { medusaIntegrationTestRunner } from "medusa-test-utils/dist" import { medusaIntegrationTestRunner } from "medusa-test-utils/dist"
jest.setTimeout(50000) jest.setTimeout(50000)
@@ -1,6 +1,6 @@
import { IUserModuleService } from "@medusajs/types" import { IUserModuleService } from "@medusajs/types"
import { ModuleRegistrationName } from "@medusajs/modules-sdk" import { ModuleRegistrationName } from "@medusajs/modules-sdk"
import { createAdminUser } from "../../helpers/create-admin-user" import { createAdminUser } from "../../../helpers/create-admin-user"
import { medusaIntegrationTestRunner } from "medusa-test-utils" import { medusaIntegrationTestRunner } from "medusa-test-utils"
jest.setTimeout(50000) jest.setTimeout(50000)
@@ -1,6 +1,6 @@
import { IUserModuleService } from "@medusajs/types" import { IUserModuleService } from "@medusajs/types"
import { ModuleRegistrationName } from "@medusajs/modules-sdk" import { ModuleRegistrationName } from "@medusajs/modules-sdk"
import { createAdminUser } from "../../helpers/create-admin-user" import { createAdminUser } from "../../../helpers/create-admin-user"
import { medusaIntegrationTestRunner } from "medusa-test-utils" import { medusaIntegrationTestRunner } from "medusa-test-utils"
jest.setTimeout(50000) jest.setTimeout(50000)
@@ -1,6 +1,6 @@
import { IUserModuleService } from "@medusajs/types" import { IUserModuleService } from "@medusajs/types"
import { ModuleRegistrationName } from "@medusajs/modules-sdk" import { ModuleRegistrationName } from "@medusajs/modules-sdk"
import { createAdminUser } from "../../helpers/create-admin-user" import { createAdminUser } from "../../../helpers/create-admin-user"
import { medusaIntegrationTestRunner } from "medusa-test-utils" import { medusaIntegrationTestRunner } from "medusa-test-utils"
jest.setTimeout(50000) jest.setTimeout(50000)
@@ -4,7 +4,7 @@ import {
StepResponse, StepResponse,
WorkflowData, WorkflowData,
} from "@medusajs/workflows-sdk" } from "@medusajs/workflows-sdk"
import { createAdminUser } from "../../helpers/create-admin-user" import { createAdminUser } from "../../../helpers/create-admin-user"
import { medusaIntegrationTestRunner } from "medusa-test-utils" import { medusaIntegrationTestRunner } from "medusa-test-utils"
export const workflowEngineTestSuite = ( export const workflowEngineTestSuite = (
@@ -1,29 +0,0 @@
import { ModuleRegistrationName } from "@medusajs/modules-sdk"
import { IAuthModuleService } from "@medusajs/types"
import jwt from "jsonwebtoken"
import { getContainer } from "../../environment-helpers/use-container"
import adminSeeder from "../../helpers/admin-seeder"
export const createAdminUser = async (
dbConnection,
adminHeaders,
container?
) => {
await adminSeeder(dbConnection)
const appContainer = container ?? getContainer()!
const authModule: IAuthModuleService = appContainer.resolve(
ModuleRegistrationName.AUTH
)
const authUser = await authModule.create({
provider: "emailpass",
entity_id: "admin@medusa.js",
scope: "admin",
app_metadata: {
user_id: "admin_user",
},
})
const token = jwt.sign(authUser, "test")
adminHeaders.headers["authorization"] = `Bearer ${token}`
}
@@ -3,12 +3,13 @@ import { initDb } from "./medusa-test-runner-utils/use-db"
import { startBootstrapApp } from "./medusa-test-runner-utils/bootstrap-app" import { startBootstrapApp } from "./medusa-test-runner-utils/bootstrap-app"
import { createDatabase, dropDatabase } from "pg-god" import { createDatabase, dropDatabase } from "pg-god"
import { ContainerLike } from "@medusajs/types" import { ContainerLike } from "@medusajs/types"
import { createMedusaContainer } from "@medusajs/utils"
const axios = require("axios").default const axios = require("axios").default
const keepTables = [ const keepTables = [
"store", /*"store",*/
"staged_job", /* "staged_job",
"shipping_profile", "shipping_profile",
"fulfillment_provider", "fulfillment_provider",
"payment_provider", "payment_provider",
@@ -16,7 +17,7 @@ const keepTables = [
"region_country", "region_country",
"currency", "currency",
"migrations", "migrations",
"mikro_orm_migrations", "mikro_orm_migrations",*/
] ]
const DB_HOST = process.env.DB_HOST const DB_HOST = process.env.DB_HOST
@@ -45,26 +46,19 @@ const dbTestUtilFactory = (): any => ({
forceDelete, forceDelete,
schema, schema,
}: { forceDelete?: string[]; schema?: string } = {}) { }: { forceDelete?: string[]; schema?: string } = {}) {
forceDelete = forceDelete || [] forceDelete ??= []
const manager = this.db_.manager const manager = this.db_.manager
schema ??= "public"
await manager.query(`SET session_replication_role = 'replica';`) await manager.query(`SET session_replication_role = 'replica';`)
const tableNames = await manager.query(`SELECT table_name const tableNames = await manager.query(`SELECT table_name
FROM information_schema.tables FROM information_schema.tables
WHERE table_schema = '${ WHERE table_schema = '${schema}';`)
schema ?? "public"
}';`)
for (const { table_name } of tableNames) { for (const { table_name } of tableNames) {
if (
keepTables.includes(table_name) &&
!forceDelete.includes(table_name)
) {
continue
}
await manager.query(`DELETE await manager.query(`DELETE
FROM "${table_name}";`) FROM ${schema}."${table_name}";`)
} }
await manager.query(`SET session_replication_role = 'origin';`) await manager.query(`SET session_replication_role = 'origin';`)
@@ -209,9 +203,29 @@ export function medusaIntegrationTestRunner({
shutdown = shutdown_ shutdown = shutdown_
} }
const beforeEach_ = async () => {
const container = options.getContainer()
const copiedContainer = createMedusaContainer({}, container)
if (process.env.MEDUSA_FF_MEDUSA_V2 != "true") {
const defaultLoader =
require("@medusajs/medusa/dist/loaders/defaults").default
await defaultLoader({
container: copiedContainer,
})
}
const medusaAppLoaderRunner =
require("@medusajs/medusa/dist/loaders/medusa-app").runModulesLoader
await medusaAppLoaderRunner({
container: copiedContainer,
configModule: container.resolve("configModule"),
})
}
const afterEach_ = async () => { const afterEach_ = async () => {
try { try {
await dbUtils.teardown({ forceDelete: [], schema }) await dbUtils.teardown({ schema })
} catch (error) { } catch (error) {
console.error("Error tearing down database:", error) console.error("Error tearing down database:", error)
} }
@@ -219,6 +233,7 @@ export function medusaIntegrationTestRunner({
return describe("", () => { return describe("", () => {
beforeAll(beforeAll_) beforeAll(beforeAll_)
beforeEach(beforeEach_)
afterEach(afterEach_) afterEach(afterEach_)
afterAll(async () => { afterAll(async () => {
await dbUtils.shutdown(dbName) await dbUtils.shutdown(dbName)
@@ -4,10 +4,13 @@ export const defaultAdminStoreFields = [
"id", "id",
"name", "name",
"supported_currency_codes", "supported_currency_codes",
"default_currency_code",
"default_sales_channel_id", "default_sales_channel_id",
"default_region_id", "default_region_id",
"default_location_id", "default_location_id",
"metadata", "metadata",
"created_at",
"updated_at",
] ]
export const retrieveTransformQueryConfig = { export const retrieveTransformQueryConfig = {
@@ -1,9 +1,12 @@
import { remoteQueryObjectFromString } from "@medusajs/utils" import {
ContainerRegistrationKeys,
remoteQueryObjectFromString
} from "@medusajs/utils"
import { MedusaRequest, MedusaResponse } from "../../../types/routing" import { MedusaRequest, MedusaResponse } from "../../../types/routing"
import { defaultAdminStoreFields } from "./query-config" import { defaultAdminStoreFields } from "./query-config"
export const GET = async (req: MedusaRequest, res: MedusaResponse) => { export const GET = async (req: MedusaRequest, res: MedusaResponse) => {
const remoteQuery = req.scope.resolve("remoteQuery") const remoteQuery = req.scope.resolve(ContainerRegistrationKeys.REMOTE_QUERY)
const queryObject = remoteQueryObjectFromString({ const queryObject = remoteQueryObjectFromString({
entryPoint: "store", entryPoint: "store",
@@ -51,6 +51,10 @@ export class AdminPostStoresStoreReq {
@IsArray() @IsArray()
supported_currency_codes?: string[] supported_currency_codes?: string[]
@IsOptional()
@IsString()
default_currency_code?: string
@IsOptional() @IsOptional()
@IsString() @IsString()
default_sales_channel_id?: string default_sales_channel_id?: string
+68
View File
@@ -231,4 +231,72 @@ export const loadMedusaApp = async (
return medusaApp return medusaApp
} }
/**
* Run the modules loader without taking care of anything else. This is useful for running the loader as a separate action or to re run all modules loaders.
*
* @param configModule
* @param container
*/
export async function runModulesLoader({
configModule,
container,
}: {
configModule: {
modules?: CommonTypes.ConfigModule["modules"]
projectConfig: CommonTypes.ConfigModule["projectConfig"]
}
container: MedusaContainer
}): Promise<void> {
const featureFlagRouter = container.resolve<FlagRouter>("featureFlagRouter")
const injectedDependencies = {
[ContainerRegistrationKeys.PG_CONNECTION]: container.resolve(
ContainerRegistrationKeys.PG_CONNECTION
),
[ContainerRegistrationKeys.LOGGER]: container.resolve(
ContainerRegistrationKeys.LOGGER
),
}
const sharedResourcesConfig = {
database: {
clientUrl: configModule.projectConfig.database_url,
driverOptions: configModule.projectConfig.database_extra,
debug: !!(configModule.projectConfig.database_logging ?? false),
},
}
const configModules = mergeDefaultModules(configModule.modules)
// Apply default options to legacy modules
for (const moduleKey of Object.keys(configModules)) {
if (!ModulesDefinition[moduleKey]?.isLegacy) {
continue
}
if (isObject(configModules[moduleKey])) {
;(
configModules[moduleKey] as Partial<InternalModuleDeclaration>
).options ??= {
database: {
type: "postgres",
url: configModule.projectConfig.database_url,
extra: configModule.projectConfig.database_extra,
schema: configModule.projectConfig.database_schema,
logging: configModule.projectConfig.database_logging,
},
}
}
}
await MedusaApp({
modulesConfig: configModules,
servicesConfig: joinerConfig,
remoteFetchData: remoteQueryFetchData(container),
sharedContainer: container,
sharedResourcesConfig,
injectedDependencies,
loaderOnly: true,
})
}
export default loadMedusaApp export default loadMedusaApp
Binary file not shown.
@@ -14,18 +14,21 @@ export const moduleLoader = async ({
moduleResolutions, moduleResolutions,
logger, logger,
migrationOnly, migrationOnly,
loaderOnly,
}: { }: {
container: MedusaContainer container: MedusaContainer
moduleResolutions: Record<string, ModuleResolution> moduleResolutions: Record<string, ModuleResolution>
logger: Logger logger: Logger
migrationOnly?: boolean migrationOnly?: boolean
loaderOnly?: boolean
}): Promise<void> => { }): Promise<void> => {
for (const resolution of Object.values(moduleResolutions ?? {})) { for (const resolution of Object.values(moduleResolutions ?? {})) {
const registrationResult = await loadModule( const registrationResult = await loadModule(
container, container,
resolution, resolution,
logger!, logger!,
migrationOnly migrationOnly,
loaderOnly
) )
if (registrationResult?.error) { if (registrationResult?.error) {
@@ -48,7 +51,8 @@ async function loadModule(
container: MedusaContainer, container: MedusaContainer,
resolution: ModuleResolution, resolution: ModuleResolution,
logger: Logger, logger: Logger,
migrationOnly?: boolean migrationOnly?: boolean,
loaderOnly?: boolean
): Promise<{ error?: Error } | void> { ): Promise<{ error?: Error } | void> {
const modDefinition = resolution.definition const modDefinition = resolution.definition
const registrationName = modDefinition.registrationName const registrationName = modDefinition.registrationName
@@ -85,5 +89,11 @@ async function loadModule(
return return
} }
return await loadInternalModule(container, resolution, logger, migrationOnly) return await loadInternalModule(
container,
resolution,
logger,
migrationOnly,
loaderOnly
)
} }
@@ -17,7 +17,8 @@ export async function loadInternalModule(
container: MedusaContainer, container: MedusaContainer,
resolution: ModuleResolution, resolution: ModuleResolution,
logger: Logger, logger: Logger,
migrationOnly?: boolean migrationOnly?: boolean,
loaderOnly?: boolean
): Promise<{ error?: Error } | void> { ): Promise<{ error?: Error } | void> {
const registrationName = resolution.definition.registrationName const registrationName = resolution.definition.registrationName
@@ -121,6 +122,10 @@ export async function loadInternalModule(
} }
} }
if (loaderOnly) {
return
}
const moduleService = loadedModule.service const moduleService = loadedModule.service
container.register({ container.register({
[registrationName]: asFunction((cradle) => { [registrationName]: asFunction((cradle) => {
+32 -3
View File
@@ -67,10 +67,11 @@ export type SharedResources = {
} }
} }
async function loadModules( export async function loadModules(
modulesConfig, modulesConfig,
sharedContainer, sharedContainer,
migrationOnly = false migrationOnly = false,
loaderOnly = false
) { ) {
const allModules = {} const allModules = {}
@@ -111,8 +112,13 @@ async function loadModules(
moduleDefinition: definition as ModuleDefinition, moduleDefinition: definition as ModuleDefinition,
moduleExports, moduleExports,
migrationOnly, migrationOnly,
loaderOnly,
})) as LoadedModule })) as LoadedModule
if (loaderOnly) {
return
}
const service = loaded[moduleName] const service = loaded[moduleName]
sharedContainer.register({ sharedContainer.register({
[service.__definition.registrationName]: asValue(service), [service.__definition.registrationName]: asValue(service),
@@ -207,6 +213,10 @@ export type MedusaAppOptions = {
remoteFetchData?: RemoteFetchDataCallback remoteFetchData?: RemoteFetchDataCallback
injectedDependencies?: any injectedDependencies?: any
onApplicationStartCb?: () => void onApplicationStartCb?: () => void
/**
* Forces the modules bootstrapper to only run the modules loaders and return prematurely
*/
loaderOnly?: boolean
} }
async function MedusaApp_({ async function MedusaApp_({
@@ -221,6 +231,7 @@ async function MedusaApp_({
injectedDependencies = {}, injectedDependencies = {},
onApplicationStartCb, onApplicationStartCb,
migrationOnly = false, migrationOnly = false,
loaderOnly = false,
}: MedusaAppOptions & { migrationOnly?: boolean } = {}): Promise<{ }: MedusaAppOptions & { migrationOnly?: boolean } = {}): Promise<{
modules: Record<string, LoadedModule | LoadedModule[]> modules: Record<string, LoadedModule | LoadedModule[]>
link: RemoteLink | undefined link: RemoteLink | undefined
@@ -285,7 +296,25 @@ async function MedusaApp_({
}) })
} }
const allModules = await loadModules(modules, sharedContainer_, migrationOnly) const allModules = await loadModules(
modules,
sharedContainer_,
migrationOnly,
loaderOnly
)
if (loaderOnly) {
return {
modules: allModules,
link: undefined,
query: async () => {
throw new Error("Querying not allowed in loaderOnly mode")
},
runMigrations: async () => {
throw new Error("Migrations not allowed in loaderOnly mode")
},
}
}
// Share Event bus with link modules // Share Event bus with link modules
injectedDependencies[ModuleRegistrationName.EVENT_BUS] = injectedDependencies[ModuleRegistrationName.EVENT_BUS] =
+15 -2
View File
@@ -65,6 +65,10 @@ export type ModuleBootstrapOptions = {
* Don't forget to clear the instances (MedusaModule.clearInstances()) after the migration are done. * Don't forget to clear the instances (MedusaModule.clearInstances()) after the migration are done.
*/ */
migrationOnly?: boolean migrationOnly?: boolean
/**
* Forces the modules bootstrapper to only run the modules loaders and return prematurely
*/
loaderOnly?: boolean
} }
export type LinkModuleBootstrapOptions = { export type LinkModuleBootstrapOptions = {
@@ -220,6 +224,7 @@ export class MedusaModule {
moduleDefinition, moduleDefinition,
injectedDependencies, injectedDependencies,
migrationOnly, migrationOnly,
loaderOnly,
}: ModuleBootstrapOptions): Promise<{ }: ModuleBootstrapOptions): Promise<{
[key: string]: T [key: string]: T
}> { }> {
@@ -227,18 +232,20 @@ export class MedusaModule {
stringifyCircular({ moduleKey, defaultPath, declaration }) stringifyCircular({ moduleKey, defaultPath, declaration })
) )
if (MedusaModule.instances_.has(hashKey)) { if (!loaderOnly && MedusaModule.instances_.has(hashKey)) {
return MedusaModule.instances_.get(hashKey)! as { return MedusaModule.instances_.get(hashKey)! as {
[key: string]: T [key: string]: T
} }
} }
if (MedusaModule.loading_.has(hashKey)) { if (!loaderOnly && MedusaModule.loading_.has(hashKey)) {
return MedusaModule.loading_.get(hashKey) return MedusaModule.loading_.get(hashKey)
} }
let finishLoading: any let finishLoading: any
let errorLoading: any let errorLoading: any
if (!loaderOnly) {
MedusaModule.loading_.set( MedusaModule.loading_.set(
hashKey, hashKey,
new Promise((resolve, reject) => { new Promise((resolve, reject) => {
@@ -246,6 +253,7 @@ export class MedusaModule {
errorLoading = reject errorLoading = reject
}) })
) )
}
let modDeclaration = let modDeclaration =
declaration ?? declaration ??
@@ -294,6 +302,7 @@ export class MedusaModule {
moduleResolutions, moduleResolutions,
logger: logger_, logger: logger_,
migrationOnly, migrationOnly,
loaderOnly
}) })
} catch (err) { } catch (err) {
errorLoading(err) errorLoading(err)
@@ -302,6 +311,10 @@ export class MedusaModule {
const services = {} const services = {}
if (loaderOnly) {
return services
}
for (const resolution of Object.values( for (const resolution of Object.values(
moduleResolutions moduleResolutions
) as ModuleResolution[]) { ) as ModuleResolution[]) {
+4
View File
@@ -1,8 +1,12 @@
import * as entities from "./src/models" import * as entities from "./src/models"
import { TSMigrationGenerator } from "@medusajs/utils"
module.exports = { module.exports = {
entities: Object.values(entities), entities: Object.values(entities),
schema: "public", schema: "public",
clientUrl: "postgres://postgres@localhost/medusa-region", clientUrl: "postgres://postgres@localhost/medusa-region",
type: "postgresql", type: "postgresql",
migrations: {
generator: TSMigrationGenerator,
},
} }
+1 -1
View File
@@ -5,7 +5,7 @@ import { Country, Region } from "@models"
export const LinkableKeys = { export const LinkableKeys = {
region_id: Region.name, region_id: Region.name,
country_id: Region.name, country_iso: Country.name,
} }
const entityLinkableKeysMap: MapToConfig = {} const entityLinkableKeysMap: MapToConfig = {}
@@ -26,14 +26,13 @@ ${generatePostgresAlterColummnIfExistStatement(
CREATE INDEX IF NOT EXISTS "IDX_region_deleted_at" ON "region" ("deleted_at") WHERE "deleted_at" IS NOT NULL; 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 or update "region_country" table
CREATE TABLE IF NOT EXISTS "region_country" ( CREATE TABLE IF NOT EXISTS "region_country" (
"id" text NOT NULL,
"iso_2" text NOT NULL, "iso_2" text NOT NULL,
"iso_3" text NOT NULL, "iso_3" text NOT NULL,
"num_code" int NOT NULL, "num_code" int NOT NULL,
"name" text NOT NULL, "name" text NOT NULL,
"display_name" text NOT NULL, "display_name" text NOT NULL,
"region_id" text NULL, "region_id" text NULL,
CONSTRAINT "region_country_pkey" PRIMARY KEY ("id") 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); 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" -- Adjust foreign keys for "region_country"
+2 -26
View File
@@ -1,18 +1,6 @@
import { import { Entity, ManyToOne, PrimaryKey, Property } from "@mikro-orm/core"
BeforeCreate,
Entity,
Unique,
ManyToOne,
OnInit,
PrimaryKey,
Property,
Index,
} from "@mikro-orm/core"
import { import { createPsqlIndexStatementHelper } from "@medusajs/utils"
createPsqlIndexStatementHelper,
generateEntityId,
} from "@medusajs/utils"
import Region from "./region" import Region from "./region"
// We don't need a partial index on deleted_at here since we don't support soft deletes on countries // We don't need a partial index on deleted_at here since we don't support soft deletes on countries
@@ -28,8 +16,6 @@ RegionIdIsoIndexStatement.MikroORMIndex()
@Entity({ tableName: "region_country" }) @Entity({ tableName: "region_country" })
export default class Country { export default class Country {
@PrimaryKey({ columnType: "text" }) @PrimaryKey({ columnType: "text" })
id: string
@Property({ columnType: "text" }) @Property({ columnType: "text" })
iso_2: string iso_2: string
@@ -55,14 +41,4 @@ export default class Country {
onDelete: "set null", onDelete: "set null",
}) })
region?: Region | null region?: Region | null
@BeforeCreate()
onCreate() {
this.id = generateEntityId(this.id, "reg_ctry")
}
@OnInit()
onInit() {
this.id = generateEntityId(this.id, "reg_ctry")
}
} }
@@ -30,6 +30,14 @@ moduleIntegrationTestRunner({
}) })
}) })
it("should fail to get created if default currency code is not in list of supported currency codes", async function () {
const err = await service
.create({ ...createStoreFixture, default_currency_code: "jpy" })
.catch((err) => err.message)
expect(err).toEqual("Store does not have currency: jpy")
})
describe("upserting a store", () => { describe("upserting a store", () => {
it("should get created if it does not exist", async function () { it("should get created if it does not exist", async function () {
const store = await service.upsert(createStoreFixture) const store = await service.upsert(createStoreFixture)
@@ -67,6 +75,45 @@ moduleIntegrationTestRunner({
}) })
expect(updatedStore.title).toEqual("Updated store") expect(updatedStore.title).toEqual("Updated store")
}) })
it("should fail updating default currency code to an unsupported one", async function () {
const createdStore = await service.create(createStoreFixture)
const updateErr = await service
.update(createdStore.id, {
default_currency_code: "jpy",
})
.catch((err) => err.message)
expect(updateErr).toEqual("Store does not have currency: jpy")
})
it("should fail updating default currency code to an unsupported one if the supported currencies are also updated", async function () {
const createdStore = await service.create(createStoreFixture)
const updateErr = await service
.update(createdStore.id, {
supported_currency_codes: ["mkd"],
default_currency_code: "jpy",
})
.catch((err) => err.message)
expect(updateErr).toEqual("Store does not have currency: jpy")
})
it("should fail updating supported currencies if one of them is used as a default one", async function () {
const createdStore = await service.create({
...createStoreFixture,
default_currency_code: "eur",
})
const updateErr = await service
.update(createdStore.id, {
supported_currency_codes: ["jpy"],
})
.catch((err) => err.message)
expect(updateErr).toEqual(
"You are not allowed to remove default currency from store currencies without replacing it as well"
)
})
}) })
describe("deleting a store", () => { describe("deleting a store", () => {
@@ -35,6 +35,15 @@
"default": "'{}'", "default": "'{}'",
"mappedType": "array" "mappedType": "array"
}, },
"default_currency_code": {
"name": "default_currency_code",
"type": "text",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": true,
"mappedType": "text"
},
"default_sales_channel_id": { "default_sales_channel_id": {
"name": "default_sales_channel_id", "name": "default_sales_channel_id",
"type": "text", "type": "text",
@@ -13,6 +13,12 @@ export class InitialSetup20240226130829 extends Migration {
this.addSql( this.addSql(
`alter table "store" alter column "name" SET DEFAULT 'Medusa Store';` `alter table "store" alter column "name" SET DEFAULT 'Medusa Store';`
) )
this.addSql(
`alter table "store" alter column "default_currency_code" TYPE text;`
)
this.addSql(
`alter table "store" alter column "default_currency_code" drop not null;`
)
this.addSql( this.addSql(
`alter table "store" alter column "default_sales_channel_id" TYPE text;` `alter table "store" alter column "default_sales_channel_id" TYPE text;`
) )
@@ -20,7 +26,9 @@ export class InitialSetup20240226130829 extends Migration {
`alter table "store" alter column "default_location_id" TYPE text;` `alter table "store" alter column "default_location_id" TYPE text;`
) )
this.addSql(`alter table "store" add column "default_region_id" text;`) this.addSql(
`alter table "store" add column "default_region_id" text null;`
)
this.addSql( this.addSql(
`alter table "store" add column "deleted_at" timestamptz null;` `alter table "store" add column "deleted_at" timestamptz null;`
) )
@@ -32,6 +40,13 @@ export class InitialSetup20240226130829 extends Migration {
'create index if not exists "IDX_store_deleted_at" on "store" (deleted_at) where deleted_at is not null;' 'create index if not exists "IDX_store_deleted_at" on "store" (deleted_at) where deleted_at is not null;'
) )
this.addSql(
`alter table "store" drop constraint if exists "FK_61b0f48cccbb5f41c750bac7286";`
)
this.addSql(
`alter table "store" drop constraint if exists "FK_55beebaa09e947cccca554af222";`
)
// this.addSql(`alter table "store" drop column "default_currency_code";`) // this.addSql(`alter table "store" drop column "default_currency_code";`)
// this.addSql(`alter table "store" drop column "swap_link_template";`) // this.addSql(`alter table "store" drop column "swap_link_template";`)
// this.addSql(`alter table "store" drop column "payment_link_template";`) // this.addSql(`alter table "store" drop column "payment_link_template";`)
@@ -39,7 +54,7 @@ export class InitialSetup20240226130829 extends Migration {
} else { } else {
this.addSql(`create table if not exists "store" this.addSql(`create table if not exists "store"
("id" text not null, "name" text not null default \'Medusa Store\', "supported_currency_codes" text[] not null default \'{}\', ("id" text not null, "name" text not null default \'Medusa Store\', "supported_currency_codes" text[] not null default \'{}\',
"default_sales_channel_id" text null, "default_region_id" text null, "default_location_id" text null, "default_currency_code" text null, "default_sales_channel_id" text null, "default_region_id" text null, "default_location_id" text null,
"metadata" jsonb null, "created_at" timestamptz not null default now(), "updated_at" timestamptz not null default now(), "deleted_at" timestamptz null, "metadata" jsonb null, "created_at" timestamptz not null default now(), "updated_at" timestamptz not null default now(), "deleted_at" timestamptz null,
constraint "store_pkey" primary key ("id"));`) constraint "store_pkey" primary key ("id"));`)
+3
View File
@@ -38,6 +38,9 @@ export default class Store {
@Property({ type: "array", default: "{}" }) @Property({ type: "array", default: "{}" })
supported_currency_codes: string[] = [] supported_currency_codes: string[] = []
@Property({ columnType: "text", nullable: true })
default_currency_code: string | null = null
@Property({ columnType: "text", nullable: true }) @Property({ columnType: "text", nullable: true })
default_sales_channel_id: string | null = null default_sales_channel_id: string | null = null
@@ -11,6 +11,7 @@ import {
InjectManager, InjectManager,
InjectTransactionManager, InjectTransactionManager,
MedusaContext, MedusaContext,
MedusaError,
ModulesSdkUtils, ModulesSdkUtils,
isString, isString,
promiseAll, promiseAll,
@@ -83,6 +84,8 @@ export default class StoreModuleService<TEntity extends Store = Store>
@MedusaContext() sharedContext: Context = {} @MedusaContext() sharedContext: Context = {}
): Promise<Store[]> { ): Promise<Store[]> {
let normalizedInput = StoreModuleService.normalizeInput(data) let normalizedInput = StoreModuleService.normalizeInput(data)
StoreModuleService.validateCreateRequest(normalizedInput)
return await this.storeService_.create(normalizedInput, sharedContext) return await this.storeService_.create(normalizedInput, sharedContext)
} }
@@ -169,6 +172,7 @@ export default class StoreModuleService<TEntity extends Store = Store>
@MedusaContext() sharedContext: Context = {} @MedusaContext() sharedContext: Context = {}
): Promise<Store[]> { ): Promise<Store[]> {
const normalizedInput = StoreModuleService.normalizeInput(data) const normalizedInput = StoreModuleService.normalizeInput(data)
await this.validateUpdateRequest(normalizedInput)
return await this.storeService_.update(normalizedInput, sharedContext) return await this.storeService_.update(normalizedInput, sharedContext)
} }
@@ -182,4 +186,80 @@ export default class StoreModuleService<TEntity extends Store = Store>
}) })
) )
} }
private static validateCreateRequest(stores: StoreTypes.CreateStoreDTO[]) {
for (const store of stores) {
// If we are setting the default currency code on creating, make sure it is supported
if (store.default_currency_code) {
if (
!store.supported_currency_codes?.includes(
store.default_currency_code ?? ""
)
) {
throw new MedusaError(
MedusaError.Types.INVALID_DATA,
`Store does not have currency: ${store.default_currency_code}`
)
}
}
}
}
private async validateUpdateRequest(stores: UpdateStoreInput[]) {
const dbStores = await this.storeService_.list(
{ id: stores.map((s) => s.id) },
{ take: null }
)
const dbStoresMap = new Map<string, Store>(
dbStores.map((dbStore) => [dbStore.id, dbStore])
)
for (const store of stores) {
const dbStore = dbStoresMap.get(store.id)
// If it is updating both the supported currency codes and the default one, look in that list
if (store.supported_currency_codes && store.default_currency_code) {
if (
!store.supported_currency_codes.includes(
store.default_currency_code ?? ""
)
) {
throw new MedusaError(
MedusaError.Types.INVALID_DATA,
`Store does not have currency: ${store.default_currency_code}`
)
}
return
}
// If it is updating only the default currency code, look in the db store
if (store.default_currency_code) {
if (
!dbStore?.supported_currency_codes?.includes(
store.default_currency_code
)
) {
throw new MedusaError(
MedusaError.Types.INVALID_DATA,
`Store does not have currency: ${store.default_currency_code}`
)
}
}
// If it is updating only the supported currency codes, make sure one of them is not set as a default one
if (store.supported_currency_codes) {
if (
!store.supported_currency_codes.includes(
dbStore?.default_currency_code ?? ""
)
) {
throw new MedusaError(
MedusaError.Types.INVALID_DATA,
"You are not allowed to remove default currency from store currencies without replacing it as well"
)
}
}
}
}
} }
+3
View File
@@ -4,10 +4,13 @@ export interface StoreDTO {
id: string id: string
name: string name: string
supported_currency_codes: string[] supported_currency_codes: string[]
default_currency_code?: string
default_sales_channel_id?: string default_sales_channel_id?: string
default_region_id?: string default_region_id?: string
default_location_id?: string default_location_id?: string
metadata: Record<string, any> | null metadata: Record<string, any> | null
created_at: string
updated_at: string
} }
export interface FilterableStoreProps export interface FilterableStoreProps
extends BaseFilterable<FilterableStoreProps> { extends BaseFilterable<FilterableStoreProps> {
@@ -1,6 +1,7 @@
export interface CreateStoreDTO { export interface CreateStoreDTO {
name?: string name?: string
supported_currency_codes?: string[] supported_currency_codes?: string[]
default_currency_code?: string
default_sales_channel_id?: string default_sales_channel_id?: string
default_region_id?: string default_region_id?: string
default_location_id?: string default_location_id?: string
@@ -11,6 +12,7 @@ export interface UpsertStoreDTO {
id?: string id?: string
name?: string name?: string
supported_currency_codes?: string[] supported_currency_codes?: string[]
default_currency_code?: string
default_sales_channel_id?: string default_sales_channel_id?: string
default_region_id?: string default_region_id?: string
default_location_id?: string default_location_id?: string
@@ -20,6 +22,7 @@ export interface UpsertStoreDTO {
export interface UpdateStoreDTO { export interface UpdateStoreDTO {
name?: string name?: string
supported_currency_codes?: string[] supported_currency_codes?: string[]
default_currency_code?: string
default_sales_channel_id?: string default_sales_channel_id?: string
default_region_id?: string default_region_id?: string
default_location_id?: string default_location_id?: string
+15
View File
@@ -31765,15 +31765,30 @@ __metadata:
"@babel/cli": ^7.12.10 "@babel/cli": ^7.12.10
"@babel/core": ^7.12.10 "@babel/core": ^7.12.10
"@babel/node": ^7.12.10 "@babel/node": ^7.12.10
"@medusajs/api-key": "workspace:^"
"@medusajs/auth": "workspace:*"
"@medusajs/cache-inmemory": "workspace:*" "@medusajs/cache-inmemory": "workspace:*"
"@medusajs/customer": "workspace:^"
"@medusajs/event-bus-local": "workspace:*" "@medusajs/event-bus-local": "workspace:*"
"@medusajs/inventory": "workspace:^"
"@medusajs/medusa": "workspace:*" "@medusajs/medusa": "workspace:*"
"@medusajs/modules-sdk": "workspace:^"
"@medusajs/pricing": "workspace:^"
"@medusajs/product": "workspace:^"
"@medusajs/promotion": "workspace:^"
"@medusajs/region": "workspace:^"
"@medusajs/store": "workspace:^"
"@medusajs/tax": "workspace:^"
"@medusajs/user": "workspace:^"
"@medusajs/utils": "workspace:^"
"@medusajs/workflow-engine-inmemory": "workspace:*" "@medusajs/workflow-engine-inmemory": "workspace:*"
babel-preset-medusa-package: "*" babel-preset-medusa-package: "*"
faker: ^5.5.3 faker: ^5.5.3
jest: ^26.6.3 jest: ^26.6.3
jest-environment-node: 26.6.2 jest-environment-node: 26.6.2
medusa-fulfillment-webshipper: "workspace:*"
medusa-interfaces: "workspace:*" medusa-interfaces: "workspace:*"
medusa-plugin-sendgrid: "workspace:*"
pg: ^8.11.0 pg: ^8.11.0
typeorm: ^0.3.16 typeorm: ^0.3.16
languageName: unknown languageName: unknown