배달 서비스를 구현하며, 주문 생성과 취소 시에 잔액이 옮겨지는 작업을 구현해야 했다.
user 주문 시, totalPrice가 Admin 계정으로 이동
=> 배달 완료 시 Admin 계정의 wallet이 Owner 계정으로 이동
=> 주문 취소 시 Admin 계정의 wallet이 User 계정으로 이동
이었다.
고민해본 결과 transaction 사용하여 진행했다.
검증 완료(인증 및 주문데이터)
=> transaction 사용 > 주문 생성 > user 잔액 차감 > admin 잔액 증가 > 반환이었다.
prisma에서 증가와 차감하는 메서드가 있어서 해당 메서드를 사용하였다
// 고객의 잔액 차감
await tx.user.update({
where: { id: userId },
data: { wallet: { decrement: createdOrder.totalPrice } }, //고객의 잔액을 totalPrice만큼 증가
});
// admin 잔액 증가
const adminId = 1;
await tx.user.update({
where: { id: adminId },
data: { wallet: { increment: createdOrder.totalPrice } },
});
이렇게 작성하여 해결하였다