Using WRAP ASYNC
AN ASYNC FUNCTION IS CREATED.WHICH WRAPS THE ASYNC CALLBACK.
function asyncWrap(fn) {
return function (req, res, next) {
fn(req, res, next).catch((err) => next(err));
};
}
WE WRAP EVERY TRY-CATCH TO ASYNC WRAP.
// INDEX ROUTE
app.get(
"/chats",
asyncWrap(async (req, res, next) => {
let chats = await Chat.find();
res.render("index.ejs", { chats });
})
);
// NEW ROUTE
app.get("/chats/new", (req, res) => {
res.render("new.ejs");
});
const ExpressError = require("./ExpressError.js");
// HANDLING ASYNC ERROR MESSAGES
app.use((err, req, res, next) => {
let { status = 500, message = " UNKNOWN ERROR OCCURRED" } = err;
res.status(status).send(message);
});
// SHOW ROUTE
app.get(
"/chats/:id",
asyncWrap(async (req, res, next) => {
let { id } = req.params;
let chat = await Chat.findById(id);
if (!chat) {
next(new ExpressError(404, "chat not found"));
}
res.render("edit.ejs", { chat });
})
);
// POST ROUTE
app.post(
"/chats",
asyncWrap(async (req, res, next) => {
let { from, to, msg } = req.body;
let newchat = new Chat({
from: from,
msg: msg,
to: to,
created_at: new Date(),
});
await newchat.save();
res.redirect("/chats");
})
);
// EDIT ROUTE
app.get(
"/chats/:id/edit",
asyncWrap(async (req, res, next) => {
let { id } = req.params;
let chat = await Chat.findById(id);
res.render("edit.ejs", { chat });
})
);
let chat1 = new Chat({
from: "abhi",
to: "ash",
msg: "silencer",
created_at: new Date(),
});
//UPDATE ROUTE
app.put(
"/chats/:id",
asyncWrap(async (req, res, next) => {
let { id } = req.params;
let { msg: newMsg } = req.body;
let updatedmsg = await Chat.findByIdAndUpdate(
id,
{ msg: newMsg },
{ new: true, runValidators: true }
);
console.log(updatedmsg);
res.redirect("/chats");
})
);
// DELETE ROUTE
app.delete(
"/chats/:id",
asyncWrap(async (req, res, next) => {
let { id } = req.params;
let deletedChat = await Chat.findByIdAndDelete(id);
console.log(deletedChat);
res.redirect("/chats");
})
);
Comments
Post a Comment