1 import { SearchTypes } from "@medusajs/framework/types"
2 import { MedusaError } from "@medusajs/framework/utils"
3 import { jsonbPath } from "./filters"
4 import { IndexPlan, isFacetable } from "./plan"
5
6 function fail(message: string): never {
7 throw new MedusaError(MedusaError.Types.NOT_ALLOWED, message)
8 }
9
10 export type NormalizedFacetRequest = {
11 field: string
12 type: "value" | "range" | "stats"
13 limit?: number
14 sort?: "count" | "alpha"
15 query?: string
16 ranges?: {
17 key: string
18 from?: number
19 to?: number
20 }[]
21 }
22
23 export function normalizeFacetRequests(
24 requests: (string | SearchTypes.SearchFacetRequest)[] | undefined,
25 plan: IndexPlan
26 ): NormalizedFacetRequest[] {
27 if (!requests?.length) {
28 return []
29 }
30
31 return requests.map((request) => {
32 if (typeof request === "string") {
33 const planned = plan.fields.get(request)
34 if (!planned || !isFacetable(planned.field)) {
35 fail(`Field "${request}" is not facetable on the postgres search provider`)
36 }
37 return { field: request, type: "value" as const }
38 }
39
40 const planned = plan.fields.get(request.field)
41 if (!planned || !isFacetable(planned.field)) {
42 fail(
43 `Field "${request.field}" is not facetable on the postgres search provider`
44 )
45 }
46
47 if (request.type === "stats") {
48 if (planned.kind !== "number") {
49 fail(`Stats facets require a numeric field ("${request.field}")`)
50 }
51 return { field: request.field, type: "stats" }
52 }
53
54 if (request.type === "range") {
55 if (planned.kind !== "number") {
56 fail(`Range facets require a numeric field ("${request.field}")`)
57 }
58 return {
59 field: request.field,
60 type: "range",
61 ranges: request.ranges.map((range) => ({
62 key: range.key ?? `${range.from ?? "*"}-${range.to ?? "*"}`,
63 from:
64 range.from === undefined
65 ? undefined
66 : typeof range.from === "number"
67 ? range.from
68 : Number(range.from),
69 to:
70 range.to === undefined
71 ? undefined
72 : typeof range.to === "number"
73 ? range.to
74 : Number(range.to),
75 })),
76 }
77 }
78
79 return {
80 field: request.field,
81 type: "value",
82 limit: request.limit,
83 sort: request.sort,
84 query: request.query,
85 }
86 })
87 }
88
89 /**
90 * Builds a SELECT that returns facet rows for a single request, scoped by the
91 * same WHERE clause as the main search (passed in as a pre-built fragment).
92 */
93 export function buildFacetQuery(input: {
94 table: string
95 whereSql?: string
96 whereParams: unknown[]
97 request: NormalizedFacetRequest
98 plan: IndexPlan
99 }): { sql: string; params: unknown[] } {
100 const { table, whereSql, whereParams, request, plan } = input
101 const planned = plan.fields.get(request.field)!
102 const params = [...whereParams]
103 const where = whereSql ? `WHERE ${whereSql}` : ""
104
105 if (request.type === "stats") {
106 const expr = `(${jsonbPath(request.field, true)})::float8`
107 return {
108 sql: `
109 SELECT
110 MIN(${expr}) AS min,
111 MAX(${expr}) AS max,
112 AVG(${expr}) AS avg,
113 SUM(${expr}) AS sum,
114 COUNT(*)::int AS count
115 FROM "${table}"
116 ${where}
117 `,
118 params,
119 }
120 }
121
122 if (request.type === "range") {
123 const expr = `(${jsonbPath(request.field, true)})::float8`
124 // The range bounds sit in the SELECT list, ahead of the WHERE clause, so
125 // their params must precede whereParams.
126 const rangeParams: unknown[] = []
127 const selects = (request.ranges ?? [])
128 .map((range, index) => {
129 const conditions: string[] = []
130 if (range.from !== undefined) {
131 rangeParams.push(range.from)
132 conditions.push(`${expr} >= ?`)
133 }
134 if (range.to !== undefined) {
135 rangeParams.push(range.to)
136 conditions.push(`${expr} < ?`)
137 }
138 const predicate = conditions.length
139 ? conditions.join(" AND ")
140 : "TRUE"
141 return `COUNT(*) FILTER (WHERE ${predicate})::int AS r${index}`
142 })
143 .join(",\n")
144
145 return {
146 sql: `SELECT ${selects} FROM "${table}" ${where}`,
147 params: [...rangeParams, ...whereParams],
148 }
149 }
150
151 // value facet
152 const valueExpr = planned.is_array
153 ? `jsonb_array_elements_text(${jsonbPath(request.field)})`
154 : jsonbPath(request.field, true)
155
156 const limit = request.limit ?? 10
157 params.push(limit)
158
159 let valueFilter = ""
160 if (request.query) {
161 params.splice(params.length - 1, 0, `${request.query}%`)
162 valueFilter = planned.is_array
163 ? `AND value LIKE ?`
164 : `AND ${valueExpr} LIKE ?`
165 }
166
167 const order =
168 request.sort === "alpha" ? "value ASC" : "count DESC, value ASC"
169
170 if (planned.is_array) {
171 return {
172 sql: `
173 SELECT value, COUNT(*)::int AS count
174 FROM (
175 SELECT ${valueExpr} AS value
176 FROM "${table}"
177 ${where}
178 ) AS exploded
179 WHERE value IS NOT NULL
180 ${valueFilter}
181 GROUP BY value
182 ORDER BY ${order}
183 LIMIT ?
184 `,
185 params,
186 }
187 }
188
189 const nullGuard = `${valueExpr} IS NOT NULL`
190 const facetWhere = whereSql
191 ? `WHERE ${whereSql} AND ${nullGuard}`
192 : `WHERE ${nullGuard}`
193
194 return {
195 sql: `
196 SELECT ${valueExpr} AS value, COUNT(*)::int AS count
197 FROM "${table}"
198 ${facetWhere}
199 ${valueFilter}
200 GROUP BY 1
201 ORDER BY ${order}
202 LIMIT ?
203 `,
204 params,
205 }
206 }
207
208 export function mapFacetResult(
209 request: NormalizedFacetRequest,
210 rows: Record<string, unknown>[]
211 ): SearchTypes.SearchFacetResult {
212 if (request.type === "stats") {
213 const row = rows[0] ?? {}
214 return {
215 type: "stats",
216 min: Number(row.min ?? 0),
217 max: Number(row.max ?? 0),
218 avg: row.avg === null || row.avg === undefined ? undefined : Number(row.avg),
219 sum: row.sum === null || row.sum === undefined ? undefined : Number(row.sum),
220 count: Number(row.count ?? 0),
221 }
222 }
223
224 if (request.type === "range") {
225 const row = rows[0] ?? {}
226 return {
227 type: "range",
228 ranges: (request.ranges ?? []).map((range, index) => ({
229 key: range.key,
230 from: range.from,
231 to: range.to,
232 count: Number(row[`r${index}`] ?? 0),
233 })),
234 }
235 }
236
237 return {
238 type: "value",
239 values: rows.map((row) => ({
240 value: String(row.value),
241 count: Number(row.count ?? 0),
242 })),
243 }
244 }