Files
medusa-store/packages/medusa-test-utils/src/init-modules.ts
Adrien de Peretti ab22faaa52 Chore/test runner improvements (#12439)
**What**
Make sure there is no open handles left and that the shutdown function are properly called. Refactor and improve the medusa test runner. Make sure all modules instances are released and cleaned up

**NOTE:**
On a separate PR we can continue the investigation for the memory growing over time while the tests execute
2025-05-14 13:17:41 +00:00

86 lines
2.1 KiB
TypeScript

import {
ExternalModuleDeclaration,
InternalModuleDeclaration,
ModuleJoinerConfig,
} from "@medusajs/framework/types"
import {
ContainerRegistrationKeys,
createPgConnection,
promiseAll,
} from "@medusajs/framework/utils"
import { logger } from "@medusajs/framework/logger"
export interface InitModulesOptions {
injectedDependencies?: Record<string, unknown>
databaseConfig: {
clientUrl: string
schema?: string
}
modulesConfig: {
[key: string]:
| string
| boolean
| Partial<InternalModuleDeclaration | ExternalModuleDeclaration>
}
joinerConfig?: ModuleJoinerConfig[]
preventConnectionDestroyWarning?: boolean
}
export async function initModules({
injectedDependencies,
databaseConfig,
modulesConfig,
joinerConfig,
preventConnectionDestroyWarning = false,
}: InitModulesOptions) {
const moduleSdkImports = require("@medusajs/framework/modules-sdk")
injectedDependencies ??= {}
let sharedPgConnection =
injectedDependencies?.[ContainerRegistrationKeys.PG_CONNECTION]
let shouldDestroyConnectionAutomatically = !sharedPgConnection
if (!sharedPgConnection) {
sharedPgConnection = createPgConnection({
clientUrl: databaseConfig.clientUrl,
schema: databaseConfig.schema,
})
injectedDependencies[ContainerRegistrationKeys.PG_CONNECTION] =
sharedPgConnection
}
const medusaApp = await moduleSdkImports.MedusaApp({
modulesConfig,
servicesConfig: joinerConfig,
injectedDependencies,
})
await medusaApp.onApplicationStart()
async function shutdown() {
if (shouldDestroyConnectionAutomatically) {
await medusaApp.onApplicationPrepareShutdown()
await promiseAll([
(sharedPgConnection as any).context?.destroy(),
(sharedPgConnection as any).destroy(),
medusaApp.onApplicationShutdown(),
])
} else {
if (!preventConnectionDestroyWarning) {
logger.info(
`You are using a custom shared connection. The connection won't be destroyed automatically.`
)
}
}
moduleSdkImports.MedusaModule.clearInstances()
}
return {
medusaApp,
shutdown,
}
}