Skip to content

Commit

Permalink
update book
Browse files Browse the repository at this point in the history
  • Loading branch information
felixtanhm committed Apr 16, 2024
1 parent 3dd9d86 commit c9e268d
Showing 1 changed file with 106 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -191,17 +191,115 @@ exports.book_delete_post = async function (req, res, next) {
// Display book update form on GET.
exports.book_update_get = async function (req, res, next) {
try {
res.send("NOT IMPLEMENTED: Book update GET");
// Get book, authors and genres for form.
const [book, allAuthors, allGenres] = await Promise.all([
Book.findById(req.params.id).populate("author").exec(),
Author.find().sort({ family_name: 1 }).exec(),
Genre.find().sort({ name: 1 }).exec(),
]);

if (book === null) {
// No results.
const err = new Error("Book not found");
err.status = 404;
return next(err);
}

// Mark our selected genres as checked.
allGenres.forEach((genre) => {
if (book.genre.includes(genre._id)) genre.checked = "true";
});

res.render("book_form", {
title: "Update Book",
authors: allAuthors,
genres: allGenres,
book: book,
errors: null,
});
} catch (error) {
return next(error);
}
};

// Handle book update on POST.
exports.book_update_post = async function (req, res, next) {
try {
res.send("NOT IMPLEMENTED: Book update POST");
} catch (error) {
return next(error);
}
};
exports.book_update_post = [
// Convert the genre to an array.
(req, res, next) => {
if (!Array.isArray(req.body.genre)) {
req.body.genre =
typeof req.body.genre === "undefined" ? [] : [req.body.genre];
}
next();
},

// Validate and sanitize fields.
body("title", "Title must not be empty.")
.trim()
.isLength({ min: 1 })
.escape(),
body("author", "Author must not be empty.")
.trim()
.isLength({ min: 1 })
.escape(),
body("summary", "Summary must not be empty.")
.trim()
.isLength({ min: 1 })
.escape(),
body("isbn", "ISBN must not be empty").trim().isLength({ min: 1 }).escape(),
body("genre.*").escape(),

// Process request after validation and sanitization.
async function (req, res, next) {
try {
// Extract the validation errors from a request.
const errors = validationResult(req);

// Create a Book object with escaped/trimmed data and old id.;
const book = new Book({
title: req.body.title,
author: req.body.author,
summary: req.body.summary,
isbn: req.body.isbn,
genre: typeof req.body.genre === "undefined" ? [] : req.body.genre,
_id: req.params.id, // This is required, or a new ID will be assigned!
});

if (!errors.isEmpty()) {
// There are errors. Render form again with sanitized values/error messages.

// Get all authors and genres for form
const [allAuthors, allGenres] = await Promise.all([
Author.find().sort({ family_name: 1 }).exec(),
Genre.find().sort({ name: 1 }).exec(),
]);

// Mark our selected genres as checked.
for (const genre of allGenres) {
if (book.genre.indexOf(genre._id) > -1) {
genre.checked = "true";
}
}
res.render("book_form", {
title: "Update Book",
authors: allAuthors,
genres: allGenres,
book: book,
errors: errors.array(),
});
return;
} else {
// Data from form is valid. Update the record.
const updatedBook = await Book.findByIdAndUpdate(
req.params.id,
book,
{}
);
// Redirect to book detail page.
res.redirect(updatedBook.url);
}
} catch (error) {
return next(error);
}
},
];

0 comments on commit c9e268d

Please sign in to comment.