Light Blue Pointer
본문 바로가기
Developing/Journal

✨Repository가 다르다고 Model도 다를 필요는 없다👍

by Greedy 2024. 6. 20.

✨Repository를 나눠서 model도 나눴던 것 통합

서버 채팅을 조회할 때는 채팅방 채팅을 조회할 필요가 없고

채팅방 채팅을 조회할때는 서버 채팅을 조회할 필요가 없는데

둘 다 ChatRepository에 저장하게 되면 조회 성능이 안 좋아질 것 같아서

Repository를 RoomChatRepository , ServerChatRepository로 분리했었다

@NoArg
@Document(collection = "chats")
class RoomChat(
  val userId: String,
  val roomId: String,
  val content: String,
) : BaseTime() {
  @Id
  var id: String? = null

  fun isEdited(): Boolean {
    return !createdAt.equals(updatedAt)
  }
}
@NoArg
@Document(collection = "server_chats")
class ServerChat(
  val userId: String,
  val serverId: String,
  val content: String,
) : BaseTime() {
  @Id
  var id: String? = null

  fun isEdited(): Boolean {
    return !createdAt.equals(updatedAt)
  }
}
@Repository
interface RoomChatRepository : MongoRepository<RoomChat, String>, QuerydslPredicateExecutor<RoomChat> {
  fun findAllByRoomId(
    roomId: String,
    pageable: Pageable,
  ): List<RoomChat>
}
@Repository
interface ServerChatRepository : MongoRepository<ServerChat, String>, QuerydslPredicateExecutor<ServerChat> {
  fun findAllByServerId(
    serverId: String,
    pageable: Pageable,
  ): List<ServerChat>
}

 

하지만 다시 생각해 보니 둘 다 거의 똑같은 model을 사용하고 있는데 굳이 model이 나뉘어야 할 필요성을 못 느껴서

두개를 다시 Chat으로 통합하고 RoomChatRepository , ServerChatRepository가 Chat을 저장하도록 했다

@NoArg
@Document(collection = "chats")
class Chat(
  @Id
  val id: String? = null,
  val userId: String,
  // roomId or serverId
  val contextId: String,
  var content: String,
) : BaseTime() {
  fun isEdited(): Boolean {
    return !createdAt.equals(updatedAt)
  }

  fun updateContent(content: String) {
    this.content = content
  }
}
@Repository
interface RoomChatRepository : MongoRepository<Chat, String>, QuerydslPredicateExecutor<Chat> {
  fun findAllByContextId(
    contextId: String,
    pageable: Pageable,
  ): List<Chat>
}
@Repository
interface ServerChatRepository : MongoRepository<Chat, String>, QuerydslPredicateExecutor<Chat> {
  fun findAllByContextId(
    serverId: String,
    pageable: Pageable,
  ): List<Chat>
}