1 import { Logger, MedusaContainer } from "@medusajs/types"
2 import {
3 ContainerRegistrationKeys,
4 dynamicImport,
5 promiseAll,
6 readDirRecursive,
7 } from "@medusajs/utils"
8 import { Dirent } from "fs"
9 import { access } from "fs/promises"
10 import { join, parse } from "path"
11
12 export abstract class ResourceLoader {
13 /**
14 * The name of the resource (e.g job, subscriber, workflow)
15 */
16 protected abstract resourceName: string
17
18 /**
19 * The directory from which to load the jobs
20 * @private
21 */
22 #sourceDir: string | string[]
23
24 /**
25 * The list of file name patterns to exclude from resource scanning.
26 * Excludes: files starting with _, test files (.spec.ts, .test.ts)
27 * @private
28 */
29 #excludes: RegExp[] = [
30 /^_[^/\\]*(\.[^/\\]+)?$/,
31 /\.spec\.[jt]s$/,
32 /\.test\.[jt]s$/,
33 ]
34
35 protected logger: Logger
36
37 constructor(sourceDir: string | string[], container: MedusaContainer) {
38 this.#sourceDir = sourceDir
39 this.logger = container.resolve(ContainerRegistrationKeys.LOGGER)
40 }
41
42 /**
43 * Discover resources from the source directory
44 * @param exclude - custom exclusion regexes
45 * @param customFiltering - custom filtering function
46 * @param allowIndex - when true, files named `index` are not filtered out
47 * @returns The resources discovered
48 */
49 protected async discoverResources({
50 exclude,
51 customFiltering,
52 allowIndex,
53 }: {
54 exclude?: RegExp[]
55 customFiltering?: (entry: Dirent) => boolean
56 allowIndex?: boolean
57 } = {}): Promise<Record<string, unknown>[]> {
58 exclude ??= []
59 customFiltering ??= (entry: Dirent) => {
60 const parsedName = parse(entry.name)
61
62 return (
63 !entry.isDirectory() &&
64 (allowIndex || parsedName.name !== "index") &&
65 !parsedName.base.endsWith(".d.ts") &&
66 !entry.path.includes("__tests__") &&
67 [".js", ".ts"].includes(parsedName.ext) &&
68 !this.#excludes.some((exclude) => exclude.test(parsedName.base)) &&
69 !exclude.some((exclude) => exclude.test(parsedName.base))
70 )
71 }
72
73 const normalizedSourcePath = Array.isArray(this.#sourceDir)
74 ? this.#sourceDir
75 : [this.#sourceDir]
76
77 const promises = normalizedSourcePath.map(async (sourcePath) => {
78 try {
79 await access(sourcePath)
80 } catch {
81 this.logger.info(
82 `No ${this.resourceName} to load from ${sourcePath}. skipped.`
83 )
84 return
85 }
86
87 return await readDirRecursive(sourcePath).then(async (entries) => {
88 const fileEntries = entries.filter((entry: Dirent) =>
89 customFiltering(entry)
90 )
91
92 return await promiseAll(
93 fileEntries.map(async (entry: Dirent) => {
94 const fullPath = join(entry.path, entry.name)
95
96 const module_ = await dynamicImport(fullPath)
97
98 await this.onFileLoaded(fullPath, module_)
99 return module_
100 })
101 )
102 })
103 })
104
105 const resources = await promiseAll(promises)
106 return resources.flat().filter(Boolean)
107 }
108
109 /**
110 * Called when a file is imported
111 * @param path - The path of the file
112 * @param fileExports - The exports of the file
113 */
114 protected abstract onFileLoaded(
115 path: string,
116 fileExports: Record<string, unknown>
117 ): Promise<void> | never
118 }