|
1 | 1 | import type { ApiParams } from "@/types"; |
2 | 2 | import humps from "humps"; |
3 | 3 |
|
4 | | -const { decamelize, decamelizeKeys } = humps; |
| 4 | +const { decamelize } = humps; |
5 | 5 |
|
6 | 6 | export const removeBeginningSlash = (url: string) => { |
7 | 7 | return url.startsWith("/") ? url.slice(1) : url; |
8 | 8 | }; |
9 | 9 |
|
10 | | -const fieldsKey = ["wordFields", "translationFields", "fields"]; |
| 10 | +const fieldsKey = ["wordFields", "translationFields", "fields"] as const; |
| 11 | +const fieldsKeySet = new Set<string>([ |
| 12 | + ...fieldsKey, |
| 13 | + ...fieldsKey.map((key) => decamelize(key)), |
| 14 | +]); |
| 15 | +const preservedKeys = new Set(["navigationalResultsNumber", "versesResultsNumber"]); |
11 | 16 |
|
12 | 17 | export const paramsToString = (params?: ApiParams): string => { |
13 | 18 | if (!params) return ""; |
14 | 19 |
|
15 | | - const paramsWithDecamelizedKeys = decamelizeKeys(params) as ApiParams; |
16 | 20 | const paramsString = new URLSearchParams(); |
17 | 21 |
|
18 | | - for (const [key, value] of Object.entries(paramsWithDecamelizedKeys)) { |
19 | | - if (value === undefined) continue; |
20 | | - |
21 | | - if (typeof value === "string") { |
22 | | - paramsString.set(key, value); |
23 | | - } else if (typeof value === "number") { |
24 | | - paramsString.set(key, value.toString()); |
25 | | - } else if (typeof value === "boolean") { |
26 | | - paramsString.set(key, value.toString()); |
27 | | - } else if (Array.isArray(value)) { |
28 | | - paramsString.set(key, value.join(",")); |
29 | | - } |
| 22 | + for (const [rawKey, rawValue] of Object.entries(params)) { |
| 23 | + if (rawValue === undefined) continue; |
| 24 | + |
| 25 | + const key = preservedKeys.has(rawKey) ? rawKey : decamelize(rawKey); |
30 | 26 |
|
31 | 27 | // fields is a special case, it's an object with boolean values |
32 | | - if (fieldsKey.includes(key)) { |
33 | | - const fields = Object.entries(value) |
| 28 | + if (fieldsKeySet.has(rawKey) || fieldsKeySet.has(key)) { |
| 29 | + const fields = Object.entries(rawValue as Record<string, boolean>) |
34 | 30 | .filter(([, value]) => value) |
35 | | - .map(([key]) => decamelize(key)); |
| 31 | + .map(([fieldKey]) => decamelize(fieldKey)); |
36 | 32 | if (fields.length > 0) { |
37 | 33 | paramsString.set(key, fields.join(",")); |
38 | 34 | } |
| 35 | + continue; |
| 36 | + } |
| 37 | + |
| 38 | + if (typeof rawValue === "string") { |
| 39 | + paramsString.set(key, rawValue); |
| 40 | + } else if (typeof rawValue === "number") { |
| 41 | + paramsString.set(key, rawValue.toString()); |
| 42 | + } else if (typeof rawValue === "boolean") { |
| 43 | + paramsString.set(key, rawValue.toString()); |
| 44 | + } else if (Array.isArray(rawValue)) { |
| 45 | + paramsString.set(key, rawValue.join(",")); |
39 | 46 | } |
40 | 47 | } |
41 | 48 |
|
|
0 commit comments