diff --git a/src/api/openLibrary.test.ts b/src/api/openLibrary.test.ts index 74cba71..1a6643e 100644 --- a/src/api/openLibrary.test.ts +++ b/src/api/openLibrary.test.ts @@ -56,6 +56,30 @@ describe("searchBooksBySubject", () => { }); }); + it("treats a publication year of 0 as missing", async () => { + const responseWithInvalidYear = { + docs: [ + { + key: "/works/OL3", + title: "Unknown Publication Year", + first_publish_year: 0, + }, + ], + }; + + vi.stubGlobal( + "fetch", + vi.fn().mockResolvedValue({ + ok: true, + json: async () => responseWithInvalidYear, + }), + ); + + const books = await searchBooksBySubject("history"); + + expect(books[0].firstPublishYear).toBeNull(); + }); + it("requests the configured limit and only the needed fields", async () => { const fetchMock = vi.fn().mockResolvedValue({ ok: true, json: async () => ({ docs: [] }) }); vi.stubGlobal("fetch", fetchMock); diff --git a/src/api/openLibrary.ts b/src/api/openLibrary.ts index 707ba1c..8eee597 100644 --- a/src/api/openLibrary.ts +++ b/src/api/openLibrary.ts @@ -30,7 +30,7 @@ function toBook(doc: OpenLibrarySearchDoc): Book { key: doc.key, title: doc.title, authors: doc.author_name ?? [], - firstPublishYear: doc.first_publish_year ?? null, + firstPublishYear: yearOrNull(doc.first_publish_year), averageRating: numberOrNull(doc.ratings_average), ratingsCount: numberOrNull(doc.ratings_count), coverId: doc.cover_i ?? null, @@ -38,6 +38,10 @@ function toBook(doc: OpenLibrarySearchDoc): Book { }; } +function yearOrNull(value: number | undefined): number | null { + return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : null; +} + function numberOrNull(value: number | undefined): number | null { return typeof value === "number" && Number.isFinite(value) ? value : null; }