From 58a6dad2f5205515cb456905eedef2782b6d62f4 Mon Sep 17 00:00:00 2001 From: John Mwendwa <72663882+JohnMwendwa@users.noreply.github.com> Date: Mon, 5 Jun 2023 11:45:50 +0300 Subject: [PATCH] Update book query method and type checking --- src/pages/api/books/update.ts | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/src/pages/api/books/update.ts b/src/pages/api/books/update.ts index b31af36..488d2fa 100644 --- a/src/pages/api/books/update.ts +++ b/src/pages/api/books/update.ts @@ -1,5 +1,6 @@ import { getServerSession } from "next-auth/next"; import { NextApiRequest, NextApiResponse } from "next"; +import { Types } from "mongoose"; import connectDB from "lib/db/connection"; import Book from "lib/db/models/book_model"; @@ -27,6 +28,13 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => { return; } + // Chec if it is a valid id + if (!Types.ObjectId.isValid(id)) { + return res.status(404).json({ + error: "Book Not Found!", + }); + } + await connectDB(); // Find and delete book @@ -51,10 +59,17 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => { return; } + // Chec if it is a valid id + if (!Types.ObjectId.isValid(id)) { + return res.status(404).json({ + error: "Book Not Found!", + }); + } + await connectDB(); // Update book finish date - const book = await Book.findOne({ id }); + const book = await Book.findById(id); book.end = new Date(); await book.save();