Can Comment a Comment

This commit is contained in:
2019-10-15 15:46:19 +02:00
parent 499fbd6dcf
commit 8cb5c35296
4 changed files with 77 additions and 13 deletions

View File

@@ -1,17 +1,19 @@
package fr.dcproject.routes
import fr.dcproject.security.voter.CommentVoter.Action.UPDATE
import fr.dcproject.security.voter.CommentVoter.Action.VIEW
import fr.dcproject.citizen
import fr.dcproject.entity.Comment
import fr.dcproject.routes.CommentPaths.CreateCommentRequest.Content
import fr.dcproject.security.voter.CommentVoter.Action.*
import fr.dcproject.security.voter.assertCan
import io.ktor.application.call
import io.ktor.features.NotFoundException
import io.ktor.http.HttpStatusCode
import io.ktor.locations.KtorExperimentalLocationsAPI
import io.ktor.locations.Location
import io.ktor.locations.get
import io.ktor.locations.put
import io.ktor.locations.*
import io.ktor.request.receive
import io.ktor.request.receiveText
import io.ktor.response.respond
import io.ktor.routing.Route
import io.ktor.util.KtorExperimentalAPI
import java.util.*
import fr.dcproject.repository.CommentGeneric as CommentRepository
@@ -30,8 +32,14 @@ object CommentPaths {
val page: Int = if (page < 1) 1 else page
val limit: Int = if (limit > 50) 50 else if (limit < 1) 1 else limit
}
@Location("/comments/{comment}/children")
class CreateCommentRequest(val comment: UUID) {
class Content(val content: String)
}
}
@KtorExperimentalAPI
@KtorExperimentalLocationsAPI
fun Route.comment(repo: CommentRepository) {
get<CommentPaths.CommentRequest> {
@@ -54,6 +62,21 @@ fun Route.comment(repo: CommentRepository) {
call.respond(HttpStatusCode.OK, comments)
}
post<CommentPaths.CreateCommentRequest> {
val parent = repo.findById(it.comment) ?: throw NotFoundException("Comment not found")
val newComment = Comment(
content = call.receive<Content>().content,
createdBy = citizen,
parent = parent
)
assertCan(CREATE, newComment)
repo.comment(newComment)
call.respond(HttpStatusCode.Created, newComment)
}
put<CommentPaths.CommentRequest> {
val comment = repo.findById(it.comment)!!
assertCan(UPDATE, comment)