librarian-web/src/lib/api.ts

100 lines
2.4 KiB
TypeScript

import { DetailedBook } from "./book";
import { Book } from "@/models/book";
export async function getBooks() {
let bookRes = [];
try {
const res = await (
await fetch(`${process.env.NEXT_PUBLIC_API_URL}/books`)
).json();
if (!res.success) {
throw new Error("Failed to fetch/json parse books");
}
bookRes = res.result;
} catch (err) {
console.error("Failed to fetch books: " + err);
return null;
}
const books: DetailedBook[] = [];
for (const book of bookRes) {
// Create a new DetailedBook object and push it to the books array. Use object.assign to copy the properties of the book object to the new DetailedBook object only if the properties are defined
try {
const newBook = new DetailedBook(
Object.assign(
book,
{
id: book.id,
title: book.title,
category: book.category?.length > 0 ? book.category : [],
subtitle: book.subtitle || "",
authors: book.authors || "",
isbn: book.isbn || "",
},
{
last_updated: book.last_updated
? new Date(book.last_updated)
: undefined,
}
)
);
books.push(newBook);
} catch (err) {
console.error(`Failed to create entry for ${book?.title}: ${err}`);
continue;
}
}
return books;
}
export async function getBookDetail(id: string) {
let bookRes: Book;
try {
const res = await (
await fetch(`${process.env.NEXT_PUBLIC_API_URL}/books/${id}`)
).json();
if (!res.success) {
throw new Error("Failed to fetch/json parse book detail");
}
bookRes = res.result;
} catch (err) {
console.error("Failed to fetch book details: " + err);
return null;
}
// Convert nulls to undefined for not required fields
const entries: [string, unknown][] = [];
Object.entries(bookRes).forEach(([key, value]) => {
if (value === null) {
entries.push([key, undefined]);
}
});
try {
const newBook = new DetailedBook(
Object.assign(
Object.fromEntries(entries),
{
id: bookRes.id,
title: bookRes.title,
category: bookRes.category?.length > 0 ? bookRes.category : [],
subtitle: bookRes.subtitle || "",
authors: bookRes.authors || "",
isbn: bookRes.isbn || "",
},
{
last_updated: bookRes.last_updated
? new Date(bookRes.last_updated)
: undefined,
}
)
);
return newBook;
} catch (err) {
console.error(`Failed to get details for ${bookRes?.title}: ${err}`);
return null;
}
}