fix: Remove medusa v2 flag from the medusa app package (#7295)
This commit is contained in:
@@ -2,14 +2,11 @@ import { asValue, createContainer } from "awilix"
|
|||||||
import getMigrations, {
|
import getMigrations, {
|
||||||
getModuleSharedResources,
|
getModuleSharedResources,
|
||||||
revertIsolatedModulesMigration,
|
revertIsolatedModulesMigration,
|
||||||
runIsolatedModulesMigration,
|
|
||||||
} from "./utils/get-migrations"
|
} from "./utils/get-migrations"
|
||||||
|
|
||||||
import {
|
import {
|
||||||
ContainerRegistrationKeys,
|
ContainerRegistrationKeys,
|
||||||
createMedusaContainer,
|
createMedusaContainer,
|
||||||
MedusaV2Flag,
|
|
||||||
promiseAll,
|
|
||||||
} from "@medusajs/utils"
|
} from "@medusajs/utils"
|
||||||
import configModuleLoader from "../loaders/config"
|
import configModuleLoader from "../loaders/config"
|
||||||
import databaseLoader from "../loaders/database"
|
import databaseLoader from "../loaders/database"
|
||||||
@@ -76,30 +73,22 @@ const main = async function ({ directory }) {
|
|||||||
const featureFlagRouter = featureFlagLoader(configModule)
|
const featureFlagRouter = featureFlagLoader(configModule)
|
||||||
|
|
||||||
if (args[0] === "run") {
|
if (args[0] === "run") {
|
||||||
if (featureFlagRouter.isFeatureEnabled(MedusaV2Flag.key)) {
|
const container = createMedusaContainer()
|
||||||
const container = createMedusaContainer()
|
const pgConnection = await pgConnectionLoader({ configModule, container })
|
||||||
const pgConnection = await pgConnectionLoader({ configModule, container })
|
container.register({
|
||||||
container.register({
|
[ContainerRegistrationKeys.CONFIG_MODULE]: asValue(configModule),
|
||||||
[ContainerRegistrationKeys.CONFIG_MODULE]: asValue(configModule),
|
[ContainerRegistrationKeys.LOGGER]: asValue(Logger),
|
||||||
[ContainerRegistrationKeys.LOGGER]: asValue(Logger),
|
[ContainerRegistrationKeys.PG_CONNECTION]: asValue(pgConnection),
|
||||||
[ContainerRegistrationKeys.PG_CONNECTION]: asValue(pgConnection),
|
[ContainerRegistrationKeys.FEATURE_FLAG_ROUTER]:
|
||||||
featureFlagRouter: asValue(featureFlagRouter),
|
asValue(featureFlagRouter),
|
||||||
})
|
})
|
||||||
await migrateMedusaApp(
|
await migrateMedusaApp(
|
||||||
{ configModule, container },
|
{ configModule, container },
|
||||||
{ registerInContainer: false }
|
{ registerInContainer: false }
|
||||||
)
|
)
|
||||||
} else {
|
|
||||||
const dataSource = await getDataSource(directory)
|
|
||||||
await dataSource.runMigrations()
|
|
||||||
await dataSource.destroy()
|
|
||||||
await runIsolatedModulesMigration(configModule)
|
|
||||||
|
|
||||||
await runLinkMigrations(directory)
|
|
||||||
}
|
|
||||||
process.exit()
|
|
||||||
|
|
||||||
Logger.info("Migrations completed.")
|
Logger.info("Migrations completed.")
|
||||||
|
process.exit()
|
||||||
} else if (args[0] === "revert") {
|
} else if (args[0] === "revert") {
|
||||||
const dataSource = await getDataSource(directory)
|
const dataSource = await getDataSource(directory)
|
||||||
await dataSource.undoLastMigration({ transaction: "all" })
|
await dataSource.undoLastMigration({ transaction: "all" })
|
||||||
|
|||||||
@@ -7,43 +7,6 @@ import { track } from "medusa-telemetry"
|
|||||||
import loaders from "../loaders"
|
import loaders from "../loaders"
|
||||||
import Logger from "../loaders/logger"
|
import Logger from "../loaders/logger"
|
||||||
import { ModuleRegistrationName } from "@medusajs/modules-sdk"
|
import { ModuleRegistrationName } from "@medusajs/modules-sdk"
|
||||||
import featureFlagLoader from "../loaders/feature-flags"
|
|
||||||
import configModuleLoader from "../loaders/config"
|
|
||||||
import { MedusaV2Flag } from "@medusajs/utils"
|
|
||||||
|
|
||||||
const useV2Command = async (
|
|
||||||
{ email, password, isInvite, provider = "emailpass" },
|
|
||||||
{ container }
|
|
||||||
) => {
|
|
||||||
const userService = container.resolve(ModuleRegistrationName.USER)
|
|
||||||
const authService = container.resolve(ModuleRegistrationName.AUTH)
|
|
||||||
|
|
||||||
if (isInvite) {
|
|
||||||
// The invite flow only works with the V2 version of packages/admin-next/dashboard, so enable the V2 feature flag in admin before using this command
|
|
||||||
const invite = await userService.createInvites({ email })
|
|
||||||
|
|
||||||
Logger.info(`
|
|
||||||
Invite token: ${invite.token}
|
|
||||||
Open the invite in Medusa Admin at: [your-admin-url]/invite?token=${invite.token}`)
|
|
||||||
} else {
|
|
||||||
const user = await userService.create({ email })
|
|
||||||
|
|
||||||
const { authUser } = await authService.authenticate(provider, {
|
|
||||||
body: {
|
|
||||||
email,
|
|
||||||
password,
|
|
||||||
},
|
|
||||||
authScope: "admin",
|
|
||||||
})
|
|
||||||
|
|
||||||
await authService.update({
|
|
||||||
id: authUser.id,
|
|
||||||
app_metadata: {
|
|
||||||
user_id: user.id,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export default async function ({
|
export default async function ({
|
||||||
directory,
|
directory,
|
||||||
@@ -61,25 +24,33 @@ export default async function ({
|
|||||||
expressApp: app,
|
expressApp: app,
|
||||||
})
|
})
|
||||||
|
|
||||||
const configModule = configModuleLoader(directory)
|
const userService = container.resolve(ModuleRegistrationName.USER)
|
||||||
const featureFlagRouter = featureFlagLoader(configModule)
|
const authService = container.resolve(ModuleRegistrationName.AUTH)
|
||||||
|
const provider = "emailpass"
|
||||||
|
|
||||||
if (featureFlagRouter.isFeatureEnabled(MedusaV2Flag.key)) {
|
if (invite) {
|
||||||
await useV2Command({ email, password, isInvite: invite }, { container })
|
const invite = await userService.createInvites({ email })
|
||||||
|
|
||||||
|
Logger.info(`
|
||||||
|
Invite token: ${invite.token}
|
||||||
|
Open the invite in Medusa Admin at: [your-admin-url]/invite?token=${invite.token}`)
|
||||||
} else {
|
} else {
|
||||||
if (invite) {
|
const user = await userService.create({ email })
|
||||||
const inviteService = container.resolve("inviteService")
|
|
||||||
await inviteService.create(email, "admin")
|
const { authUser } = await authService.authenticate(provider, {
|
||||||
const invite = await inviteService.list({
|
body: {
|
||||||
user_email: email,
|
email,
|
||||||
})
|
password,
|
||||||
Logger.info(`
|
},
|
||||||
Invite token: ${invite[0].token}
|
authScope: "admin",
|
||||||
Open the invite in Medusa Admin at: [your-admin-url]/invite?token=${invite[0].token}`)
|
})
|
||||||
} else {
|
|
||||||
const userService = container.resolve("userService")
|
await authService.update({
|
||||||
await userService.create({ id, email }, password)
|
id: authUser.id,
|
||||||
}
|
app_metadata: {
|
||||||
|
user_id: user.id,
|
||||||
|
},
|
||||||
|
})
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error(err)
|
console.error(err)
|
||||||
|
|||||||
@@ -13,12 +13,7 @@ type Options = {
|
|||||||
featureFlagRouter?: FlagRouter
|
featureFlagRouter?: FlagRouter
|
||||||
}
|
}
|
||||||
|
|
||||||
export default async ({
|
export default async ({ app, configModule }: Options) => {
|
||||||
app,
|
|
||||||
container,
|
|
||||||
configModule,
|
|
||||||
featureFlagRouter,
|
|
||||||
}: Options) => {
|
|
||||||
// This is a workaround for the issue described here: https://github.com/expressjs/express/issues/3454
|
// This is a workaround for the issue described here: https://github.com/expressjs/express/issues/3454
|
||||||
// We parse the url and get the qs to be parsed and override the query prop from the request
|
// We parse the url and get the qs to be parsed and override the query prop from the request
|
||||||
app.use(function (req, res, next) {
|
app.use(function (req, res, next) {
|
||||||
|
|||||||
@@ -11,8 +11,11 @@ type Options = {
|
|||||||
configModule: ConfigModule
|
configModule: ConfigModule
|
||||||
}
|
}
|
||||||
|
|
||||||
export default async ({ app, configModule }: Options): Promise<{
|
export default async ({
|
||||||
app: Express,
|
app,
|
||||||
|
configModule,
|
||||||
|
}: Options): Promise<{
|
||||||
|
app: Express
|
||||||
shutdown: () => Promise<void>
|
shutdown: () => Promise<void>
|
||||||
}> => {
|
}> => {
|
||||||
let sameSite: string | boolean = false
|
let sameSite: string | boolean = false
|
||||||
@@ -46,7 +49,7 @@ export default async ({ app, configModule }: Options): Promise<{
|
|||||||
if (configModule?.projectConfig?.redis_url) {
|
if (configModule?.projectConfig?.redis_url) {
|
||||||
const RedisStore = createStore(session)
|
const RedisStore = createStore(session)
|
||||||
redisClient = new Redis(
|
redisClient = new Redis(
|
||||||
configModule.projectConfig.redis_url,
|
configModule.projectConfig.redis_url,
|
||||||
configModule.projectConfig.redis_options ?? {}
|
configModule.projectConfig.redis_options ?? {}
|
||||||
)
|
)
|
||||||
sessionOpts.store = new RedisStore({
|
sessionOpts.store = new RedisStore({
|
||||||
|
|||||||
@@ -1,43 +1,22 @@
|
|||||||
import { createDefaultsWorkflow } from "@medusajs/core-flows"
|
import { createDefaultsWorkflow } from "@medusajs/core-flows"
|
||||||
import {
|
import { ConfigModule } from "@medusajs/types"
|
||||||
InternalModuleDeclaration,
|
import { ContainerRegistrationKeys, promiseAll } from "@medusajs/utils"
|
||||||
ModulesDefinition,
|
|
||||||
} from "@medusajs/modules-sdk"
|
|
||||||
import { ConfigModule, MODULE_RESOURCE_TYPE } from "@medusajs/types"
|
|
||||||
import {
|
|
||||||
ContainerRegistrationKeys,
|
|
||||||
MedusaV2Flag,
|
|
||||||
isString,
|
|
||||||
promiseAll,
|
|
||||||
} from "@medusajs/utils"
|
|
||||||
import { asValue } from "awilix"
|
import { asValue } from "awilix"
|
||||||
import { Express, NextFunction, Request, Response } from "express"
|
import { Express, NextFunction, Request, Response } from "express"
|
||||||
import { createMedusaContainer } from "medusa-core-utils"
|
import { createMedusaContainer } from "medusa-core-utils"
|
||||||
import { track } from "medusa-telemetry"
|
|
||||||
import { EOL } from "os"
|
|
||||||
import requestIp from "request-ip"
|
import requestIp from "request-ip"
|
||||||
import { Connection } from "typeorm"
|
|
||||||
import { v4 } from "uuid"
|
import { v4 } from "uuid"
|
||||||
import { MedusaContainer } from "../types/global"
|
import { MedusaContainer } from "../types/global"
|
||||||
import apiLoader from "./api"
|
import apiLoader from "./api"
|
||||||
import loadConfig from "./config"
|
import loadConfig from "./config"
|
||||||
import databaseLoader, { dataSource } from "./database"
|
|
||||||
import expressLoader from "./express"
|
import expressLoader from "./express"
|
||||||
import featureFlagsLoader from "./feature-flags"
|
import featureFlagsLoader from "./feature-flags"
|
||||||
import { registerProjectWorkflows } from "./helpers/register-workflows"
|
import { registerProjectWorkflows } from "./helpers/register-workflows"
|
||||||
import medusaProjectApisLoader from "./load-medusa-project-apis"
|
import medusaProjectApisLoader from "./load-medusa-project-apis"
|
||||||
import Logger from "./logger"
|
import Logger from "./logger"
|
||||||
import loadMedusaApp, { mergeDefaultModules } from "./medusa-app"
|
import loadMedusaApp from "./medusa-app"
|
||||||
import modelsLoader from "./models"
|
|
||||||
import passportLoader from "./passport"
|
|
||||||
import pgConnectionLoader from "./pg-connection"
|
import pgConnectionLoader from "./pg-connection"
|
||||||
import pluginsLoader, { registerPluginModels } from "./plugins"
|
// import subscribersLoader from "./subscribers"
|
||||||
import redisLoader from "./redis"
|
|
||||||
import repositoriesLoader from "./repositories"
|
|
||||||
import searchIndexLoader from "./search-index"
|
|
||||||
import servicesLoader from "./services"
|
|
||||||
import strategiesLoader from "./strategies"
|
|
||||||
import subscribersLoader from "./subscribers"
|
|
||||||
|
|
||||||
type Options = {
|
type Options = {
|
||||||
directory: string
|
directory: string
|
||||||
@@ -45,57 +24,63 @@ type Options = {
|
|||||||
isTest: boolean
|
isTest: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
async function loadLegacyModulesEntities(configModules, container) {
|
const isWorkerMode = (configModule) => {
|
||||||
const logger = container.resolve(ContainerRegistrationKeys.LOGGER)
|
return configModule.projectConfig.worker_mode === "worker"
|
||||||
|
|
||||||
for (const [moduleName, moduleConfig] of Object.entries(configModules)) {
|
|
||||||
const definition = ModulesDefinition[moduleName]
|
|
||||||
|
|
||||||
if (!definition?.isLegacy) {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
const modulePath = isString(moduleConfig)
|
|
||||||
? moduleConfig
|
|
||||||
: (moduleConfig as InternalModuleDeclaration).resolve ??
|
|
||||||
(definition.defaultPackage as string)
|
|
||||||
|
|
||||||
const resources = isString(moduleConfig)
|
|
||||||
? (definition.defaultModuleDeclaration as InternalModuleDeclaration)
|
|
||||||
.resources
|
|
||||||
: (moduleConfig as InternalModuleDeclaration).resources ??
|
|
||||||
(definition.defaultModuleDeclaration as InternalModuleDeclaration)
|
|
||||||
.resources
|
|
||||||
|
|
||||||
if (resources === MODULE_RESOURCE_TYPE.SHARED) {
|
|
||||||
if (!modulePath) {
|
|
||||||
logger.warn(`Unable to load module entities for ${moduleName}`)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
const module = await import(modulePath as string)
|
|
||||||
|
|
||||||
if (module.default?.models) {
|
|
||||||
module.default.models.map((model) =>
|
|
||||||
container.registerAdd("db_entities", asValue(model))
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async function loadMedusaV2({
|
async function loadEntrypoints(
|
||||||
rootDirectory,
|
|
||||||
configModule,
|
configModule,
|
||||||
featureFlagRouter,
|
container,
|
||||||
expressApp,
|
expressApp,
|
||||||
}) {
|
featureFlagRouter
|
||||||
|
) {
|
||||||
|
if (isWorkerMode(configModule)) {
|
||||||
|
return async () => {}
|
||||||
|
}
|
||||||
|
|
||||||
|
const { shutdown } = await expressLoader({ app: expressApp, configModule })
|
||||||
|
expressApp.use((req: Request, res: Response, next: NextFunction) => {
|
||||||
|
req.scope = container.createScope() as MedusaContainer
|
||||||
|
req.requestId = (req.headers["x-request-id"] as string) ?? v4()
|
||||||
|
next()
|
||||||
|
})
|
||||||
|
|
||||||
|
// Add additional information to context of request
|
||||||
|
expressApp.use((req: Request, res: Response, next: NextFunction) => {
|
||||||
|
const ipAddress = requestIp.getClientIp(req) as string
|
||||||
|
;(req as any).request_context = {
|
||||||
|
ip_address: ipAddress,
|
||||||
|
}
|
||||||
|
next()
|
||||||
|
})
|
||||||
|
|
||||||
|
// subscribersLoader({ container })
|
||||||
|
|
||||||
|
await apiLoader({
|
||||||
|
container,
|
||||||
|
app: expressApp,
|
||||||
|
configModule,
|
||||||
|
featureFlagRouter,
|
||||||
|
})
|
||||||
|
|
||||||
|
return shutdown
|
||||||
|
}
|
||||||
|
|
||||||
|
export default async ({
|
||||||
|
directory: rootDirectory,
|
||||||
|
expressApp,
|
||||||
|
}: Options): Promise<{
|
||||||
|
configModule: ConfigModule
|
||||||
|
container: MedusaContainer
|
||||||
|
app: Express
|
||||||
|
pgConnection: unknown
|
||||||
|
shutdown: () => Promise<void>
|
||||||
|
prepareShutdown: () => Promise<void>
|
||||||
|
}> => {
|
||||||
|
const configModule = loadConfig(rootDirectory)
|
||||||
|
const featureFlagRouter = featureFlagsLoader(configModule, Logger)
|
||||||
const container = createMedusaContainer()
|
const container = createMedusaContainer()
|
||||||
|
|
||||||
const shouldStartAPI = configModule.projectConfig.worker_mode !== "worker"
|
|
||||||
|
|
||||||
const pgConnection = await pgConnectionLoader({ container, configModule })
|
const pgConnection = await pgConnectionLoader({ container, configModule })
|
||||||
|
|
||||||
container.register({
|
container.register({
|
||||||
[ContainerRegistrationKeys.LOGGER]: asValue(Logger),
|
[ContainerRegistrationKeys.LOGGER]: asValue(Logger),
|
||||||
[ContainerRegistrationKeys.FEATURE_FLAG_ROUTER]: asValue(featureFlagRouter),
|
[ContainerRegistrationKeys.FEATURE_FLAG_ROUTER]: asValue(featureFlagRouter),
|
||||||
@@ -115,36 +100,12 @@ async function loadMedusaV2({
|
|||||||
container,
|
container,
|
||||||
})
|
})
|
||||||
|
|
||||||
let expressShutdown = async () => {}
|
const entrypointsShutdown = await loadEntrypoints(
|
||||||
|
configModule,
|
||||||
if (shouldStartAPI) {
|
container,
|
||||||
const { shutdown } = await expressLoader({ app: expressApp, configModule })
|
expressApp,
|
||||||
expressShutdown = shutdown
|
featureFlagRouter
|
||||||
|
)
|
||||||
expressApp.use((req: Request, res: Response, next: NextFunction) => {
|
|
||||||
req.scope = container.createScope() as MedusaContainer
|
|
||||||
req.requestId = (req.headers["x-request-id"] as string) ?? v4()
|
|
||||||
next()
|
|
||||||
})
|
|
||||||
|
|
||||||
// Add additional information to context of request
|
|
||||||
expressApp.use((req: Request, res: Response, next: NextFunction) => {
|
|
||||||
const ipAddress = requestIp.getClientIp(req) as string
|
|
||||||
;(req as any).request_context = {
|
|
||||||
ip_address: ipAddress,
|
|
||||||
}
|
|
||||||
next()
|
|
||||||
})
|
|
||||||
|
|
||||||
// TODO: Add Subscribers loader
|
|
||||||
|
|
||||||
await apiLoader({
|
|
||||||
container,
|
|
||||||
app: expressApp,
|
|
||||||
configModule,
|
|
||||||
featureFlagRouter,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
await medusaProjectApisLoader({
|
await medusaProjectApisLoader({
|
||||||
rootDirectory,
|
rootDirectory,
|
||||||
@@ -162,7 +123,7 @@ async function loadMedusaV2({
|
|||||||
await promiseAll([
|
await promiseAll([
|
||||||
container.dispose(),
|
container.dispose(),
|
||||||
pgConnection?.context?.destroy(),
|
pgConnection?.context?.destroy(),
|
||||||
expressShutdown(),
|
entrypointsShutdown(),
|
||||||
medusaAppOnApplicationShutdown(),
|
medusaAppOnApplicationShutdown(),
|
||||||
])
|
])
|
||||||
}
|
}
|
||||||
@@ -176,203 +137,3 @@ async function loadMedusaV2({
|
|||||||
prepareShutdown: medusaAppOnApplicationPrepareShutdown,
|
prepareShutdown: medusaAppOnApplicationPrepareShutdown,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export default async ({
|
|
||||||
directory: rootDirectory,
|
|
||||||
expressApp,
|
|
||||||
isTest,
|
|
||||||
}: Options): Promise<{
|
|
||||||
configModule: ConfigModule
|
|
||||||
container: MedusaContainer
|
|
||||||
dbConnection?: Connection
|
|
||||||
app: Express
|
|
||||||
pgConnection: unknown
|
|
||||||
shutdown: () => Promise<void>
|
|
||||||
prepareShutdown: () => Promise<void>
|
|
||||||
}> => {
|
|
||||||
const configModule = loadConfig(rootDirectory)
|
|
||||||
const featureFlagRouter = featureFlagsLoader(configModule, Logger)
|
|
||||||
track("FEATURE_FLAGS_LOADED")
|
|
||||||
|
|
||||||
if (featureFlagRouter.isFeatureEnabled(MedusaV2Flag.key)) {
|
|
||||||
return await loadMedusaV2({
|
|
||||||
rootDirectory,
|
|
||||||
configModule,
|
|
||||||
featureFlagRouter,
|
|
||||||
expressApp,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
const container = createMedusaContainer()
|
|
||||||
container.register(
|
|
||||||
ContainerRegistrationKeys.CONFIG_MODULE,
|
|
||||||
asValue(configModule)
|
|
||||||
)
|
|
||||||
|
|
||||||
// Add additional information to context of request
|
|
||||||
expressApp.use((req: Request, res: Response, next: NextFunction) => {
|
|
||||||
const ipAddress = requestIp.getClientIp(req) as string
|
|
||||||
;(req as any).request_context = {
|
|
||||||
ip_address: ipAddress,
|
|
||||||
}
|
|
||||||
next()
|
|
||||||
})
|
|
||||||
|
|
||||||
container.register({
|
|
||||||
[ContainerRegistrationKeys.LOGGER]: asValue(Logger),
|
|
||||||
featureFlagRouter: asValue(featureFlagRouter),
|
|
||||||
})
|
|
||||||
|
|
||||||
const { shutdown: redisShutdown } = await redisLoader({
|
|
||||||
container,
|
|
||||||
configModule,
|
|
||||||
logger: Logger,
|
|
||||||
})
|
|
||||||
|
|
||||||
const modelsActivity = Logger.activity(`Initializing models${EOL}`)
|
|
||||||
track("MODELS_INIT_STARTED")
|
|
||||||
modelsLoader({ container, rootDirectory })
|
|
||||||
const mAct = Logger.success(modelsActivity, "Models initialized") || {}
|
|
||||||
track("MODELS_INIT_COMPLETED", { duration: mAct.duration })
|
|
||||||
|
|
||||||
const pmActivity = Logger.activity(`Initializing plugin models${EOL}`)
|
|
||||||
track("PLUGIN_MODELS_INIT_STARTED")
|
|
||||||
await registerPluginModels({
|
|
||||||
rootDirectory,
|
|
||||||
container,
|
|
||||||
configModule,
|
|
||||||
})
|
|
||||||
const pmAct = Logger.success(pmActivity, "Plugin models initialized") || {}
|
|
||||||
track("PLUGIN_MODELS_INIT_COMPLETED", { duration: pmAct.duration })
|
|
||||||
|
|
||||||
const stratActivity = Logger.activity(`Initializing strategies${EOL}`)
|
|
||||||
track("STRATEGIES_INIT_STARTED")
|
|
||||||
strategiesLoader({ container, configModule, isTest })
|
|
||||||
const stratAct = Logger.success(stratActivity, "Strategies initialized") || {}
|
|
||||||
track("STRATEGIES_INIT_COMPLETED", { duration: stratAct.duration })
|
|
||||||
|
|
||||||
const pgConnection = await pgConnectionLoader({ container, configModule })
|
|
||||||
|
|
||||||
const configModules = mergeDefaultModules(configModule.modules)
|
|
||||||
await loadLegacyModulesEntities(configModules, container)
|
|
||||||
|
|
||||||
const dbActivity = Logger.activity(`Initializing database${EOL}`)
|
|
||||||
track("DATABASE_INIT_STARTED")
|
|
||||||
const dbConnection = await databaseLoader({
|
|
||||||
container,
|
|
||||||
configModule,
|
|
||||||
})
|
|
||||||
const dbAct = Logger.success(dbActivity, "Database initialized") || {}
|
|
||||||
track("DATABASE_INIT_COMPLETED", { duration: dbAct.duration })
|
|
||||||
|
|
||||||
const repoActivity = Logger.activity(`Initializing repositories${EOL}`)
|
|
||||||
track("REPOSITORIES_INIT_STARTED")
|
|
||||||
repositoriesLoader({ container })
|
|
||||||
const rAct = Logger.success(repoActivity, "Repositories initialized") || {}
|
|
||||||
track("REPOSITORIES_INIT_COMPLETED", { duration: rAct.duration })
|
|
||||||
|
|
||||||
container.register({
|
|
||||||
[ContainerRegistrationKeys.MANAGER]: asValue(dataSource.manager),
|
|
||||||
})
|
|
||||||
|
|
||||||
container.register("remoteQuery", asValue(null)) // ensure remoteQuery is always registered
|
|
||||||
|
|
||||||
const servicesActivity = Logger.activity(`Initializing services${EOL}`)
|
|
||||||
track("SERVICES_INIT_STARTED")
|
|
||||||
servicesLoader({ container, configModule, isTest })
|
|
||||||
const servAct = Logger.success(servicesActivity, "Services initialized") || {}
|
|
||||||
track("SERVICES_INIT_COMPLETED", { duration: servAct.duration })
|
|
||||||
|
|
||||||
const modulesActivity = Logger.activity(`Initializing modules${EOL}`)
|
|
||||||
track("MODULES_INIT_STARTED")
|
|
||||||
|
|
||||||
// Move before services init once all modules are migrated and do not rely on core resources anymore
|
|
||||||
const {
|
|
||||||
onApplicationShutdown: medusaAppOnApplicationShutdown,
|
|
||||||
onApplicationPrepareShutdown: medusaAppOnApplicationPrepareShutdown,
|
|
||||||
} = await loadMedusaApp({
|
|
||||||
configModule,
|
|
||||||
container,
|
|
||||||
})
|
|
||||||
|
|
||||||
const modAct = Logger.success(modulesActivity, "Modules initialized") || {}
|
|
||||||
track("MODULES_INIT_COMPLETED", { duration: modAct.duration })
|
|
||||||
|
|
||||||
const expActivity = Logger.activity(`Initializing express${EOL}`)
|
|
||||||
track("EXPRESS_INIT_STARTED")
|
|
||||||
const { shutdown: expressShutdown } = await expressLoader({
|
|
||||||
app: expressApp,
|
|
||||||
configModule,
|
|
||||||
})
|
|
||||||
await passportLoader({ app: expressApp, configModule })
|
|
||||||
const exAct = Logger.success(expActivity, "Express intialized") || {}
|
|
||||||
track("EXPRESS_INIT_COMPLETED", { duration: exAct.duration })
|
|
||||||
|
|
||||||
// Add the registered services to the request scope
|
|
||||||
expressApp.use((req: Request, res: Response, next: NextFunction) => {
|
|
||||||
container.register({ manager: asValue(dataSource.manager) })
|
|
||||||
req.scope = container.createScope() as MedusaContainer
|
|
||||||
req.requestId = (req.headers["x-request-id"] as string) ?? v4()
|
|
||||||
next()
|
|
||||||
})
|
|
||||||
|
|
||||||
const pluginsActivity = Logger.activity(`Initializing plugins${EOL}`)
|
|
||||||
track("PLUGINS_INIT_STARTED")
|
|
||||||
await pluginsLoader({
|
|
||||||
container,
|
|
||||||
rootDirectory,
|
|
||||||
configModule,
|
|
||||||
app: expressApp,
|
|
||||||
activityId: pluginsActivity,
|
|
||||||
})
|
|
||||||
const pAct = Logger.success(pluginsActivity, "Plugins intialized") || {}
|
|
||||||
track("PLUGINS_INIT_COMPLETED", { duration: pAct.duration })
|
|
||||||
|
|
||||||
const subActivity = Logger.activity(`Initializing subscribers${EOL}`)
|
|
||||||
track("SUBSCRIBERS_INIT_STARTED")
|
|
||||||
subscribersLoader({ container })
|
|
||||||
const subAct = Logger.success(subActivity, "Subscribers initialized") || {}
|
|
||||||
track("SUBSCRIBERS_INIT_COMPLETED", { duration: subAct.duration })
|
|
||||||
|
|
||||||
const apiActivity = Logger.activity(`Initializing API${EOL}`)
|
|
||||||
track("API_INIT_STARTED")
|
|
||||||
await apiLoader({
|
|
||||||
container,
|
|
||||||
app: expressApp,
|
|
||||||
configModule,
|
|
||||||
featureFlagRouter,
|
|
||||||
})
|
|
||||||
const apiAct = Logger.success(apiActivity, "API initialized") || {}
|
|
||||||
track("API_INIT_COMPLETED", { duration: apiAct.duration })
|
|
||||||
|
|
||||||
const searchActivity = Logger.activity(
|
|
||||||
`Initializing search engine indexing${EOL}`
|
|
||||||
)
|
|
||||||
track("SEARCH_ENGINE_INDEXING_STARTED")
|
|
||||||
await searchIndexLoader({ container })
|
|
||||||
const searchAct =
|
|
||||||
Logger.success(searchActivity, "Indexing event emitted") || {}
|
|
||||||
track("SEARCH_ENGINE_INDEXING_COMPLETED", { duration: searchAct.duration })
|
|
||||||
|
|
||||||
async function shutdown() {
|
|
||||||
await medusaAppOnApplicationShutdown()
|
|
||||||
|
|
||||||
await promiseAll([
|
|
||||||
container.dispose(),
|
|
||||||
dbConnection?.destroy(),
|
|
||||||
pgConnection?.context?.destroy(),
|
|
||||||
redisShutdown(),
|
|
||||||
expressShutdown(),
|
|
||||||
])
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
configModule,
|
|
||||||
container,
|
|
||||||
dbConnection,
|
|
||||||
app: expressApp,
|
|
||||||
pgConnection,
|
|
||||||
shutdown,
|
|
||||||
prepareShutdown: async () => medusaAppOnApplicationPrepareShutdown(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -17,7 +17,6 @@ import {
|
|||||||
import {
|
import {
|
||||||
ContainerRegistrationKeys,
|
ContainerRegistrationKeys,
|
||||||
FlagRouter,
|
FlagRouter,
|
||||||
MedusaV2Flag,
|
|
||||||
isObject,
|
isObject,
|
||||||
} from "@medusajs/utils"
|
} from "@medusajs/utils"
|
||||||
|
|
||||||
@@ -120,8 +119,6 @@ export const loadMedusaApp = async (
|
|||||||
},
|
},
|
||||||
config = { registerInContainer: true }
|
config = { registerInContainer: true }
|
||||||
): Promise<MedusaAppOutput> => {
|
): Promise<MedusaAppOutput> => {
|
||||||
const featureFlagRouter = container.resolve<FlagRouter>("featureFlagRouter")
|
|
||||||
const isMedusaV2Enabled = featureFlagRouter.isFeatureEnabled(MedusaV2Flag.key)
|
|
||||||
const injectedDependencies = {
|
const injectedDependencies = {
|
||||||
[ContainerRegistrationKeys.PG_CONNECTION]: container.resolve(
|
[ContainerRegistrationKeys.PG_CONNECTION]: container.resolve(
|
||||||
ContainerRegistrationKeys.PG_CONNECTION
|
ContainerRegistrationKeys.PG_CONNECTION
|
||||||
@@ -174,30 +171,29 @@ export const loadMedusaApp = async (
|
|||||||
injectedDependencies,
|
injectedDependencies,
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// TODO: Remove this and make it more dynamic on ensuring all modules are loaded.
|
||||||
const requiredModuleKeys = [Modules.PRODUCT, Modules.PRICING]
|
const requiredModuleKeys = [Modules.PRODUCT, Modules.PRICING]
|
||||||
|
|
||||||
const missingPackages: string[] = []
|
const missingPackages: string[] = []
|
||||||
|
|
||||||
if (isMedusaV2Enabled) {
|
for (const requiredModuleKey of requiredModuleKeys) {
|
||||||
for (const requiredModuleKey of requiredModuleKeys) {
|
const isModuleInstalled = MedusaModule.isInstalled(requiredModuleKey)
|
||||||
const isModuleInstalled = MedusaModule.isInstalled(requiredModuleKey)
|
|
||||||
|
|
||||||
if (!isModuleInstalled) {
|
if (!isModuleInstalled) {
|
||||||
missingPackages.push(
|
missingPackages.push(
|
||||||
MODULE_PACKAGE_NAMES[requiredModuleKey] || requiredModuleKey
|
MODULE_PACKAGE_NAMES[requiredModuleKey] || requiredModuleKey
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (missingPackages.length) {
|
|
||||||
throw new Error(
|
|
||||||
`FeatureFlag medusa_v2 (MEDUSA_FF_MEDUSA_V2) requires the following packages/module registration: (${missingPackages.join(
|
|
||||||
", "
|
|
||||||
)})`
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (missingPackages.length) {
|
||||||
|
throw new Error(
|
||||||
|
`Medusa requires the following packages/module registration: (${missingPackages.join(
|
||||||
|
", "
|
||||||
|
)})`
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
if (!config.registerInContainer) {
|
if (!config.registerInContainer) {
|
||||||
return medusaApp
|
return medusaApp
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,5 @@
|
|||||||
import { MedusaV2Flag } from "@medusajs/utils"
|
|
||||||
import { MigrationInterface, QueryRunner } from "typeorm"
|
import { MigrationInterface, QueryRunner } from "typeorm"
|
||||||
|
|
||||||
export const featureFlag = MedusaV2Flag.key
|
|
||||||
|
|
||||||
export class LineItemProductId1692870898424 implements MigrationInterface {
|
export class LineItemProductId1692870898424 implements MigrationInterface {
|
||||||
public async up(queryRunner: QueryRunner): Promise<void> {
|
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||||
await queryRunner.query(`
|
await queryRunner.query(`
|
||||||
|
|||||||
-3
@@ -1,8 +1,5 @@
|
|||||||
import { MedusaV2Flag } from "@medusajs/utils"
|
|
||||||
import { MigrationInterface, QueryRunner } from "typeorm"
|
import { MigrationInterface, QueryRunner } from "typeorm"
|
||||||
|
|
||||||
export const featureFlag = MedusaV2Flag.key
|
|
||||||
|
|
||||||
export class AddTimestempsToProductShippingProfiles1692870898425
|
export class AddTimestempsToProductShippingProfiles1692870898425
|
||||||
implements MigrationInterface
|
implements MigrationInterface
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -1,8 +1,5 @@
|
|||||||
import { MedusaV2Flag } from "@medusajs/utils"
|
|
||||||
import { MigrationInterface, QueryRunner } from "typeorm"
|
import { MigrationInterface, QueryRunner } from "typeorm"
|
||||||
|
|
||||||
export const featureFlag = MedusaV2Flag.key
|
|
||||||
|
|
||||||
export class dropFksIsolatedProducts1694602553610
|
export class dropFksIsolatedProducts1694602553610
|
||||||
implements MigrationInterface
|
implements MigrationInterface
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -1,7 +1,4 @@
|
|||||||
import { MigrationInterface, QueryRunner } from "typeorm"
|
import { MigrationInterface, QueryRunner } from "typeorm"
|
||||||
import { MedusaV2Flag } from "@medusajs/utils"
|
|
||||||
|
|
||||||
export const featureFlag = MedusaV2Flag.key
|
|
||||||
|
|
||||||
export class ProductSalesChannelsLink1698056997411
|
export class ProductSalesChannelsLink1698056997411
|
||||||
implements MigrationInterface
|
implements MigrationInterface
|
||||||
|
|||||||
@@ -1,8 +1,5 @@
|
|||||||
import { MedusaV2Flag } from "@medusajs/utils"
|
|
||||||
import { MigrationInterface, QueryRunner } from "typeorm"
|
import { MigrationInterface, QueryRunner } from "typeorm"
|
||||||
|
|
||||||
export const featureFlag = MedusaV2Flag.key
|
|
||||||
|
|
||||||
export class DropNonNullConstraintPriceList1699371074198
|
export class DropNonNullConstraintPriceList1699371074198
|
||||||
implements MigrationInterface
|
implements MigrationInterface
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
import { MigrationInterface, QueryRunner } from "typeorm"
|
import { MigrationInterface, QueryRunner } from "typeorm"
|
||||||
import { MedusaV2Flag } from "@medusajs/utils"
|
|
||||||
|
|
||||||
import SalesChannelFeatureFlag from "../loaders/feature-flags/sales-channels"
|
import SalesChannelFeatureFlag from "../loaders/feature-flags/sales-channels"
|
||||||
|
|
||||||
export const featureFlag = [SalesChannelFeatureFlag.key, MedusaV2Flag.key]
|
export const featureFlag = [SalesChannelFeatureFlag.key]
|
||||||
|
|
||||||
export class OrderSalesChannelLink1701860329931 implements MigrationInterface {
|
export class OrderSalesChannelLink1701860329931 implements MigrationInterface {
|
||||||
public async up(queryRunner: QueryRunner): Promise<void> {
|
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
|||||||
@@ -8,7 +8,6 @@ import { MedusaError, isDefined } from "medusa-core-utils"
|
|||||||
import { RequestQueryFields } from "@medusajs/types"
|
import { RequestQueryFields } from "@medusajs/types"
|
||||||
import { BaseEntity } from "../interfaces"
|
import { BaseEntity } from "../interfaces"
|
||||||
import { featureFlagRouter } from "../loaders/feature-flags"
|
import { featureFlagRouter } from "../loaders/feature-flags"
|
||||||
import MedusaV2 from "../loaders/feature-flags/medusa-v2"
|
|
||||||
import { FindConfig, QueryConfig } from "../types/common"
|
import { FindConfig, QueryConfig } from "../types/common"
|
||||||
|
|
||||||
export function pickByConfig<TModel extends BaseEntity>(
|
export function pickByConfig<TModel extends BaseEntity>(
|
||||||
@@ -31,8 +30,6 @@ export function prepareListQuery<
|
|||||||
T extends RequestQueryFields,
|
T extends RequestQueryFields,
|
||||||
TEntity extends BaseEntity
|
TEntity extends BaseEntity
|
||||||
>(validated: T, queryConfig: QueryConfig<TEntity> = {}) {
|
>(validated: T, queryConfig: QueryConfig<TEntity> = {}) {
|
||||||
const isMedusaV2 = featureFlagRouter.isFeatureEnabled(MedusaV2.key)
|
|
||||||
|
|
||||||
// TODO: this function will be simplified a lot once we drop support for the old api
|
// TODO: this function will be simplified a lot once we drop support for the old api
|
||||||
const { order, fields, limit = 50, expand, offset = 0 } = validated
|
const { order, fields, limit = 50, expand, offset = 0 } = validated
|
||||||
let {
|
let {
|
||||||
@@ -190,10 +187,6 @@ export function prepareListQuery<
|
|||||||
`Order field ${orderField} is not valid`
|
`Order field ${orderField} is not valid`
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
} else {
|
|
||||||
if (!isMedusaV2) {
|
|
||||||
orderBy["created_at"] = "DESC"
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const finalOrder = isPresent(orderBy) ? orderBy : undefined
|
const finalOrder = isPresent(orderBy) ? orderBy : undefined
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ describe("transformQuery", () => {
|
|||||||
offset: number
|
offset: number
|
||||||
limit: number
|
limit: number
|
||||||
inputOrder: string | undefined
|
inputOrder: string | undefined
|
||||||
transformedOrder: Record<string, "ASC" | "DESC">
|
transformedOrder?: Record<string, "ASC" | "DESC">
|
||||||
relations?: string[]
|
relations?: string[]
|
||||||
}) => {
|
}) => {
|
||||||
expect(mockRequest.validatedQuery).toEqual({
|
expect(mockRequest.validatedQuery).toEqual({
|
||||||
@@ -115,9 +115,6 @@ describe("transformQuery", () => {
|
|||||||
limit: 20,
|
limit: 20,
|
||||||
offset: 0,
|
offset: 0,
|
||||||
inputOrder: undefined,
|
inputOrder: undefined,
|
||||||
transformedOrder: {
|
|
||||||
created_at: "DESC",
|
|
||||||
},
|
|
||||||
})
|
})
|
||||||
|
|
||||||
//////////////////////////////
|
//////////////////////////////
|
||||||
|
|||||||
@@ -1,34 +1,11 @@
|
|||||||
import { ContainerRegistrationKeys, MedusaV2Flag } from "@medusajs/utils"
|
|
||||||
import { NextFunction, Request, RequestHandler, Response } from "express"
|
import { NextFunction, Request, RequestHandler, Response } from "express"
|
||||||
|
|
||||||
import passport from "passport"
|
// TODO: See how this should look like for v2.
|
||||||
|
|
||||||
// Optional customer authentication
|
// Optional customer authentication
|
||||||
// If authenticated, middleware attaches customer to request (as user) otherwise we pass through
|
// If authenticated, middleware attaches customer to request (as user) otherwise we pass through
|
||||||
// If you want to require authentication, use `requireCustomerAuthentication` in `packages/medusa/src/api/middlewares/require-customer-authentication.ts`
|
// If you want to require authentication, use `requireCustomerAuthentication` in `packages/medusa/src/api/middlewares/require-customer-authentication.ts`
|
||||||
export default (): RequestHandler => {
|
export default (): RequestHandler => {
|
||||||
return (req: Request, res: Response, next: NextFunction): void => {
|
return (req: Request, res: Response, next: NextFunction): void => {
|
||||||
const featureFlagRouter = req.scope.resolve(
|
return next()
|
||||||
ContainerRegistrationKeys.FEATURE_FLAG_ROUTER
|
|
||||||
)
|
|
||||||
if (featureFlagRouter.isFeatureEnabled(MedusaV2Flag.key)) {
|
|
||||||
return next()
|
|
||||||
}
|
|
||||||
|
|
||||||
passport.authenticate(
|
|
||||||
["store-session", "store-bearer"],
|
|
||||||
{ session: false },
|
|
||||||
(err, user) => {
|
|
||||||
if (err) {
|
|
||||||
return next(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if (user) {
|
|
||||||
req.user = user
|
|
||||||
}
|
|
||||||
|
|
||||||
return next()
|
|
||||||
}
|
|
||||||
)(req, res, next)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,19 +1,8 @@
|
|||||||
import { ContainerRegistrationKeys, MedusaV2Flag } from "@medusajs/utils"
|
|
||||||
import { NextFunction, Request, RequestHandler, Response } from "express"
|
import { NextFunction, Request, RequestHandler, Response } from "express"
|
||||||
|
|
||||||
import passport from "passport"
|
// TODO: See how this should look like for v2.
|
||||||
|
|
||||||
export default (): RequestHandler => {
|
export default (): RequestHandler => {
|
||||||
return (req: Request, res: Response, next: NextFunction): void => {
|
return (req: Request, res: Response, next: NextFunction): void => {
|
||||||
const featureFlagRouter = req.scope.resolve(
|
return next()
|
||||||
ContainerRegistrationKeys.FEATURE_FLAG_ROUTER
|
|
||||||
)
|
|
||||||
if (featureFlagRouter.isFeatureEnabled(MedusaV2Flag.key)) {
|
|
||||||
return next()
|
|
||||||
}
|
|
||||||
passport.authenticate(
|
|
||||||
["admin-session", "admin-bearer", "admin-api-token"],
|
|
||||||
{ session: false }
|
|
||||||
)(req, res, next)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user