실무 프로젝트로 배우는 Kotlin & Spring/이슈 관리 서비스 개발하기

코멘트 등록

webmaster 2022. 11. 27. 22:42
728x90

Domain

comment

@Entity
@Table
class Comment(
    @Id @GeneratedValue(strategy = IDENTITY)
    val id: Long? = null,

    @ManyToOne(fetch = LAZY)
    @JoinColumn(name = "issue_id")
    val issue: Issue,

    @Column
    val userId: Long,

    @Column
    val username: String,

    @Column
    var body: String,
    ): BaseEntity() {

}

Issue 필드 추가

@Entity
@Table
class Issue(
  	//...
    
    @OneToMany(fetch = EAGER)
    val comments: MutableList<Comment> = mutableListOf(),
	
    //..
) : BaseEntity() {

}

Repository

interface CommentRepository : JpaRepository<Comment, Long> {
}

Service

@Service
class CommentService(
    private val commentRepository: CommentRepository,
    private val issueRepository: IssueRepository,
) {
    @Transactional
    fun create(
        issueId: Long,
        userId: Long,
        username: String,
        request: CommentRequest,
    ) : CommentResponse {
        val issue = issueRepository.findByIdOrNull(issueId) ?: throw NotFoundException("이슈가 존재하지 않습니다.")
        val comment = Comment(
            issue = issue,
            userId = userId,
            username = username,
            body = request.body,
        )
        issue.comments.add(comment)
        return commentRepository.save(comment).toResponse()
    }
}
  • issue를 조회해야 하므로, issueRepository도 주입받는다.
  • 확장 함수 기능을 이용하여 Comment을 toReponse 함수를 작성해 Comment를 CommentResponse로 변경해준다.

Controller

@RestController
@RequestMapping("/api/v1/issues/{issueId}/comments")
class CommentController(
    private val commentService: CommentService,
) {

    @PostMapping
    fun create(
        authUser: AuthUser,
        @PathVariable issueId: Long,
        @RequestBody request: CommentRequest,
    ): CommentResponse {
        return commentService.create(issueId, authUser.userId, authUser.username, request)
    }
}

 

728x90