From b0b774a0765ea2dc1f455b03f874531689ef8acc Mon Sep 17 00:00:00 2001 From: yg-i <148152939+yg-i@users.noreply.github.com> Date: Tue, 28 Nov 2023 04:51:36 -0500 Subject: [PATCH 1/2] protect against the scenario when langlinks is undefined For some pages, the langlinks property is undefined, and the current implementation throws an error. An example: ``` import wiki from 'wikipedia' const pageObj = await wiki.page('TheBrain') const langLinks = await pageObj.langLinks() ``` throws the error: ``` linksError: linksError: TypeError: Cannot read properties of undefined (reading 'map') at Page.langLinks (...node_modules\wikipedia\dist\page.js:234:23) ``` This PR is so that langLinks() returns an empty array rather than throws an error --- source/page.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/source/page.ts b/source/page.ts index 0ff254c..788b748 100644 --- a/source/page.ts +++ b/source/page.ts @@ -665,7 +665,7 @@ export const langLinks = async (title: string, listOptions?: listOptions): Promi languageOptions = setPageIdOrTitleParam(languageOptions, title); const response = await request(languageOptions, listOptions?.redirect); const pageId = setPageId(languageOptions, response); - const result = response.query.pages[pageId].langlinks.map((link: any) => { + const result = (response.query.pages[pageId].langlinks ?? []).map((link: any) => { return { lang: link.lang, title: link['*'], @@ -881,4 +881,4 @@ export const citation = async (query: string, format?: citationFormat, language? } } -export default Page; \ No newline at end of file +export default Page; From c65a4fce06382295324ff13c6563e6e31654d6e2 Mon Sep 17 00:00:00 2001 From: Govind S Date: Sat, 13 Jan 2024 18:35:35 +0530 Subject: [PATCH 2/2] Add test for handling if langlinks is not present --- test/langlinks.test.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/test/langlinks.test.ts b/test/langlinks.test.ts index 1753de5..961ddfb 100644 --- a/test/langlinks.test.ts +++ b/test/langlinks.test.ts @@ -58,6 +58,12 @@ test('Returns empty if no lang links are available', async () => { expect(result).toStrictEqual([]); }); +test('Returns empty if lang links object itself is not available', async () => { + requestMock.mockImplementation(async () => { return { query: { pages: {404: {}} } } }); + const result = await langLinks("Test"); + expect(result).toStrictEqual([]); +}); + test('Returns with results an array of langLinksResult object', async () => { requestMock.mockImplementation(async () => { return { query: { pages: langLinkskMock } } }); const result = await langLinks("Test");