어제 지도페이지에서 다시 에러가 발생했다.
지난번과 같은 에러인가? 그렇다기엔 로직을 수정해서 여태 에러없이 잘 지내왔잖아?!
탈퇴 시 연관관계로 인해 게시글이 삭제되는데 해당 게시글의 장소 정보는 테이블에 남아있고, 해당 장소에 대한 게시글은 없어서 생긴 에러라고 생각을 했다. (전과 같은 에러라고 생각)
( 1차 띠용 구간 : 회원탈퇴 할 때 postCount update해주는 로직이 없었음. )
그래서 회원 탈퇴 시
1) 유저가 작성한 게시글의 개수를 구해서 postCount 를 업데이트 해주는 로직과
2) location table의 postCount가 0이 되면 해당 location 정보가 삭제되도록 로직을 넣음
updateUserPostsCounts = async (userId) => {
// 유저가 작성한 게시글
const userPosts = await prisma.posts.findMany({
where: {
UserId: +userId,
},
});
for (const post of userPosts) {
const userLocation = await prisma.locations.update({
where: {
locationId: post.LocationId,
},
data: {
postCount: {
decrement: 1,
},
},
});
if (userLocation.postCount === 0) {
await prisma.locations.delete({
where: { locationId: userLocation.locationId }
})
}
}
};
그러고 로컬 db로 확인해봤는데 해당 유저가 3개 쓴 글밖에 없는 location의 경우 이상없이 삭제가 되었지만,
location 테이블에 userId 정보( 맨 처음 작성한 userId가 들어감 )가 같이 들어있어서
해당 유저가 탈퇴해버리면 게시글이 남아있더라도 장소 정보가 삭제가 되어버렸다.
( 2차 띠용 구간 : location table에서 userId를 뺀 줄 알았는데 안빠져있었음 )
그래서 schema에서 userId를 삭제, 관계를 끊었다. ( 유저 탈퇴 시 장소 정보 없어지는 경우 없앰 )
// Locations 테이블과 Users 테이블의 관계를 끊음
model Locations {
locationId Int @id @default(autoincrement()) @map("locationId")
CategoryId Int @map("CategoryId")
DistrictId Int @map("DistrictId")
// UserId Int @map("UserId")
storeName String @map("storeName")
address String @map("address")
latitude String @map("latitude")
longitude String @map("longitude")
starAvg Int @map("starAvg")
postCount Int @default(0) @map("postCount")
placeInfoId String? @map("placeInfoId")
Category Categories @relation(fields: [CategoryId], references: [categoryId], onDelete: Cascade)
District Districts @relation(fields: [DistrictId], references: [districtId], onDelete: Cascade)
// User Users @relation(fields: [UserId], references: [userId], onDelete: Cascade)
Posts Posts[]
Bookmark Bookmark[]
@@map("Locations")
}
model Users {
userId Int @id @default(autoincrement()) @map("userId")
email String @map("email")
password String @map("password")
nickname String @map("nickname")
imgUrl String @map("imgUrl")
snsId String? @map("snsId")
provider String? @map("provider")
createdAt DateTime @default(now()) @map("createdAt")
updatedAt DateTime @updatedAt @map("updatedAt")
Posts Posts[]
Comments Comments[]
Likes Likes[]
Bookmark Bookmark[]
RefreshTokens RefreshTokens[]
// Location Locations[]
Replies Replies[]
@@map("Users")
}
//posts.repository.js 내용 수정 : location 정보를 만드는데 연관되어있는 user정보를 없앴다.
const createLocation = await this.prisma.locations.create({
data: {
storeName,
address,
latitude,
longitude,
starAvg: star,
postCount: 1,
placeInfoId,
Category: { connect: { categoryId: +category.categoryId } },
District: { connect: { districtId: +district.districtId } },
// User: { connect: { userId: +userId } },
},
});
일단 내가 발견한 부분은 이렇다...
근데 이게 맞는가 의문이 든다. 발견한 현상에 대해서 디버깅한 결과는 이런데,,,
로직자체가 너무 어렵게 굴러가는건 아닌지 너무 고민스럽다.
같이 이런 내용에 대해서 로직이 너무 복잡하다, 간단하게 만들어보자라며 같이 고민할 사람이 필요하다.
내가 쉬운 문제를 너무 어렵게만 접근하는 것 같다.