diff --git a/src/object-helpers.ts b/src/object-helpers.ts index c57b467..813c454 100644 --- a/src/object-helpers.ts +++ b/src/object-helpers.ts @@ -1,21 +1,23 @@ import { MissingPageInfo } from "./errors.js"; -const isObject = (value: any) => +type unknownObject = Record; + +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[] => { @@ -23,11 +25,11 @@ const deepFindPathToProperty = ( 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, diff --git a/test/extract-page-infos.test.ts b/test/extract-page-infos.test.ts index 2963a09..45c83b4 100644 --- a/test/extract-page-infos.test.ts +++ b/test/extract-page-infos.test.ts @@ -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"; @@ -63,4 +64,10 @@ describe("extractPageInfos()", (): void => { pathInQuery: ["data", "repository", "issues"], }); }); + + it("throws a MissingPageInfo error if the response has unexpected structure", async (): Promise => { + expect(() => extractPageInfos({ unknown1: null, unknown2: 42 })).toThrow( + MissingPageInfo, + ); + }); });