-
Notifications
You must be signed in to change notification settings - Fork 74
/
Copy pathsanitizeResource.ts
47 lines (42 loc) · 1.11 KB
/
sanitizeResource.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
export const sanitizeResource = (data: any = {}) => {
const result: any = Object.keys(data).reduce((acc, key) => {
if (key.startsWith('_')) {
return acc;
}
const dataKey = data[key];
if (dataKey === null || dataKey === undefined) {
return acc;
}
if (Array.isArray(dataKey)) {
if (dataKey[0] && typeof dataKey[0] === 'object') {
// if var is an array of reference objects with id properties
if (dataKey[0].id != null) {
return {
...acc,
[key]: dataKey.map(sanitizeResource),
[`${key}Ids`]: dataKey.map((d) => d.id),
};
} else {
return {
...acc,
[key]: dataKey.map(sanitizeResource),
};
}
} else {
return { ...acc, [key]: dataKey };
}
}
if (typeof dataKey === 'object') {
return {
...acc,
...(dataKey &&
dataKey.id && {
[`${key}.id`]: dataKey.id,
}),
[key]: sanitizeResource(dataKey),
};
}
return { ...acc, [key]: dataKey };
}, {});
return result;
};