From 2a308e1f3770f7867910d22a82b86ffc33cb3822 Mon Sep 17 00:00:00 2001 From: Amy Date: Wed, 23 Feb 2022 00:17:02 -0500 Subject: [PATCH] Get All Books API (#13) Closes #2 This PR implements the getAllBooks function that can be used to get summary information about all the books, in order to display them on the main page. I'm not sure why I waited so long to create this PR, but I suspect that we were blocked by #11 (which has now been merged). Co-authored-by: Amy Reviewed-on: https://git.csclub.uwaterloo.ca/www/library/pulls/13 Reviewed-by: j285he --- lib/books.ts | 30 ++++++++++++++++++++++++++++++ pages/index.tsx | 31 ++++++++++++++++++++++++++----- 2 files changed, 56 insertions(+), 5 deletions(-) create mode 100644 lib/books.ts diff --git a/lib/books.ts b/lib/books.ts new file mode 100644 index 0000000..0ba0964 --- /dev/null +++ b/lib/books.ts @@ -0,0 +1,30 @@ +import sqlite3 from "sqlite3"; + +const DATABASE_PATH = "catalogue.db"; + +export async function getAllBooks() { + const database = new sqlite3.Database(DATABASE_PATH, sqlite3.OPEN_READONLY); + + const books = new Promise((resolve, reject) => { + database.all( + "SELECT id, title, authors, isbn FROM books WHERE deleted = 0", + (error: Error | null, rows: SimpleBook[]) => { + if (error) { + reject(error); + } + resolve(rows); + } + ); + }); + + database.close(); + + return books; +} + +export interface SimpleBook { + id: number; + title: string | null; + authors: string | null; + isbn: string | null; +} diff --git a/pages/index.tsx b/pages/index.tsx index cf73651..46c3461 100644 --- a/pages/index.tsx +++ b/pages/index.tsx @@ -1,8 +1,29 @@ -import type { NextPage } from "next"; import React from "react"; -const Home: NextPage = () => { - return
I am a book
; -}; +import { getAllBooks, SimpleBook } from "../lib/books"; -export default Home; +export default function Home(props: Props) { + return ( +
    + {props.books.map((book, idx) => { + return ( +
  • + {book.id}; {book.title}; {book.authors}; {book.isbn} +
  • + ); + })} +
+ ); +} + +interface Props { + books: SimpleBook[]; +} + +export async function getServerSideProps() { + return { + props: { + books: await getAllBooks(), + }, + }; +}