Get All Books API #13

Merged
a258wang merged 10 commits from feat/api-all-books into main 2022-02-23 00:17:03 -05:00
2 changed files with 56 additions and 5 deletions

30
lib/books.ts Normal file
View File

@ -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<SimpleBook[]>((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;
}

View File

@ -1,8 +1,29 @@
import type { NextPage } from "next";
import React from "react";
const Home: NextPage = () => {
return <main>I am a book</main>;
};
import { getAllBooks, SimpleBook } from "../lib/books";
export default Home;
export default function Home(props: Props) {
return (
<ul>
{props.books.map((book, idx) => {
return (
<li key={`${idx}_${book.id}`}>
{book.id}; {book.title}; {book.authors}; {book.isbn}
</li>
);
})}
</ul>
);
}
interface Props {
books: SimpleBook[];
}
export async function getServerSideProps() {
return {
props: {
books: await getAllBooks(),
},
};
}