router.patch("/users", authMiddleware, async (req, res, next) => {
const { userId } = req.user;
const updatedData = req.body;
const userInfo = await prisma.userInfos.findFirst({
where: { UserId: +userId },
});
await prisma.$transaction(
async (tx) => {
await tx.userInfos.update({
data: {
...updatedData,
},
where: { UserId: +userId },
});
for (let key in updatedData) {
if (userInfo[key] !== updatedData[key]) {
await tx.userHistories.create({
data: {
UserId: +userId,
changeField: key,
oldValue: String(userInfo[key]),
newValue: String(updatedData[key]),
},
});
}
}
},
{
isolationLevel: Prisma.TransactionIsolationLevel.ReadCommitted,
}
);
return res.status(201).json({ message: "사용자 정보 변경 됐습니다." });
});
router.post("/sign-up", async (req, res, next) => {
try {
// throw new Error("에러처리 미들웨어 테스트 용");
const { email, password, name, age, gender, profileImage } = req.body;
const isExistUser = await prisma.Users.findFirst({
where: {
email,
},
});
if (isExistUser) {
return res.status(409).json({ message: "동일한 유저가 있습니다." });
// 409이미 존재하는 id일때
}
const hashedPassword = await bcrypt.hash(password, 10);
// 트랜잭션을 이용한 생성
const [user, userInfo] = await prisma.$transaction(
async (tx) => {
const user = await tx.Users.create({
data: {
email,
password: hashedPassword,
},
});
const userInfo = await tx.UserInfos.create({
data: {
UserId: user.userId,
name,
age,
gender: gender.toUpperCase(),
profileImage,
},
});
return [user, userInfo];
},
{
// 격리수준을 설정한다.
isolationLevel: Prisma.TransactionIsolationLevel.ReadCommitted,
}
);
// const user = await prisma.Users.create({
// data: {
// email,
// password: hashedPassword,
// },
// });
// const userInfo = await prisma.UserInfos.create({
// data: {
// UserId: user.userId,
// name,
// age,
// gender: gender.toUpperCase(),
// profileImage,
// },
// });
return res.status(201).json({ message: "회원가입이 완료 되었습니다." });
} catch (err) {
next(err); // error핸들링 미들웨어 next(err)
}
});