Refactor getAllBooks into promisified non-API function

This commit is contained in:
Amy 2021-11-27 22:54:46 -05:00
parent 79c759075f
commit 324ba1efde
2 changed files with 24 additions and 21 deletions

View File

@ -1,34 +1,25 @@
import { NextApiRequest, NextApiResponse } from "next";
import sqlite3 from "sqlite3"; import sqlite3 from "sqlite3";
const DATABASE_PATH = "catalogue.db"; const DATABASE_PATH = "catalogue.db";
export default function getAllBooks( export async function getAllBooks() {
request: NextApiRequest,
response: NextApiResponse
) {
if (request.method !== "GET") {
response.status(405);
return;
}
const database = new sqlite3.Database(DATABASE_PATH, sqlite3.OPEN_READONLY); const database = new sqlite3.Database(DATABASE_PATH, sqlite3.OPEN_READONLY);
try { const books = new Promise<SimpleBook[]>((resolve, reject) => {
database.all( database.all(
"SELECT title, authors, isbn FROM books", "SELECT title, authors, isbn FROM books",
(error: Error | null, rows: SimpleBook[]) => { (error: Error | null, rows: SimpleBook[]) => {
if (error) { if (error) {
throw error; reject(error);
} }
response.status(200).json(rows); resolve(rows);
} }
); );
} catch (error) { });
response.status(500);
}
database.close(); database.close();
return books;
} }
export interface SimpleBook { export interface SimpleBook {

View File

@ -1,8 +1,20 @@
import type { NextPage } from "next";
import React from "react"; import React from "react";
const Home: NextPage = () => { import { getAllBooks, SimpleBook } from "../lib/books";
return <main>I am a book</main>;
};
export default Home; export default function Home(props: Props) {
console.log(props.books);
return <main>I am a book</main>;
}
interface Props {
books: SimpleBook[];
}
export async function getServerSideProps() {
return {
props: {
books: await getAllBooks(),
},
};
}