|
1
|
import { |
|
2
|
ConfigModule, |
|
3
|
Constructor, |
|
4
|
IModuleService, |
|
5
|
InternalModuleDeclaration, |
|
6
|
LoaderOptions, |
|
7
|
Logger, |
|
8
|
MedusaContainer, |
|
9
|
ModuleExports, |
|
10
|
ModuleLoaderFunction, |
|
11
|
ModuleProvider, |
|
12
|
ModuleProviderExports, |
|
13
|
ModuleProviderLoaderFunction, |
|
14
|
ModuleResolution, |
|
15
|
} from "@medusajs/types" |
|
16
|
import { |
|
17
|
ContainerRegistrationKeys, |
|
18
|
createMedusaContainer, |
|
19
|
defineJoinerConfig, |
|
20
|
discoverAndRegisterFeatureFlags, |
|
21
|
DmlEntity, |
|
22
|
dynamicImport, |
|
23
|
FeatureFlag, |
|
24
|
getProviderRegistrationKey, |
|
25
|
isFileSkipped, |
|
26
|
isString, |
|
27
|
MedusaModuleProviderType, |
|
28
|
MedusaModuleType, |
|
29
|
Modules, |
|
30
|
ModulesSdkUtils, |
|
31
|
stringifyCircular, |
|
32
|
toMikroOrmEntities, |
|
33
|
} from "@medusajs/utils" |
|
34
|
import { asFunction, asValue } from "@medusajs/deps/awilix" |
|
35
|
import { statSync } from "fs" |
|
36
|
import { readdir } from "fs/promises" |
|
37
|
import { dirname, join, resolve } from "path" |
|
38
|
|
|
39
|
type ModuleResource = { |
|
40
|
services: Function[] |
|
41
|
models: Function[] |
|
42
|
repositories: Function[] |
|
43
|
loaders: ModuleLoaderFunction[] | ModuleProviderLoaderFunction[] |
|
44
|
moduleService: Constructor<any> |
|
45
|
normalizedPath: string |
|
46
|
} |
|
47
|
|
|
48
|
type LoadInternalArgs = { |
|
49
|
container: MedusaContainer |
|
50
|
resolution: ModuleResolution |
|
51
|
logger: Logger |
|
52
|
migrationOnly?: boolean |
|
53
|
schemaOnly?: boolean |
|
54
|
loaderOnly?: boolean |
|
55
|
} |
|
56
|
|
|
57
|
type MigrationFunction = ( |
|
58
|
options: LoaderOptions<any>, |
|
59
|
moduleDeclaration?: InternalModuleDeclaration |
|
60
|
) => Promise<{ name: string; path: string }[]> |
|
61
|
type RevertMigrationFunction = ( |
|
62
|
options: LoaderOptions<any> & { migrationNames?: string[] }, |
|
63
|
moduleDeclaration?: InternalModuleDeclaration |
|
64
|
) => Promise<void> |
|
65
|
type GenerateMigrationFunction = ( |
|
66
|
options: LoaderOptions<any>, |
|
67
|
moduleDeclaration?: InternalModuleDeclaration |
|
68
|
) => Promise<void> |
|
69
|
|
|
70
|
type ResolvedModule = ModuleExports & { |
|
71
|
discoveryPath: string |
|
72
|
} |
|
73
|
|
|
74
|
type ResolvedModuleProvider = ModuleProviderExports & { |
|
75
|
discoveryPath: string |
|
76
|
} |
|
77
|
|
|
78
|
export async function resolveModuleExports({ |
|
79
|
resolution, |
|
80
|
}: { |
|
81
|
resolution: ModuleResolution |
|
82
|
}): Promise<ResolvedModule | ResolvedModuleProvider | { error: any }> { |
|
83
|
let resolvedModuleExports: ModuleExports |
|
84
|
try { |
|
85
|
if (resolution.moduleExports) { |
|
86
|
// TODO: |
|
87
|
// If we want to benefit from the auto load mechanism, even if the module exports is provided, we need to ask for the module path |
|
88
|
resolvedModuleExports = resolution.moduleExports as ModuleExports |
|
89
|
resolvedModuleExports.discoveryPath = resolution.resolutionPath as string |
|
90
|
} else { |
|
91
|
const module = await dynamicImport(resolution.resolutionPath as string) |
|
92
|
|
|
93
|
if ("discoveryPath" in module) { |
|
94
|
const reExportedLoadedModule = await dynamicImport(module.discoveryPath) |
|
95
|
const discoveryPath = module.discoveryPath |
|
96
|
resolvedModuleExports = |
|
97
|
reExportedLoadedModule.default ?? reExportedLoadedModule |
|
98
|
resolvedModuleExports.discoveryPath = discoveryPath as string |
|
99
|
} else { |
|
100
|
resolvedModuleExports = |
|
101
|
(module as { default: ModuleExports }).default ?? module |
|
102
|
resolvedModuleExports.discoveryPath = |
|
103
|
resolution.resolutionPath as string |
|
104
|
} |
|
105
|
} |
|
106
|
|
|
107
|
return resolvedModuleExports as ModuleExports & { |
|
108
|
discoveryPath: string |
|
109
|
} |
|
110
|
} catch (error) { |
|
111
|
if ( |
|
112
|
resolution.definition.isRequired && |
|
113
|
resolution.definition.defaultPackage |
|
114
|
) { |
|
115
|
return { |
|
116
|
error: new Error( |
|
117
|
`Make sure you have installed the default package: ${resolution.definition.defaultPackage}` |
|
118
|
), |
|
119
|
} |
|
120
|
} |
|
121
|
|
|
122
|
return { error } |
|
123
|
} |
|
124
|
} |
|
125
|
|
|
126
|
async function loadInternalProvider( |
|
127
|
args: LoadInternalArgs, |
|
128
|
providers: ModuleProvider[] |
|
129
|
): Promise<{ error?: Error } | void> { |
|
130
|
const { container, resolution, logger, migrationOnly, schemaOnly } = args |
|
131
|
|
|
132
|
const errors: { error?: Error }[] = [] |
|
133
|
for (const provider of providers) { |
|
134
|
const providerRes = provider.resolve as ModuleProviderExports |
|
135
|
|
|
136
|
const canLoadProvider = |
|
137
|
providerRes && (isString(providerRes) || !providerRes?.services) |
|
138
|
|
|
139
|
if (!canLoadProvider) { |
|
140
|
continue |
|
141
|
} |
|
142
|
|
|
143
|
const res = await loadInternalModule({ |
|
144
|
container, |
|
145
|
resolution: { |
|
146
|
...resolution, |
|
147
|
moduleExports: !isString(providerRes) ? providerRes : undefined, |
|
148
|
definition: { |
|
149
|
...resolution.definition, |
|
150
|
key: provider.id!, |
|
151
|
}, |
|
152
|
resolutionPath: isString(provider.resolve) |
|
153
|
? require.resolve(provider.resolve, { |
|
154
|
paths: [process.cwd()], |
|
155
|
}) |
|
156
|
: false, |
|
157
|
}, |
|
158
|
logger, |
|
159
|
migrationOnly, |
|
160
|
schemaOnly, |
|
161
|
loadingProviders: true, |
|
162
|
}) |
|
163
|
|
|
164
|
if (res) { |
|
165
|
errors.push(res) |
|
166
|
} |
|
167
|
} |
|
168
|
|
|
169
|
const errorMessages = errors.map((e) => e.error?.message).join("\n") |
|
170
|
return errors.length |
|
171
|
? { |
|
172
|
error: { |
|
173
|
name: "ModuleProviderError", |
|
174
|
message: `Errors while loading module providers for module ${resolution.definition.key}:\n${errorMessages}`, |
|
175
|
stack: errors.map((e) => e.error?.stack).join("\n"), |
|
176
|
}, |
|
177
|
} |
|
178
|
: undefined |
|
179
|
} |
|
180
|
|
|
181
|
export async function loadInternalModule(args: { |
|
182
|
container: MedusaContainer |
|
183
|
resolution: ModuleResolution |
|
184
|
logger: Logger |
|
185
|
migrationOnly?: boolean |
|
186
|
loaderOnly?: boolean |
|
187
|
loadingProviders?: boolean |
|
188
|
schemaOnly?: boolean |
|
189
|
}): Promise<{ error?: Error } | void> { |
|
190
|
const { |
|
191
|
container, |
|
192
|
resolution, |
|
193
|
logger, |
|
194
|
migrationOnly, |
|
195
|
loaderOnly, |
|
196
|
loadingProviders, |
|
197
|
schemaOnly, |
|
198
|
} = args |
|
199
|
|
|
200
|
const keyName = !loaderOnly |
|
201
|
? resolution.definition.key |
|
202
|
: resolution.definition.key + "__loaderOnly" |
|
203
|
|
|
204
|
const loadedModule = await resolveModuleExports({ resolution }) |
|
205
|
|
|
206
|
if ("error" in loadedModule) { |
|
207
|
return loadedModule |
|
208
|
} |
|
209
|
|
|
210
|
let moduleResources = {} as ModuleResource |
|
211
|
|
|
212
|
if (loadedModule.discoveryPath) { |
|
213
|
moduleResources = await loadResources({ |
|
214
|
container, |
|
215
|
moduleResolution: resolution, |
|
216
|
discoveryPath: loadedModule.discoveryPath, |
|
217
|
logger, |
|
218
|
loadedModuleLoaders: loadedModule?.loaders, |
|
219
|
}) |
|
220
|
} |
|
221
|
|
|
222
|
const loadedModule_ = loadedModule as ModuleExports |
|
223
|
if ( |
|
224
|
!loadingProviders && |
|
225
|
!loadedModule_?.service && |
|
226
|
!moduleResources.moduleService |
|
227
|
) { |
|
228
|
container.register({ |
|
229
|
[keyName]: asValue(undefined), |
|
230
|
}) |
|
231
|
|
|
232
|
return { |
|
233
|
error: new Error( |
|
234
|
`No service found in module ${resolution?.definition?.label}. Make sure your module exports a service.` |
|
235
|
), |
|
236
|
} |
|
237
|
} |
|
238
|
|
|
239
|
const localContainer = createMedusaContainer() |
|
240
|
|
|
241
|
const dependencies = resolution?.dependencies ?? [] |
|
242
|
|
|
243
|
dependencies.push( |
|
244
|
ContainerRegistrationKeys.MANAGER, |
|
245
|
ContainerRegistrationKeys.CONFIG_MODULE, |
|
246
|
ContainerRegistrationKeys.LOGGER, |
|
247
|
ContainerRegistrationKeys.PG_CONNECTION, |
|
248
|
Modules.EVENT_BUS, |
|
249
|
Modules.CACHING |
|
250
|
) |
|
251
|
|
|
252
|
for (const dependency of dependencies) { |
|
253
|
localContainer.register( |
|
254
|
dependency, |
|
255
|
asFunction(() => { |
|
256
|
return container.resolve(dependency, { allowUnregistered: true }) |
|
257
|
}) |
|
258
|
) |
|
259
|
} |
|
260
|
|
|
261
|
if (resolution.definition.__passSharedContainer) { |
|
262
|
localContainer.register( |
|
263
|
"sharedContainer", |
|
264
|
asFunction(() => { |
|
265
|
return container |
|
266
|
}) |
|
267
|
) |
|
268
|
} |
|
269
|
|
|
270
|
// if module has providers, load them |
|
271
|
let providerOptions: any = undefined |
|
272
|
if (!loadingProviders) { |
|
273
|
const providers = (resolution?.options?.providers as any[]) ?? [] |
|
274
|
|
|
275
|
const res = await loadInternalProvider( |
|
276
|
{ |
|
277
|
...args, |
|
278
|
container: localContainer, |
|
279
|
}, |
|
280
|
providers |
|
281
|
) |
|
282
|
|
|
283
|
if (res?.error) { |
|
284
|
return res |
|
285
|
} |
|
286
|
} else { |
|
287
|
providerOptions = (resolution?.options?.providers as any[]).find( |
|
288
|
(p) => p.id === resolution.definition.key |
|
289
|
)?.options |
|
290
|
} |
|
291
|
|
|
292
|
// Partial module load: register only __joinerConfig |
|
293
|
// - migrationOnly: needed for migration planning + loader execution |
|
294
|
// - schemaOnly: needed for GraphQL schema + type generation |
|
295
|
if ((schemaOnly || migrationOnly) && !loadingProviders) { |
|
296
|
const moduleService_ = |
|
297
|
moduleResources.moduleService ?? loadedModule_.service |
|
298
|
|
|
299
|
// Partially loaded module, only register the service __joinerConfig function to be able to resolve it later |
|
300
|
const moduleService = { |
|
301
|
__joinerConfig: moduleService_.prototype.__joinerConfig, |
|
302
|
} |
|
303
|
|
|
304
|
container.register({ |
|
305
|
[keyName]: asValue(moduleService), |
|
306
|
}) |
|
307
|
|
|
308
|
return |
|
309
|
} |
|
310
|
|
|
311
|
if (schemaOnly) { |
|
312
|
// in schema only mode, we only need to register the service __joinerConfig function to be able to resolve it later |
|
313
|
// For providers in schema-only mode, skip without registration |
|
314
|
return |
|
315
|
} |
|
316
|
|
|
317
|
const loaders = moduleResources.loaders ?? loadedModule?.loaders ?? [] |
|
318
|
const error = await runLoaders(loaders, { |
|
319
|
container, |
|
320
|
localContainer, |
|
321
|
logger, |
|
322
|
resolution, |
|
323
|
loaderOnly, |
|
324
|
keyName, |
|
325
|
providerOptions, |
|
326
|
}) |
|
327
|
|
|
328
|
if (error) { |
|
329
|
return error |
|
330
|
} |
|
331
|
|
|
332
|
if (loadingProviders) { |
|
333
|
const loadedProvider_ = loadedModule as ModuleProviderExports |
|
334
|
|
|
335
|
let moduleProviderServices = moduleResources.moduleService |
|
336
|
? [moduleResources.moduleService] |
|
337
|
: loadedProvider_.services ?? loadedProvider_ |
|
338
|
|
|
339
|
if (!moduleProviderServices) { |
|
340
|
return |
|
341
|
} |
|
342
|
|
|
343
|
for (const moduleProviderService of moduleProviderServices) { |
|
344
|
const modProvider_ = moduleProviderService as any |
|
345
|
|
|
346
|
const originalIdentifier = modProvider_.identifier as string |
|
347
|
const providerId = keyName |
|
348
|
|
|
349
|
if (!originalIdentifier) { |
|
350
|
const providerResolutionName = |
|
351
|
modProvider_.DISPLAY_NAME ?? resolution.resolutionPath |
|
352
|
|
|
353
|
throw new Error( |
|
354
|
`Module provider ${providerResolutionName} does not have a static "identifier" property on its service class.` |
|
355
|
) |
|
356
|
} |
|
357
|
|
|
358
|
const alreadyRegisteredProvider = container.hasRegistration( |
|
359
|
getProviderRegistrationKey({ |
|
360
|
providerId, |
|
361
|
providerIdentifier: originalIdentifier, |
|
362
|
}) |
|
363
|
) |
|
364
|
if (alreadyRegisteredProvider) { |
|
365
|
throw new Error( |
|
366
|
`Module provider ${originalIdentifier} has already been registered. Please provide a different "id" in the provider options.` |
|
367
|
) |
|
368
|
} |
|
369
|
|
|
370
|
modProvider_.__type = MedusaModuleProviderType |
|
371
|
|
|
372
|
const registrationKey = getProviderRegistrationKey({ |
|
373
|
providerId, |
|
374
|
providerIdentifier: originalIdentifier, |
|
375
|
}) |
|
376
|
|
|
377
|
container.register({ |
|
378
|
[registrationKey]: asFunction(() => { |
|
379
|
;(moduleProviderService as any).__type = MedusaModuleType |
|
380
|
return new moduleProviderService( |
|
381
|
localContainer.cradle, |
|
382
|
resolution.options, |
|
383
|
resolution.moduleDeclaration |
|
384
|
) |
|
385
|
}).singleton(), |
|
386
|
}) |
|
387
|
} |
|
388
|
} else { |
|
389
|
const moduleService = moduleResources.moduleService ?? loadedModule_.service |
|
390
|
container.register({ |
|
391
|
[keyName]: asFunction((cradle) => { |
|
392
|
;(moduleService as any).__type = MedusaModuleType |
|
393
|
return new moduleService( |
|
394
|
localContainer.cradle, |
|
395
|
resolution.options, |
|
396
|
resolution.moduleDeclaration |
|
397
|
) |
|
398
|
}).singleton(), |
|
399
|
}) |
|
400
|
} |
|
401
|
|
|
402
|
if (loaderOnly) { |
|
403
|
// The expectation is only to run the loader as standalone, so we do not need to register the service and we need to cleanup all services |
|
404
|
const service = container.resolve<IModuleService>(keyName) |
|
405
|
await service.__hooks?.onApplicationPrepareShutdown?.() |
|
406
|
await service.__hooks?.onApplicationShutdown?.() |
|
407
|
} |
|
408
|
} |
|
409
|
|
|
410
|
export async function loadModuleMigrations( |
|
411
|
container: MedusaContainer, |
|
412
|
resolution: ModuleResolution, |
|
413
|
moduleExports?: ModuleExports |
|
414
|
): Promise<{ |
|
415
|
runMigrations?: MigrationFunction |
|
416
|
revertMigration?: RevertMigrationFunction |
|
417
|
generateMigration?: GenerateMigrationFunction |
|
418
|
}> { |
|
419
|
const runMigrationsFn: ((...args) => Promise<any>)[] = [] |
|
420
|
const revertMigrationFn: ((...args) => Promise<any>)[] = [] |
|
421
|
const generateMigrationFn: ((...args) => Promise<any>)[] = [] |
|
422
|
|
|
423
|
try { |
|
424
|
const mainLoadedModule = await resolveModuleExports({ |
|
425
|
resolution: { ...resolution, moduleExports }, |
|
426
|
}) |
|
427
|
if ("error" in mainLoadedModule) { |
|
428
|
throw mainLoadedModule.error |
|
429
|
} |
|
430
|
|
|
431
|
const loadedServices = [mainLoadedModule] as ( |
|
432
|
| ResolvedModule |
|
433
|
| ResolvedModuleProvider |
|
434
|
)[] |
|
435
|
|
|
436
|
if (Array.isArray(resolution?.options?.providers)) { |
|
437
|
for (const provider of (resolution.options as any).providers) { |
|
438
|
const providerRes = provider.resolve as ModuleProviderExports |
|
439
|
|
|
440
|
const canLoadProvider = |
|
441
|
providerRes && (isString(providerRes) || !providerRes?.services) |
|
442
|
|
|
443
|
if (!canLoadProvider) { |
|
444
|
continue |
|
445
|
} |
|
446
|
|
|
447
|
const loadedProvider = await resolveModuleExports({ |
|
448
|
resolution: { |
|
449
|
...resolution, |
|
450
|
moduleExports: !isString(providerRes) ? providerRes : undefined, |
|
451
|
definition: { |
|
452
|
...resolution.definition, |
|
453
|
key: provider.id, |
|
454
|
}, |
|
455
|
resolutionPath: isString(provider.resolve) |
|
456
|
? require.resolve(provider.resolve, { paths: [process.cwd()] }) |
|
457
|
: false, |
|
458
|
}, |
|
459
|
}) |
|
460
|
|
|
461
|
if ("error" in loadedProvider) { |
|
462
|
throw loadedProvider.error |
|
463
|
} |
|
464
|
|
|
465
|
loadedServices.push(loadedProvider as ResolvedModuleProvider) |
|
466
|
} |
|
467
|
} |
|
468
|
|
|
469
|
const migrationScripts: any[] = [] |
|
470
|
for (const loadedModule of loadedServices) { |
|
471
|
let runMigrationsCustom = loadedModule.runMigrations |
|
472
|
let revertMigrationCustom = loadedModule.revertMigration |
|
473
|
let generateMigrationCustom = loadedModule.generateMigration |
|
474
|
|
|
475
|
runMigrationsCustom && runMigrationsFn.push(runMigrationsCustom) |
|
476
|
revertMigrationCustom && revertMigrationFn.push(revertMigrationCustom) |
|
477
|
generateMigrationCustom && |
|
478
|
generateMigrationFn.push(generateMigrationCustom) |
|
479
|
|
|
480
|
if (!runMigrationsCustom || !revertMigrationCustom) { |
|
481
|
const moduleResources = await loadResources({ |
|
482
|
container, |
|
483
|
moduleResolution: resolution, |
|
484
|
discoveryPath: loadedModule.discoveryPath, |
|
485
|
loadedModuleLoaders: loadedModule?.loaders, |
|
486
|
}) |
|
487
|
|
|
488
|
migrationScripts.push({ |
|
489
|
moduleName: resolution.definition.key, |
|
490
|
models: moduleResources.models, |
|
491
|
pathToMigrations: join(moduleResources.normalizedPath, "migrations"), |
|
492
|
}) |
|
493
|
} |
|
494
|
|
|
495
|
for (const migrationScriptOptions of migrationScripts) { |
|
496
|
const migrationUp = |
|
497
|
runMigrationsCustom ?? |
|
498
|
ModulesSdkUtils.buildMigrationScript(migrationScriptOptions) |
|
499
|
runMigrationsFn.push(migrationUp) |
|
500
|
|
|
501
|
const migrationDown = |
|
502
|
revertMigrationCustom ?? |
|
503
|
ModulesSdkUtils.buildRevertMigrationScript(migrationScriptOptions) |
|
504
|
revertMigrationFn.push(migrationDown) |
|
505
|
|
|
506
|
const genMigration = |
|
507
|
generateMigrationCustom ?? |
|
508
|
ModulesSdkUtils.buildGenerateMigrationScript(migrationScriptOptions) |
|
509
|
generateMigrationFn.push(genMigration) |
|
510
|
} |
|
511
|
} |
|
512
|
|
|
513
|
const runMigrations = async (...args) => { |
|
514
|
let result: { name: string; path: string }[] = [] |
|
515
|
for (const migration of runMigrationsFn.filter(Boolean)) { |
|
516
|
const res = await migration.apply(migration, args) |
|
517
|
result.push(...res) |
|
518
|
} |
|
519
|
return result |
|
520
|
} |
|
521
|
const revertMigration = async (...args) => { |
|
522
|
for (const migration of revertMigrationFn.filter(Boolean)) { |
|
523
|
await migration.apply(migration, args) |
|
524
|
} |
|
525
|
} |
|
526
|
const generateMigration = async (...args) => { |
|
527
|
for (const migration of generateMigrationFn.filter(Boolean)) { |
|
528
|
await migration.apply(migration, args) |
|
529
|
} |
|
530
|
} |
|
531
|
|
|
532
|
return { |
|
533
|
runMigrations, |
|
534
|
revertMigration, |
|
535
|
generateMigration, |
|
536
|
} |
|
537
|
} catch (e) { |
|
538
|
throw new Error( |
|
539
|
`Unable to resolve the migration scripts for the module ${resolution.definition.key}\n${e.message}\n${e.stack}` |
|
540
|
) |
|
541
|
} |
|
542
|
} |
|
543
|
|
|
544
|
async function importAllFromDir(path: string) { |
|
545
|
let filesToLoad: string[] = [] |
|
546
|
|
|
547
|
const excludedExtensions = [".ts.map", ".js.map", ".d.ts"] |
|
548
|
|
|
549
|
await readdir(path).then((files) => { |
|
550
|
files.forEach((file) => { |
|
551
|
if ( |
|
552
|
file.startsWith("index.") || |
|
553
|
excludedExtensions.some((ext) => file.endsWith(ext)) |
|
554
|
) { |
|
555
|
return |
|
556
|
} |
|
557
|
|
|
558
|
const filePath = join(path, file) |
|
559
|
const stats = statSync(filePath) |
|
560
|
|
|
561
|
if (stats.isDirectory()) { |
|
562
|
// TODO: should we handle that? dont think so but I put that here for discussion |
|
563
|
} else if (stats.isFile()) { |
|
564
|
filesToLoad.push(filePath) |
|
565
|
} |
|
566
|
}) |
|
567
|
|
|
568
|
return filesToLoad |
|
569
|
}) |
|
570
|
|
|
571
|
return ( |
|
572
|
await Promise.all(filesToLoad.map((filePath) => dynamicImport(filePath))) |
|
573
|
) |
|
574
|
.filter((value) => !isFileSkipped(value)) |
|
575
|
.flatMap((value) => { |
|
576
|
return Object.values(value) |
|
577
|
}) |
|
578
|
} |
|
579
|
|
|
580
|
export async function loadResources({ |
|
581
|
container, |
|
582
|
moduleResolution, |
|
583
|
discoveryPath, |
|
584
|
logger, |
|
585
|
loadedModuleLoaders, |
|
586
|
}: { |
|
587
|
container: MedusaContainer |
|
588
|
moduleResolution: ModuleResolution |
|
589
|
discoveryPath: string |
|
590
|
logger?: Logger |
|
591
|
loadedModuleLoaders?: ModuleLoaderFunction[] | ModuleProviderLoaderFunction[] |
|
592
|
}): Promise<ModuleResource> { |
|
593
|
logger ??= console as unknown as Logger |
|
594
|
loadedModuleLoaders ??= [] |
|
595
|
|
|
596
|
const modulePath = discoveryPath |
|
597
|
let normalizedPath = dirname( |
|
598
|
require.resolve(modulePath, { paths: [process.cwd()] }) |
|
599
|
) |
|
600
|
normalizedPath = resolve(normalizedPath) |
|
601
|
|
|
602
|
try { |
|
603
|
const defaultOnFail = () => { |
|
604
|
return [] |
|
605
|
} |
|
606
|
|
|
607
|
const flagDir = resolve(normalizedPath) |
|
608
|
|
|
609
|
const configModule = container.resolve( |
|
610
|
ContainerRegistrationKeys.CONFIG_MODULE, |
|
611
|
{ |
|
612
|
allowUnregistered: true, |
|
613
|
} |
|
614
|
) as ConfigModule |
|
615
|
|
|
616
|
await discoverAndRegisterFeatureFlags({ |
|
617
|
flagDir, |
|
618
|
projectConfigFlags: configModule?.featureFlags ?? {}, |
|
619
|
router: FeatureFlag, |
|
620
|
logger, |
|
621
|
maxDepth: 1, |
|
622
|
}) |
|
623
|
|
|
624
|
const [moduleService, services, models, repositories] = await Promise.all([ |
|
625
|
dynamicImport(modulePath).then((moduleExports) => { |
|
626
|
if (isFileSkipped(moduleExports)) { |
|
627
|
return |
|
628
|
} |
|
629
|
|
|
630
|
const mod = moduleExports.default ?? moduleExports |
|
631
|
return mod.service |
|
632
|
}), |
|
633
|
importAllFromDir(resolve(normalizedPath, "services")).catch( |
|
634
|
defaultOnFail |
|
635
|
), |
|
636
|
importAllFromDir(resolve(normalizedPath, "models")).catch(defaultOnFail), |
|
637
|
importAllFromDir(resolve(normalizedPath, "repositories")).catch( |
|
638
|
defaultOnFail |
|
639
|
), |
|
640
|
]) |
|
641
|
|
|
642
|
const cleanupResources = (resources) => { |
|
643
|
return Object.values(resources) |
|
644
|
.map((resource) => { |
|
645
|
if (DmlEntity.isDmlEntity(resource)) { |
|
646
|
return resource |
|
647
|
} |
|
648
|
|
|
649
|
if (typeof resource === "function") { |
|
650
|
return resource |
|
651
|
} |
|
652
|
|
|
653
|
return null |
|
654
|
}) |
|
655
|
.filter((v): v is Function => !!v) |
|
656
|
} |
|
657
|
|
|
658
|
const potentialServices = [...new Set(cleanupResources(services))] |
|
659
|
const potentialModels = [...new Set(cleanupResources(models))] |
|
660
|
const mikroOrmModels = toMikroOrmEntities(potentialModels) |
|
661
|
const potentialRepositories = [...new Set(cleanupResources(repositories))] |
|
662
|
|
|
663
|
const finalLoaders = prepareLoaders({ |
|
664
|
loadedModuleLoaders, |
|
665
|
models: mikroOrmModels, |
|
666
|
repositories: potentialRepositories, |
|
667
|
services: potentialServices, |
|
668
|
moduleResolution, |
|
669
|
migrationPath: normalizedPath + "/migrations", |
|
670
|
}) |
|
671
|
|
|
672
|
// if a module service is provided, we generate a joiner config |
|
673
|
if (moduleService) { |
|
674
|
generateJoinerConfigIfNecessary({ |
|
675
|
moduleResolution, |
|
676
|
service: moduleService, |
|
677
|
models: potentialModels, |
|
678
|
}) |
|
679
|
} |
|
680
|
|
|
681
|
return { |
|
682
|
services: potentialServices, |
|
683
|
models: mikroOrmModels, |
|
684
|
repositories: potentialRepositories, |
|
685
|
loaders: finalLoaders, |
|
686
|
moduleService, |
|
687
|
normalizedPath, |
|
688
|
} |
|
689
|
} catch (e) { |
|
690
|
logger.warn( |
|
691
|
`Unable to load resources for module ${modulePath} automagically. ${e.message}` |
|
692
|
) |
|
693
|
|
|
694
|
return {} as ModuleResource |
|
695
|
} |
|
696
|
} |
|
697
|
|
|
698
|
async function runLoaders( |
|
699
|
loaders: Function[] = [], |
|
700
|
{ |
|
701
|
localContainer, |
|
702
|
container, |
|
703
|
logger, |
|
704
|
resolution, |
|
705
|
loaderOnly, |
|
706
|
keyName, |
|
707
|
providerOptions, |
|
708
|
} |
|
709
|
): Promise<void | { error: Error }> { |
|
710
|
try { |
|
711
|
for (const loader of loaders) { |
|
712
|
await loader( |
|
713
|
{ |
|
714
|
container: localContainer, |
|
715
|
logger, |
|
716
|
options: providerOptions ?? resolution.options, |
|
717
|
dataLoaderOnly: loaderOnly, |
|
718
|
moduleOptions: providerOptions ? resolution.options : undefined, |
|
719
|
}, |
|
720
|
resolution.moduleDeclaration as InternalModuleDeclaration |
|
721
|
) |
|
722
|
} |
|
723
|
} catch (err) { |
|
724
|
container.register({ |
|
725
|
[keyName]: asValue(undefined), |
|
726
|
}) |
|
727
|
|
|
728
|
logger.error( |
|
729
|
`Loaders for module ${ |
|
730
|
resolution.definition.label |
|
731
|
} failed with the following error: \n${stringifyCircular(err)}` |
|
732
|
) |
|
733
|
|
|
734
|
return { |
|
735
|
error: new Error( |
|
736
|
`Loaders for module ${resolution.definition.label} failed: ${err.message}` |
|
737
|
), |
|
738
|
} |
|
739
|
} |
|
740
|
} |
|
741
|
|
|
742
|
function prepareLoaders({ |
|
743
|
loadedModuleLoaders = [] as |
|
744
|
| ModuleLoaderFunction[] |
|
745
|
| ModuleProviderLoaderFunction[], |
|
746
|
models, |
|
747
|
repositories, |
|
748
|
services, |
|
749
|
moduleResolution, |
|
750
|
migrationPath, |
|
751
|
}) { |
|
752
|
const finalLoaders: (ModuleLoaderFunction | ModuleProviderLoaderFunction)[] = |
|
753
|
[] |
|
754
|
|
|
755
|
const toObjectReducer = (acc, curr) => { |
|
756
|
acc[curr.name] = curr |
|
757
|
return acc |
|
758
|
} |
|
759
|
|
|
760
|
/* |
|
761
|
* If no connectionLoader function is provided, create a default connection loader. |
|
762
|
* TODO: Validate naming convention |
|
763
|
*/ |
|
764
|
const connectionLoaderName = "connectionLoader" |
|
765
|
const containerLoader = "containerLoader" |
|
766
|
|
|
767
|
const hasConnectionLoader = loadedModuleLoaders.some( |
|
768
|
(l) => l.name === connectionLoaderName |
|
769
|
) |
|
770
|
|
|
771
|
if (!hasConnectionLoader && models.length > 0) { |
|
772
|
const connectionLoader = ModulesSdkUtils.mikroOrmConnectionLoaderFactory({ |
|
773
|
moduleName: moduleResolution.definition.key, |
|
774
|
moduleModels: models, |
|
775
|
migrationsPath: migrationPath, |
|
776
|
}) |
|
777
|
finalLoaders.push(connectionLoader) |
|
778
|
} |
|
779
|
|
|
780
|
const hasContainerLoader = loadedModuleLoaders.some( |
|
781
|
(l) => l.name === containerLoader |
|
782
|
) |
|
783
|
|
|
784
|
if (!hasContainerLoader) { |
|
785
|
const containerLoader = ModulesSdkUtils.moduleContainerLoaderFactory({ |
|
786
|
moduleModels: models.reduce(toObjectReducer, {}), |
|
787
|
moduleRepositories: repositories.reduce(toObjectReducer, {}), |
|
788
|
moduleServices: services.reduce(toObjectReducer, {}), |
|
789
|
}) |
|
790
|
finalLoaders.push(containerLoader) |
|
791
|
} |
|
792
|
|
|
793
|
finalLoaders.push( |
|
794
|
...loadedModuleLoaders.filter((loader) => { |
|
795
|
if ( |
|
796
|
loader.name !== connectionLoaderName && |
|
797
|
loader.name !== containerLoader |
|
798
|
) { |
|
799
|
return true |
|
800
|
} |
|
801
|
|
|
802
|
return ( |
|
803
|
(loader.name === containerLoader && hasContainerLoader) || |
|
804
|
(loader.name === connectionLoaderName && hasConnectionLoader) |
|
805
|
) |
|
806
|
}) |
|
807
|
) |
|
808
|
|
|
809
|
return finalLoaders |
|
810
|
} |
|
811
|
|
|
812
|
function generateJoinerConfigIfNecessary({ |
|
813
|
moduleResolution, |
|
814
|
service, |
|
815
|
models, |
|
816
|
}: { |
|
817
|
moduleResolution: ModuleResolution |
|
818
|
service: Constructor<IModuleService> |
|
819
|
models: (Function | DmlEntity<any, any>)[] |
|
820
|
}) { |
|
821
|
const originalJoinerConfigFn = service.prototype.__joinerConfig |
|
822
|
|
|
823
|
service.prototype.__joinerConfig = function () { |
|
824
|
if (originalJoinerConfigFn) { |
|
825
|
return { |
|
826
|
serviceName: moduleResolution.definition.key, |
|
827
|
...originalJoinerConfigFn(), |
|
828
|
} |
|
829
|
} |
|
830
|
|
|
831
|
return defineJoinerConfig(moduleResolution.definition.key, { |
|
832
|
models, |
|
833
|
}) |
|
834
|
} |
|
835
|
} |