const indexController = require('../controller/indexController')
exports.indexRouter = (app) => {
// 일정 CRUD API
app.post('/todo', indexController.createTodo) // create
app.get('/user/:userIdx/todos', indexController.readTodo) // read 특정 유저의 일정
app.patch('/todo', indexController.updateTodo) // update
app.delete('/user/:userIdx/todo/:todoIdx', indexController.deleteTodo) // delete 특정 유저의 특정 투두 삭제
}
update에는 put과 patch가 있지만
put은 전체를 수정하는 것으므로 patch로 진행한다.
app.patch로 CRUD 중 업데이트를, app.delete로 CRUD 중 딜리트를 한다.
컨트롤러 파일로 들어가서
let { userIdx, todoIdx, contents, status } = req.body
if (!userIdx || !todoIdx) {
return res.send({
isSuccess: false,
code: 400,
message: 'userIdx와 todoIdx 모두 보내주세요.',
})
}
if (!contents) contents = null
if (!status) status = null
updateTodo 함수에서 우리가 필요한
userIdx, todoIdx, contents, status를 req.body에서 받아온다.
해당 데이터들이 안 왔을 경우 작동할 방어코드 작성.
userIdx나 todoIdx는 둘다 와야되고 contents나 status는 꼭 받아도 되니까 안 왔을 경우 null로 설정
그리고 db에 바로 업데이트를 하기 전에
지금 받아온 데이터들이 유효한지 확인하는 작업을 만들어 준다.
const isValidTodo = await indexDatabase.selectValidTodo(userIdx, todoIdx)
if (isValidTodo.length < 1) {
return res.send({
isSuccess: false,
code: 400,
message: '유효한 요청이 아닙니다. userIdx와 todoIdx를 확인하세요.',
})
}
이렇게 isValidTodo로 디비에 유효성 검사를 해준다.
indexDatabase 파일에서는 이렇게
exports.selectValidTodo = async (userIdx, todoIdx) => {
// DB 연결 검사
try {
const connection = await pool.getConnection(async (conn) => conn)
try {
const selectValidTodoQuery = "select * from Todos where userIdx = ? and todoIdx = ? and not(status ='D');"
const selectValidTodoParams = [userIdx, todoIdx]
const [row] = await connection.query(selectValidTodoQuery, selectValidTodoParams)
return row
} catch (err) {
console.log(error(` ##### selectValidTodo DB error ##### \n ${err}`))
return false
} finally {
// db 과부화 되지 않게 연결 다시 끊어주기
connection.release()
}
} catch (err) {
console.log(error(` ##### selectValidTodo DB error ##### \n ${err}`))
return false
}
}
select문으로 해당 userIdx와 todoIdx가 status D가 아닌 것들
즉, 삭제되지 않은 투두들을 모두 불러와 주는 쿼리를 작성한다.
그 다음 다시 컨트롤러 파일로 돌아와서
유효한 userIdx와 todoIdx 일 경우 todo를 update 해주는 함수를 만든다.
const updateTodo = await indexDatabase.updateTodo(userIdx, todoIdx, contents, status)
if (!updateTodo) {
return res.send({
isSuccess: false,
code: 400,
message: '수정 실패. 관리자에게 문의해주세요.',
})
}
return res.send({
isSuccess: true,
code: 200,
message: '일정 수정 완료',
})
역시나 updateTodo가 유효하지 않을 경우 방어하는 코드를 작성해 주고,
제대로 왔을 경우 수정 완료 메세지를 보내준다.
현재 userIdx가 1이고 todoIdx가 3인 데이터는 '오늘 수영 가기' 고 status는 A이다.
완료 했다는 의미에서 C (complete)로 바꾼다고 치면
우선 쿼리를 날려보면 성공적으로 수정이 완료된다.
디비를 확인해보면
status가 C로 제대로 바뀌어 있는 것을 확인할 수 있다.
이제 DELETE 차례 업데이트 보단 훨씬 간단하다.
exports.deleteTodo = async (req, res) => {
const { userIdx, todoIdx } = req.params
if (!userIdx || !todoIdx) {
return res.send({
isSuccess: false,
code: 400,
message: 'userIdx와 todoIdx 모두 보내주세요.',
})
}
const isValidTodo = await indexDatabase.selectValidTodo(userIdx, todoIdx)
if (isValidTodo.length < 1) {
return res.send({
isSuccess: false,
code: 400,
message: '유효한 요청이 아닙니다. userIdx와 todoIdx를 확인하세요.',
})
}
const deleteTodo = await indexDatabase.deleteTodo(userIdx, todoIdx)
if (!deleteTodo) {
return res.send({
isSuccess: false,
code: 400,
message: '삭제 실패. 관리자에게 문의해주세요.',
})
}
return res.send({
isSuccess: true,
code: 200,
message: '일정 삭제 완료',
})
}
delete는 라우터에서 이렇게 url에 user/:userIdx/todo/:todoIdx로 설정해 놨기 때문에
req.body가 아닌 params에서 userIdx와 todoIdx를 받아온다.
userIdx와 todoIdx가 안 왔을 경우 똑같이 방어코드를 작성하고
역시 업데이트처럼 유효성 검사를 해주는 isValidTodo를 실행한다.
indexDatabase 파일에 selectValidTodo를 그대로 사용하면 되고
유효할 경우 deleteTodo를 진행한다.
우리는 실제로 디비를 삭제하는 것이 아니라 status를 A, C, D로 나눠서
각각 활성화된 일정, 완료된 일정, 삭제된 일정으로 관리한다.
try {
const deleteTodoQuery = 'update Todos set status = "D" where userIdx = ? and todoIdx = ?;'
const deleteTodoParams = [userIdx, todoIdx]
const [row] = await connection.query(deleteTodoQuery, deleteTodoParams)
return row
}
indexDatabase 파일에서는 많이 달라질 것 없이
status를 D로 바꿔주는 쿼리만 날려준다.
디비에서 todoIdx 4번에 과자 먹기 status A인 데이터를 삭제 해보자
일정 삭제 완료라고 제대로 나온다.
디비에서 확인해 보면
이렇게 status D 로 잘 바뀌어 있는 것을 확인할 수 있다!!
이렇게 일정 CRUD 코드를 모두 완료 했다...!!!!!! ㅜㅜㅜㅜㅜㅜㅜㅜ드디어
'Project' 카테고리의 다른 글
[아이젠하워 매트릭스] 바닐라JS 배포 시 만났던 에러 (1) | 2023.08.17 |
---|---|
[아이젠하워 매트릭스] CRUD, Read (0) | 2023.07.05 |
[아이젠하워 매트릭스] DB설계, ERD, CRUD, create (0) | 2023.07.03 |
🪴Plant Planet Project (WEB3.0 커뮤니티 만들기 / 정리 / 회고) (0) | 2022.12.16 |
NFT 마켓플레이스 제작 (정신차려보니 프로젝트 마지막 날이었던 건에 대하여) (0) | 2022.05.30 |