|
1
|
// Those utils are used in a typeorm context and we can't be sure that they can be used elsewhere |
|
2
|
|
|
3
|
import { objectFromStringPath } from "./object-from-string-path" |
|
4
|
|
|
5
|
export type Order = { |
|
6
|
[key: string]: "ASC" | "DESC" | Order |
|
7
|
} |
|
8
|
|
|
9
|
type Selects = { |
|
10
|
[key: string]: boolean | Selects |
|
11
|
} |
|
12
|
|
|
13
|
type Relations = { |
|
14
|
[key: string]: boolean | Relations |
|
15
|
} |
|
16
|
|
|
17
|
export function buildSelects(selectCollection: string[]): Selects { |
|
18
|
return buildRelationsOrSelect(selectCollection) |
|
19
|
} |
|
20
|
|
|
21
|
export function buildRelations(relationCollection: string[]): Relations { |
|
22
|
return buildRelationsOrSelect(relationCollection) |
|
23
|
} |
|
24
|
|
|
25
|
function buildRelationsOrSelect(collection: string[]): Selects | Relations { |
|
26
|
return objectFromStringPath(collection) |
|
27
|
} |
|
28
|
|
|
29
|
const UNSAFE_ORDER_KEYS = new Set(["__proto__", "constructor", "prototype"]) |
|
30
|
|
|
31
|
/** |
|
32
|
* Convert an order of dot string into a nested object |
|
33
|
* @example |
|
34
|
* input: { id: "ASC", "items.title": "ASC", "items.variant.title": "ASC" } |
|
35
|
* output: { |
|
36
|
* "id": "ASC", |
|
37
|
* "items": { |
|
38
|
* "id": "ASC", |
|
39
|
* "variant": { |
|
40
|
* "title": "ASC" |
|
41
|
* } |
|
42
|
* }, |
|
43
|
* } |
|
44
|
* @param orderBy |
|
45
|
*/ |
|
46
|
export function buildOrder(orderBy: { [k: string]: "ASC" | "DESC" }): Order { |
|
47
|
const output: Order = {} |
|
48
|
|
|
49
|
const orderKeys = Object.keys(orderBy) |
|
50
|
|
|
51
|
for (const order of orderKeys) { |
|
52
|
const nestedOrder = order.split(".") |
|
53
|
|
|
54
|
// Guard against prototype pollution through user-controlled order keys |
|
55
|
if (nestedOrder.some((segment) => UNSAFE_ORDER_KEYS.has(segment))) { |
|
56
|
continue |
|
57
|
} |
|
58
|
|
|
59
|
if (nestedOrder.length > 1) { |
|
60
|
let parent = output |
|
61
|
|
|
62
|
while (nestedOrder.length > 1) { |
|
63
|
const nestedRelation = nestedOrder.shift() as string |
|
64
|
if (!Object.prototype.hasOwnProperty.call(parent, nestedRelation)) { |
|
65
|
parent[nestedRelation] = {} |
|
66
|
} |
|
67
|
parent = parent[nestedRelation] as Order |
|
68
|
} |
|
69
|
|
|
70
|
parent[nestedOrder[0]] = orderBy[order] |
|
71
|
|
|
72
|
continue |
|
73
|
} |
|
74
|
|
|
75
|
output[order] = orderBy[order] |
|
76
|
} |
|
77
|
|
|
78
|
return output |
|
79
|
} |