|
1
|
import { FindConfig } from "@medusajs/framework/types" |
|
2
|
import { |
|
3
|
ProductsQueryContextKey, |
|
4
|
ProductStatus, |
|
5
|
PublishedProductsContextKey, |
|
6
|
} from "@medusajs/framework/utils" |
|
7
|
|
|
8
|
const PRODUCTS_RELATION = "products" |
|
9
|
|
|
10
|
export const extractPublishedProductsContext = < |
|
11
|
TFilters extends Record<string, any> | undefined |
|
12
|
>( |
|
13
|
filters: TFilters |
|
14
|
): { filters: TFilters; publishedOnly: boolean } => { |
|
15
|
const context = filters?.context |
|
16
|
|
|
17
|
if (!context) { |
|
18
|
return { filters, publishedOnly: false } |
|
19
|
} |
|
20
|
|
|
21
|
const { context: _context, ...rest } = filters as Record<string, any> |
|
22
|
|
|
23
|
return { |
|
24
|
filters: rest as TFilters, |
|
25
|
publishedOnly: |
|
26
|
!!context[ProductsQueryContextKey]?.[PublishedProductsContextKey], |
|
27
|
} |
|
28
|
} |
|
29
|
|
|
30
|
export const applyPublishedProductsPopulateWhere = < |
|
31
|
TConfig extends FindConfig<any> | undefined |
|
32
|
>( |
|
33
|
config: TConfig, |
|
34
|
publishedOnly: boolean |
|
35
|
): TConfig => { |
|
36
|
if (!publishedOnly) { |
|
37
|
return config |
|
38
|
} |
|
39
|
|
|
40
|
const productPaths = (config?.relations ?? []).filter( |
|
41
|
(relation) => |
|
42
|
relation === PRODUCTS_RELATION || |
|
43
|
relation.split(".").includes(PRODUCTS_RELATION) |
|
44
|
) |
|
45
|
|
|
46
|
if (!productPaths.length) { |
|
47
|
return config |
|
48
|
} |
|
49
|
|
|
50
|
const populateWhere: Record<string, any> = { |
|
51
|
...((config as any)?.options?.populateWhere ?? {}), |
|
52
|
} |
|
53
|
|
|
54
|
for (const productPath of productPaths) { |
|
55
|
// Only constrain up to the products segment; anything deeper hangs off a |
|
56
|
// product that is already constrained. |
|
57
|
const segments = productPath.split(".") |
|
58
|
const productsAt = segments.indexOf(PRODUCTS_RELATION) |
|
59
|
|
|
60
|
let node = populateWhere |
|
61
|
for (const segment of segments.slice(0, productsAt)) { |
|
62
|
node[segment] ??= {} |
|
63
|
node = node[segment] |
|
64
|
} |
|
65
|
|
|
66
|
node[PRODUCTS_RELATION] = { |
|
67
|
...(node[PRODUCTS_RELATION] ?? {}), |
|
68
|
status: ProductStatus.PUBLISHED, |
|
69
|
} |
|
70
|
} |
|
71
|
|
|
72
|
return { |
|
73
|
...config, |
|
74
|
options: { |
|
75
|
...(config as any)?.options, |
|
76
|
populateWhere, |
|
77
|
}, |
|
78
|
} as TConfig |
|
79
|
} |
|
80
|
|
|
81
|
export const applyPublishedProductsContext = < |
|
82
|
TFilters extends Record<string, any> | undefined, |
|
83
|
TConfig extends FindConfig<any> | undefined |
|
84
|
>( |
|
85
|
filters: TFilters, |
|
86
|
config: TConfig |
|
87
|
): { filters: TFilters; config: TConfig } => { |
|
88
|
const { filters: cleanedFilters, publishedOnly } = |
|
89
|
extractPublishedProductsContext(filters) |
|
90
|
|
|
91
|
return { |
|
92
|
filters: cleanedFilters, |
|
93
|
config: applyPublishedProductsPopulateWhere(config, publishedOnly), |
|
94
|
} |
|
95
|
} |