I have the following tables in MySQL:
create table PostSchema
(id int not null primary key auto_increment,
categories int not null,
title varchar(50),
status varchar(20),
comments bool,
body varchar(255),
filename varchar(255),
date_created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP);
create table commentSchema (
id int not null primary key auto_increment,
userID int,
message varchar(255),
image varchar(255),
date_created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
postID int);
Currently..
When a post is created it saves an image in the '/uploads'
directory. Path name is referenced in table PostSchema
column name filename
.
Next, when a comment is created with an image attached it is also saved in '/uploads'
directory and the actual path name is referenced in commentSchema
in column image
.
My Idea
I have a router set up to delete
the records from PostSchema
and any comments
are relevant to PostSchema
. On top of that, I'll implement a unlink
function to remove any images referenced in the both tables that are held in the /uploads
directory.
I have a working code, just want to hear some reviews if there is anywhere I can improve :)
Current working code:
router.delete('/:id', (req, response)=>{
// Execute query for deleting the post
// Get filename from database
db.query("SELECT filename FROM PostSchema WHERE id = ?", req.params.id,(err,fileResult)=>{
// If error
if(err){
return res.status(500).end(err.message);
}
// If not an error continue...
else{
try {
// Unlink comments images
db.query("select image from commentschema where postID = ?", req.params.id, (cErr, cRes)=>{
if(cErr){
return res.status(500).end(err.message);
}
else{
if(fs.existsSync(uploadDir + cRes[0].image)){
fs.unlink(uploadDir + cRes[0].image, (commentFile) => {
if (commentFile) throw err;
});
}
}
});
// Unlink PostSchema images
fs.unlink(uploadDir + fileResult[0].filename, (errs)=>{
// Delete PostSchema + Delete comments
db.query("delete t1, t2 from postschema t1 join commentschema t2 on t1.id = t2.postid where t1.id = ?;", req.params.id,(errors, results)=>{
if(errors){
console.log(errors);
}
else{
db.query("delete from postschema where id = ?", req.params.id, (er, res)=>{
if(errors){
console.log(errors);
}
else{
// Redirect to all posts page
req.flash('success_message', 'Post was succesfully deleted');
response.redirect(303, '/admin/posts');
}
});
}
});
});
}
catch (e) {
return res.status(500).end(e.message);
}
}
});
});