51 lines
1.4 KiB
JavaScript
51 lines
1.4 KiB
JavaScript
import { MissingPageInfo } from "./errors.js";
|
|
const isObject = (value) => Object.prototype.toString.call(value) === "[object Object]";
|
|
function findPaginatedResourcePath(responseData) {
|
|
const paginatedResourcePath = deepFindPathToProperty(
|
|
responseData,
|
|
"pageInfo"
|
|
);
|
|
if (paginatedResourcePath.length === 0) {
|
|
throw new MissingPageInfo(responseData);
|
|
}
|
|
return paginatedResourcePath;
|
|
}
|
|
const deepFindPathToProperty = (object, searchProp, path = []) => {
|
|
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 [];
|
|
};
|
|
const get = (object, path) => {
|
|
return path.reduce((current, nextProperty) => current[nextProperty], object);
|
|
};
|
|
const set = (object, path, 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
|
|
};
|