57 lines
1.4 KiB
JavaScript
57 lines
1.4 KiB
JavaScript
import EleventyFetch from "@11ty/eleventy-fetch";
|
|
|
|
const { POSTGREST_URL, POSTGREST_API_KEY } = process.env;
|
|
|
|
const fetchAllBooks = async () => {
|
|
try {
|
|
return await EleventyFetch(
|
|
`${POSTGREST_URL}/optimized_books?order=date_finished.desc`,
|
|
{
|
|
duration: "1h",
|
|
type: "json",
|
|
fetchOptions: {
|
|
method: "GET",
|
|
headers: {
|
|
"Content-Type": "application/json",
|
|
Authorization: `Bearer ${POSTGREST_API_KEY}`,
|
|
},
|
|
},
|
|
},
|
|
);
|
|
} catch (error) {
|
|
console.error("Error fetching books:", error);
|
|
return [];
|
|
}
|
|
};
|
|
|
|
const sortBooksByYear = (books) => {
|
|
const years = {};
|
|
books.forEach((book) => {
|
|
const year = book.year;
|
|
if (!years[year]) {
|
|
years[year] = { value: year, data: [book] };
|
|
} else {
|
|
years[year].data.push(book);
|
|
}
|
|
});
|
|
return Object.values(years).filter((year) => year.value);
|
|
};
|
|
|
|
const currentYear = new Date().getFullYear();
|
|
|
|
export default async function () {
|
|
const books = await fetchAllBooks();
|
|
const sortedByYear = sortBooksByYear(books);
|
|
const booksForCurrentYear =
|
|
sortedByYear
|
|
.find((yearGroup) => yearGroup.value === currentYear)
|
|
?.data.filter((book) => book.status === "finished") || [];
|
|
|
|
return {
|
|
all: books,
|
|
years: sortedByYear,
|
|
currentYear: booksForCurrentYear,
|
|
feed: books.filter((book) => book.feed),
|
|
daysRead: books[0]?.days_read
|
|
};
|
|
}
|