|
1
|
import { SearchTypes } from "@medusajs/types" |
|
2
|
import { |
|
3
|
getCallerFilePath, |
|
4
|
isFileDisabled, |
|
5
|
MEDUSA_SKIP_FILE, |
|
6
|
} from "../common" |
|
7
|
|
|
8
|
/** |
|
9
|
* Declares a search index. Like `defineLink`, the file registers itself on |
|
10
|
* import: the application loads every file under `search/` and hands what was |
|
11
|
* registered to the Search Module as its `indexes` option, so the module has one |
|
12
|
* input rather than a registry and an option that can disagree. |
|
13
|
* |
|
14
|
* `fields` must be a schema from `search.define({ ... })`. The documents |
|
15
|
* `seed` yields are type-checked against the declared fields. |
|
16
|
*/ |
|
17
|
export function defineSearchIndex< |
|
18
|
Fields extends SearchTypes.SearchIndexFieldsInput |
|
19
|
>( |
|
20
|
definition: SearchTypes.SearchIndexDefinitionInput<Fields> |
|
21
|
): SearchTypes.SearchIndexDefinition { |
|
22
|
const callerFilePath = getCallerFilePath() |
|
23
|
|
|
24
|
if (isFileDisabled(callerFilePath ?? "")) { |
|
25
|
return { [MEDUSA_SKIP_FILE]: true } as any |
|
26
|
} |
|
27
|
|
|
28
|
const normalized: SearchTypes.SearchIndexDefinition = { |
|
29
|
...definition, |
|
30
|
fields: normalizeFields(definition.fields), |
|
31
|
} |
|
32
|
|
|
33
|
global.MedusaModule.setSearchIndex(normalized, callerFilePath ?? undefined) |
|
34
|
|
|
35
|
return normalized |
|
36
|
} |
|
37
|
|
|
38
|
/** |
|
39
|
* Compiles a `search.define(...)` schema into plain SearchFieldDefinition |
|
40
|
* records. Normalization happens here, at the declaration boundary, so the |
|
41
|
* Search Module only ever sees plain definitions and nothing user-facing |
|
42
|
* calls `toFields()`. |
|
43
|
* |
|
44
|
* The input type advertises `toFields()` structurally, so normalization |
|
45
|
* duck-types on it rather than checking for our own class — a schema built by |
|
46
|
* a duplicated copy of @medusajs/utils, or any object honoring the contract, |
|
47
|
* still normalizes. |
|
48
|
*/ |
|
49
|
function normalizeFields( |
|
50
|
fields: SearchTypes.SearchIndexFieldsInput |
|
51
|
): Record<string, SearchTypes.SearchFieldDefinition> { |
|
52
|
if (typeof fields?.toFields !== "function") { |
|
53
|
throw new Error( |
|
54
|
"`defineSearchIndex` fields must come from `search.define({ ... })`" |
|
55
|
) |
|
56
|
} |
|
57
|
|
|
58
|
return fields.toFields() |
|
59
|
} |