Skip to content

Commit

Permalink
fix: TypeError with hasOwnProperty in deepFindPathToProperty (#234)
Browse files Browse the repository at this point in the history
* chore: add failing test for response having null value

* Revert "fix: add `null` check in `deepFindPathToProperty` function (#137)"

This reverts commit cfda527.

* fix: hasOwnProperty error in deepFindPathToProperty
  • Loading branch information
kachick authored Oct 11, 2024
1 parent 3ce6b78 commit 7b17cc4
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 8 deletions.
18 changes: 10 additions & 8 deletions src/object-helpers.ts
Original file line number Diff line number Diff line change
@@ -1,33 +1,35 @@
import { MissingPageInfo } from "./errors.js";

const isObject = (value: any) =>
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: string[] | null = deepFindPathToProperty(
const paginatedResourcePath = deepFindPathToProperty(
responseData,
"pageInfo",
);
if (paginatedResourcePath === null || paginatedResourcePath.length === 0) {
if (paginatedResourcePath.length === 0) {
throw new MissingPageInfo(responseData);
}
return paginatedResourcePath;
}

const deepFindPathToProperty = (
object: any,
object: unknownObject,
searchProp: string,
path: string[] = [],
): string[] => {
for (const key of Object.keys(object)) {
const currentPath = [...path, key];
const currentValue = object[key];

if (currentValue.hasOwnProperty(searchProp)) {
return currentPath;
}

if (isObject(currentValue)) {
if (currentValue.hasOwnProperty(searchProp)) {
return currentPath;
}

const result = deepFindPathToProperty(
currentValue,
searchProp,
Expand Down
7 changes: 7 additions & 0 deletions test/extract-page-infos.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { MissingPageInfo } from "../src/errors.js";
import { extractPageInfos } from "../src/extract-page-info.js";
import type { PageInfoContext } from "../src/page-info.js";

Expand Down Expand Up @@ -63,4 +64,10 @@ describe("extractPageInfos()", (): void => {
pathInQuery: ["data", "repository", "issues"],
});
});

it("throws a MissingPageInfo error if the response has unexpected structure", async (): Promise<void> => {
expect(() => extractPageInfos({ unknown1: null, unknown2: 42 })).toThrow(
MissingPageInfo,
);
});
});

0 comments on commit 7b17cc4

Please # to comment.