Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions src/api/openLibrary.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
6 changes: 5 additions & 1 deletion src/api/openLibrary.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,14 +30,18 @@ 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,
subjects: doc.subject ?? [],
};
}

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;
}