|
1
|
import { logger } from "@medusajs/framework/logger" |
|
2
|
import { |
|
3
|
ExternalModuleDeclaration, |
|
4
|
InternalModuleDeclaration, |
|
5
|
} from "@medusajs/framework/types" |
|
6
|
import { |
|
7
|
ContainerRegistrationKeys, |
|
8
|
createPgConnection, |
|
9
|
promiseAll, |
|
10
|
} from "@medusajs/framework/utils" |
|
11
|
|
|
12
|
export interface InitModulesOptions { |
|
13
|
injectedDependencies?: Record<string, unknown> |
|
14
|
databaseConfig: { |
|
15
|
clientUrl: string |
|
16
|
schema?: string |
|
17
|
} |
|
18
|
modulesConfig: { |
|
19
|
[key: string]: |
|
20
|
| string |
|
21
|
| boolean |
|
22
|
| Partial<InternalModuleDeclaration | ExternalModuleDeclaration> |
|
23
|
} |
|
24
|
preventConnectionDestroyWarning?: boolean |
|
25
|
cwd?: string |
|
26
|
} |
|
27
|
|
|
28
|
export async function initModules({ |
|
29
|
injectedDependencies, |
|
30
|
databaseConfig, |
|
31
|
modulesConfig, |
|
32
|
preventConnectionDestroyWarning = false, |
|
33
|
cwd, |
|
34
|
}: InitModulesOptions) { |
|
35
|
const moduleSdkImports = require("@medusajs/framework/modules-sdk") |
|
36
|
|
|
37
|
injectedDependencies ??= {} |
|
38
|
|
|
39
|
let sharedPgConnection = |
|
40
|
injectedDependencies?.[ContainerRegistrationKeys.PG_CONNECTION] |
|
41
|
|
|
42
|
let shouldDestroyConnectionAutomatically = !sharedPgConnection |
|
43
|
if (!sharedPgConnection) { |
|
44
|
sharedPgConnection = createPgConnection({ |
|
45
|
clientUrl: databaseConfig.clientUrl, |
|
46
|
schema: databaseConfig.schema, |
|
47
|
}) |
|
48
|
|
|
49
|
injectedDependencies[ContainerRegistrationKeys.PG_CONNECTION] = |
|
50
|
sharedPgConnection |
|
51
|
} |
|
52
|
|
|
53
|
const medusaApp = await moduleSdkImports.MedusaApp({ |
|
54
|
modulesConfig, |
|
55
|
injectedDependencies, |
|
56
|
cwd, |
|
57
|
}) |
|
58
|
|
|
59
|
await medusaApp.onApplicationStart() |
|
60
|
|
|
61
|
async function shutdown() { |
|
62
|
const promises: Promise<void>[] = [] |
|
63
|
|
|
64
|
if (shouldDestroyConnectionAutomatically) { |
|
65
|
promises.push((sharedPgConnection as any).context?.destroy()) |
|
66
|
promises.push((sharedPgConnection as any).destroy()) |
|
67
|
promises.push(medusaApp.onApplicationPrepareShutdown()) |
|
68
|
promises.push(medusaApp.onApplicationShutdown()) |
|
69
|
} else { |
|
70
|
if (!preventConnectionDestroyWarning) { |
|
71
|
logger.info( |
|
72
|
`You are using a custom shared connection. The connection won't be destroyed automatically.` |
|
73
|
) |
|
74
|
} |
|
75
|
} |
|
76
|
|
|
77
|
await promiseAll(promises) |
|
78
|
moduleSdkImports.MedusaModule.clearInstances() |
|
79
|
} |
|
80
|
|
|
81
|
return { |
|
82
|
medusaApp, |
|
83
|
shutdown, |
|
84
|
} |
|
85
|
} |