From bafd27750555258d25952dc60d77a6f85ef75b91 Mon Sep 17 00:00:00 2001 From: felixtanhm Date: Wed, 17 Apr 2024 16:06:51 +0800 Subject: [PATCH] book delete --- .../controllers/bookController.js | 32 +++++++++++++++- .../views/book_delete.ejs | 37 +++++++++++++++++++ 2 files changed, 67 insertions(+), 2 deletions(-) create mode 100644 full-stack-javascript/20-forms-and-deployment/views/book_delete.ejs diff --git a/full-stack-javascript/20-forms-and-deployment/controllers/bookController.js b/full-stack-javascript/20-forms-and-deployment/controllers/bookController.js index 1e993d0..627d6db 100644 --- a/full-stack-javascript/20-forms-and-deployment/controllers/bookController.js +++ b/full-stack-javascript/20-forms-and-deployment/controllers/bookController.js @@ -173,7 +173,20 @@ exports.book_create_post = [ // Display book delete form on GET. exports.book_delete_get = async function (req, res, next) { try { - res.send("NOT IMPLEMENTED: Book delete GET"); + const [book, allBookCopies] = await Promise.all([ + Book.findById(req.params.id).populate("author").exec(), + BookInstance.find({ book: req.params.id }).exec(), + ]); + + if (book === null) { + res.redirect("/catalog/books"); + } + + res.render("book_delete", { + title: "Delete Book", + book, + book_copies: allBookCopies, + }); } catch (error) { return next(error); } @@ -182,7 +195,22 @@ exports.book_delete_get = async function (req, res, next) { // Handle book delete on POST. exports.book_delete_post = async function (req, res, next) { try { - res.send("NOT IMPLEMENTED: Book delete POST"); + const [book, allBookCopies] = await Promise.all([ + Book.findById(req.params.id).exec(), + BookInstance.find({ book: req.params.id }).exec(), + ]); + + if (allBookCopies.length > 0) { + res.render("book_delete", { + title: "Delete Book", + book, + book_copies: allBookCopies, + }); + return; + } else { + await Book.findByIdAndDelete(req.body.bookid); + res.redirect("/catalog/books"); + } } catch (error) { return next(error); } diff --git a/full-stack-javascript/20-forms-and-deployment/views/book_delete.ejs b/full-stack-javascript/20-forms-and-deployment/views/book_delete.ejs new file mode 100644 index 0000000..ad09450 --- /dev/null +++ b/full-stack-javascript/20-forms-and-deployment/views/book_delete.ejs @@ -0,0 +1,37 @@ + + + <%- include('./partials/header') %> + + <%- include('./partials/nav.ejs') %> +
+
+

Book: <%= book.title %>

+

<%= book.author.name %>

+

<%= book.summary %>

+
+ <% if (book_copies.length) { %> +

+ Delete the following book copies before attempting to delete this + book. +

+

Book Copies

+ <% book_copies.forEach(copy => { %> + <%= copy.id %> +

Imprint: <%= copy.imprint %>

+ <% }) %> <% } else { %> +

Do you really want to delete this Book?

+
+ + +
+ <% } %> +
+ <%- include('./partials/footer') %> +
+ +