From 79c759075fbd20f6892a434118387b95359b2af8 Mon Sep 17 00:00:00 2001 From: Amy Date: Mon, 15 Nov 2021 23:46:25 -0500 Subject: [PATCH] Add basic error checking --- pages/api/books.ts | 26 +++++++++++++++++++------- 1 file changed, 19 insertions(+), 7 deletions(-) diff --git a/pages/api/books.ts b/pages/api/books.ts index 0fb1562..1a127f9 100644 --- a/pages/api/books.ts +++ b/pages/api/books.ts @@ -3,18 +3,30 @@ import sqlite3 from "sqlite3"; const DATABASE_PATH = "catalogue.db"; -export default async function getAllBooks( +export default function getAllBooks( request: NextApiRequest, response: NextApiResponse ) { + if (request.method !== "GET") { + response.status(405); + return; + } + const database = new sqlite3.Database(DATABASE_PATH, sqlite3.OPEN_READONLY); - database.all( - "SELECT title, authors, isbn FROM books", - (error, rows: SimpleBook[]) => { - response.status(200).json(rows); - } - ); + try { + database.all( + "SELECT title, authors, isbn FROM books", + (error: Error | null, rows: SimpleBook[]) => { + if (error) { + throw error; + } + response.status(200).json(rows); + } + ); + } catch (error) { + response.status(500); + } database.close(); }