Wecode - Project 3 (부트캠프)/Project 3 독학

post update, delete **

JBS 12 2023. 10. 10. 14:34

delete 

app.delete("/deletepost" , async (req, res) => {
try{
 
const token = req.headers.authorization;
if(!token){
const error = new Error ("TOKEN_ERROR 게시물 삭제 권한이 없습니다");
error.statusCode = 400;
error.code = "TOKEN_ERROR"
throw error;
}
const {id} = jwt.verify(token, process.env.TYPEORM_JWT);
 
const postId = req.params
 
const existingUser = await myDataSource.query(`                                                                                                                       
SELECT id, email, password FROM users WHERE email='${email}';`);
console.log("existing user:", existingUser);

if (existingUser.length === 0) {
const error = new Error("삭제할 권한이 없습니다");
error.statusCode = 400;
throw error;
}
//3. 게시물 삭제
const {content} = req.body //회색으로 뜨는 건, 변수 사용이 안 돼서, 아래에서 쓰이지 않아서 -> console.log만 찍어도 흰색 됨
console.log(content)

// user id, post id, createddate select from DB
const deletePost = await myDataSource.query(`
DELETE FROM threads where users.id=${id} and post.id= ${postId}`)
//threads 중에 어떤 user의 어떤 포스트 (이것만 하면 되니, 칼럼이름 표시 안 해도 됨)
console.log(deletePost) //deltePost 변수 사용해주기 위해 (회색표시 -> 흰색)
return res.status(200).json({message:"DELETE POST 게시물 삭제"})
} catch(error){
console.log(error);
return res.status(400).json({message:"FAILED"});
// return res.status(400).json(error); -> 메세지 매번 던지기 힘드니, error라는 공용함수 사용 시
};
})

 

<토큰 검증>

const {id}의 id는 token에 담겨 있는 id 

const postId = req.params 추가 

 

/products/7 의 

7이 params 


<쿼리문> 

DELETE FROM threads WHERE post.id = ${postId}

-> threads에서 post id가 같은 것을 골라내서 삭제

DELETE
threads.id, 
threads.user.id
threads.created_at
FROM threads 
(threads 테이블에서 id, user.id, create_at 칼럼을 가져와서 삭제 한다) 
--> 필요 없는 이유가 post id 는 하나니까, 그거 하나를 골라서 delete 하면 되니까