parent
79c759075f
commit
324ba1efde
@ -1,34 +1,25 @@ |
||||
import { NextApiRequest, NextApiResponse } from "next"; |
||||
import sqlite3 from "sqlite3"; |
||||
|
||||
const DATABASE_PATH = "catalogue.db"; |
||||
|
||||
export default function getAllBooks( |
||||
request: NextApiRequest, |
||||
response: NextApiResponse |
||||
) { |
||||
if (request.method !== "GET") { |
||||
response.status(405); |
||||
return; |
||||
} |
||||
|
||||
export async function getAllBooks() { |
||||
const database = new sqlite3.Database(DATABASE_PATH, sqlite3.OPEN_READONLY); |
||||
|
||||
try { |
||||
const books = new Promise<SimpleBook[]>((resolve, reject) => { |
||||
database.all( |
||||
"SELECT title, authors, isbn FROM books", |
||||
(error: Error | null, rows: SimpleBook[]) => { |
||||
if (error) { |
||||
throw error; |
||||
reject(error); |
||||
} |
||||
response.status(200).json(rows); |
||||
resolve(rows); |
||||
} |
||||
); |
||||
} catch (error) { |
||||
response.status(500); |
||||
} |
||||
}); |
||||
|
||||
database.close(); |
||||
|
||||
return books; |
||||
} |
||||
|
||||
export interface SimpleBook { |
@ -1,8 +1,20 @@ |
||||
import type { NextPage } from "next"; |
||||
import React from "react"; |
||||
|
||||
const Home: NextPage = () => { |
||||
import { getAllBooks, SimpleBook } from "../lib/books"; |
||||
|
||||
export default function Home(props: Props) { |
||||
console.log(props.books); |
||||
return <main>I am a book</main>; |
||||
}; |
||||
} |
||||
|
||||
interface Props { |
||||
books: SimpleBook[]; |
||||
} |
||||
|
||||
export default Home; |
||||
export async function getServerSideProps() { |
||||
return { |
||||
props: { |
||||
books: await getAllBooks(), |
||||
}, |
||||
}; |
||||
} |
||||
|
Loading…
Reference in new issue