Here is my revised code from my other review question Node JS delete multiple MySQL linked records and delete physical file
Just would like to hear some reviews if I have the right logic.
router.delete('/:id', (req, res)=>{
function deleteCommentRecords(){
db.beginTransaction(function(err) {
if(err) return res.status(500).end(err.message);
//Delete comment section records
db.query("DELETE FROM commentSchema WHERE PostID = ?", req.params.id, (err, result)=>{
if(err){
db.rollback(()=>{
return res.status(500).end(err.message);
});
}
db.commit((err)=>{
if(err){
db.rollback(()=>{
return res.status(500).end(err.message);
});
}
console.log('Transaction Completed Successfully.');
});
});
});
}
function deletePostSchemaReords(){
// Delete PostSchema records
db.query("delete from postschema where id = ?", req.params.id, (err, result)=>{
if(err) {
db.rollback(()=>{
return res.status(500).end(err.message);
});
}
db.commit((err)=>{
if(err){
db.rollback(()=>{
return res.status(500).end(err.message);
});
}
console.log('Transaction Completed Successfully.');
});
});
}
function loadData(){
// Get filenames from Comments
db.query("SELECT image FROM commentschema WHERE postID = ?", req.params.id, (error, comments_image_output)=>{
if(error) return res.status(500).end(err.message);
// If there is an image
if(comments_image_output.length > 0){
// Foreach image, delete one by one
comments_image_output.forEach(function(row){
try {
console.log(row.image);
fs.unlinkSync(uploadDir + row.image);
console.log('Successfully deleted');
// Query to remove commentSchema records
deleteCommentRecords();
} catch (err) {
// handle the error
}
});
// Redirect back to posts
res.redirect(303, '/admin/posts');
}
deleteCommentRecords();
})
// Get filename from PostSchema
db.query("SELECT filename FROM PostSchema WHERE id = ?", req.params.id, (err,post_image_output)=>{
if(err) return res.status(500).end(err.message);
if(post_image_output.length > 0){
// Foreach image, delete one by one
post_image_output.forEach(function(row){
try {
console.log(row.filename);
fs.unlinkSync(uploadDir + row.filename);
console.log('Successfully deleted files');
deletePostSchemaReords();
} catch (err) {
// handle the error
}
});
}
deletePostSchemaReords();
});
}
loadData();
});