-
Notifications
You must be signed in to change notification settings - Fork 22
/
object-helpers.ts
73 lines (61 loc) · 1.93 KB
/
object-helpers.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import { MissingPageInfo } from "./errors.js";
type unknownObject = Record<string | number | symbol, unknown>;
const isObject = (value: unknown): value is unknownObject =>
Object.prototype.toString.call(value) === "[object Object]";
function findPaginatedResourcePath(responseData: any): string[] {
const paginatedResourcePath = deepFindPathToProperty(
responseData,
"pageInfo",
);
if (paginatedResourcePath.length === 0) {
throw new MissingPageInfo(responseData);
}
return paginatedResourcePath;
}
const deepFindPathToProperty = (
object: unknownObject,
searchProp: string,
path: string[] = [],
): string[] => {
for (const key of Object.keys(object)) {
const currentPath = [...path, key];
const currentValue = object[key];
if (isObject(currentValue)) {
if (currentValue.hasOwnProperty(searchProp)) {
return currentPath;
}
const result = deepFindPathToProperty(
currentValue,
searchProp,
currentPath,
);
if (result.length > 0) {
return result;
}
}
}
return [];
};
/**
* The interfaces of the "get" and "set" functions are equal to those of lodash:
* https://lodash.com/docs/4.17.15#get
* https://lodash.com/docs/4.17.15#set
*
* They are cut down to our purposes, but could be replaced by the lodash calls
* if we ever want to have that dependency.
*/
const get = (object: any, path: string[]) => {
return path.reduce((current, nextProperty) => current[nextProperty], object);
};
type Mutator = any | ((value: unknown) => any);
const set = (object: any, path: string[], mutator: Mutator) => {
const lastProperty = path[path.length - 1];
const parentPath = [...path].slice(0, -1);
const parent = get(object, parentPath);
if (typeof mutator === "function") {
parent[lastProperty!] = mutator(parent[lastProperty!]);
} else {
parent[lastProperty!] = mutator;
}
};
export { findPaginatedResourcePath, get, set };