https://choidr.tistory.com/entry/NodeJs-%ED%8A%B8%EB%9E%9C%EC%9E%AD%EC%85%98Transaction-%EC%B2%98%EB%A6%AC
https://gofnrk.tistory.com/64
Mysql Transation 처리
npm mysql2 라이브러리를 통해 DB와 요청을 주고 받을 경우,
하나의 요청에서 여러개의 쿼리를 실행해야할 상황이라면 트랜젝션 처리가 중요하다.
예를 들어 한번의 요청에서 3개의 쿼리를 실행할 경우, 첫번째 쿼리 이후 서버 에러가 발생한다면 나머지 두개의 쿼리를 처리하지 못하는 문제가 발생한다.
트랜젝션 처리를 한다면, 오류가 발생할 땐 rollback 으로 실행 전 상태로 돌아가고, 정상적으로 처리된 경우 commit을 하여 변경된 데이터를 최종 반영할 수 있다.
var express = require('express')
var router = express.Router()
const pool = require('../database/pool')
router.post('/:boardId/comment', async (req, res, next) => {
const { boardId } = req.params
const { content } = req.body
const conn = await pool.getConnection()
try {
await conn.beginTransaction() // 트랜잭션 적용 시작
const ins = await conn.query('insert into board_comment set ?', { board_id: boardId, content: content })
const upd = await conn.query('update board set comment_cnt = comment_cnt + 1 where board_id = ?', [boardId])
await conn.commit() // 커밋
return res.json(ins)
} catch (err) {
console.log(err)
await conn.rollback() // 롤백
return res.status(500).json(err)
} finally {
conn.release() // conn 회수
})