From 25640e435a0f536e70cbb2b3cdd24e919df5fd2b Mon Sep 17 00:00:00 2001 From: Alexander Sullivan Date: Mon, 9 Sep 2024 21:40:02 -0400 Subject: [PATCH] [fix] Handle empty PMID array (#220) Bug fix to address handling an empty PMID array. --- src/index.ts | 2 +- src/processor/fetchArticleDetails.test.ts | 12 ++++++++++++ src/processor/fetchArticleDetails.ts | 6 ++++++ 3 files changed, 19 insertions(+), 1 deletion(-) diff --git a/src/index.ts b/src/index.ts index cb032c7..49c66ad 100644 --- a/src/index.ts +++ b/src/index.ts @@ -29,7 +29,7 @@ async function main() { /** Array of PubMed Central IDs (PMCIDs) for the articles found. */ const pmids = await searchArticlesBySpecies(throttle, species); - if (pmids.length > 0) { + if (pmids?.length > 0) { await fetchArticleDetails(throttle, pmids, species); } else { console.log(`No articles found for the species: ${species}.`); diff --git a/src/processor/fetchArticleDetails.test.ts b/src/processor/fetchArticleDetails.test.ts index f5c61e6..3dee164 100644 --- a/src/processor/fetchArticleDetails.test.ts +++ b/src/processor/fetchArticleDetails.test.ts @@ -75,4 +75,16 @@ describe("fetchArticleDetails", () => { expect(axios.get).toHaveBeenCalledTimes(1); // Should not call axios.get again }); + + it("should handle empty PMID array gracefully", async () => { + const emptyPmids: string[] = []; + const consoleLogSpy = jest.spyOn(console, "log").mockImplementation(() => {}); + + await fetchArticleDetails(throttle, emptyPmids, species); + + expect(axios.get).not.toHaveBeenCalled(); + expect(consoleLogSpy).toHaveBeenCalledWith("No PMC IDs provided for Homo sapiens."); + + consoleLogSpy.mockRestore(); + }); }); diff --git a/src/processor/fetchArticleDetails.ts b/src/processor/fetchArticleDetails.ts index 7992120..f897a9a 100644 --- a/src/processor/fetchArticleDetails.ts +++ b/src/processor/fetchArticleDetails.ts @@ -43,6 +43,12 @@ export async function fetchArticleDetails( fs.mkdirSync(path.dirname(cachedIDsFilePath), { recursive: true }); } + // Check if PMIDs array is undefined/null or empty + if (!pmids || pmids.length === 0) { + console.log(`No PMC IDs provided for ${species.replace("_", " ")}.`); + return; + } + // Get article details based on PMC IDs for (let i = 0; i < pmids.length; i += batchSize) { // Extract a batch of 50 PMC IDs