|
1
|
import { Logger } from "@medusajs/types" |
|
2
|
import { dynamicImport, promiseAll, readDirRecursive } from "@medusajs/utils" |
|
3
|
import { Dirent } from "fs" |
|
4
|
import { access } from "fs/promises" |
|
5
|
import { join } from "path" |
|
6
|
import { logger as defaultLogger } from "../logger" |
|
7
|
|
|
8
|
export class SearchIndexLoader { |
|
9
|
/** |
|
10
|
* The directory from which to load the search index definitions |
|
11
|
* @private |
|
12
|
*/ |
|
13
|
#sourceDir: string | string[] |
|
14
|
|
|
15
|
/** |
|
16
|
* The list of file names to exclude from the search index scan |
|
17
|
* @private |
|
18
|
*/ |
|
19
|
#excludes: RegExp[] = [ |
|
20
|
// Anchored, unlike the link loader's: `product-index.ts` is a natural name |
|
21
|
// for a file in `search/` and must not be skipped as a barrel file. |
|
22
|
/^index\.(js|ts)$/, |
|
23
|
/\.DS_Store/, |
|
24
|
/(\.ts\.map|\.js\.map|\.d\.ts|\.md)$/, |
|
25
|
/^_[^/\\]*(\.[^/\\]+)?$/, |
|
26
|
] |
|
27
|
|
|
28
|
#logger: Logger |
|
29
|
|
|
30
|
constructor(sourceDir: string | string[], logger?: Logger) { |
|
31
|
this.#sourceDir = sourceDir |
|
32
|
this.#logger = logger ?? defaultLogger |
|
33
|
} |
|
34
|
|
|
35
|
/** |
|
36
|
* Load the search index definitions from the source paths. `defineSearchIndex` |
|
37
|
* registers them, so importing the files is all there is to do. What was |
|
38
|
* registered reaches the Search Module as its `indexes` option when the app |
|
39
|
* boots, which is why this has to run before `MedusaApp`. |
|
40
|
*/ |
|
41
|
async load() { |
|
42
|
const normalizedSourcePath = Array.isArray(this.#sourceDir) |
|
43
|
? this.#sourceDir |
|
44
|
: [this.#sourceDir] |
|
45
|
|
|
46
|
const promises = normalizedSourcePath.map(async (sourcePath) => { |
|
47
|
try { |
|
48
|
await access(sourcePath) |
|
49
|
} catch { |
|
50
|
this.#logger.debug( |
|
51
|
`No search index to load from ${sourcePath}. skipped.` |
|
52
|
) |
|
53
|
return |
|
54
|
} |
|
55
|
|
|
56
|
return await readDirRecursive(sourcePath).then(async (entries) => { |
|
57
|
const fileEntries = entries.filter((entry: Dirent) => { |
|
58
|
return ( |
|
59
|
!entry.isDirectory() && |
|
60
|
!this.#excludes.some((exclude) => exclude.test(entry.name)) |
|
61
|
) |
|
62
|
}) |
|
63
|
|
|
64
|
this.#logger.debug(`Registering search indexes from ${sourcePath}.`) |
|
65
|
|
|
66
|
return await promiseAll( |
|
67
|
fileEntries.map(async (entry: Dirent) => { |
|
68
|
const fullPath = join(entry.path, entry.name) |
|
69
|
return await dynamicImport(fullPath) |
|
70
|
}) |
|
71
|
) |
|
72
|
}) |
|
73
|
}) |
|
74
|
|
|
75
|
await promiseAll(promises) |
|
76
|
|
|
77
|
this.#logger.debug(`Search indexes registered.`) |
|
78
|
} |
|
79
|
} |