Add validation on route CreateCommentArticle

This commit is contained in:
2021-04-09 00:58:35 +02:00
parent 13cdaaf01a
commit a07b19a3cb
4 changed files with 68 additions and 18 deletions

View File

@@ -1,6 +1,6 @@
package fr.dcproject.component.comment.article.routes
import fr.dcproject.common.response.toOutput
import fr.dcproject.application.http.badRequestIfNotValid
import fr.dcproject.common.security.assert
import fr.dcproject.common.utils.receiveOrBadRequest
import fr.dcproject.component.article.database.ArticleRef
@@ -12,6 +12,9 @@ import fr.dcproject.component.comment.article.routes.CreateCommentArticle.PostAr
import fr.dcproject.component.comment.generic.CommentAccessControl
import fr.dcproject.component.comment.generic.database.CommentForUpdate
import fr.dcproject.component.comment.toOutput
import io.konform.validation.Validation
import io.konform.validation.jsonschema.maxLength
import io.konform.validation.jsonschema.minLength
import io.ktor.application.call
import io.ktor.http.HttpStatusCode
import io.ktor.locations.KtorExperimentalLocationsAPI
@@ -26,27 +29,36 @@ object CreateCommentArticle {
@Location("/articles/{article}/comments")
class PostArticleCommentRequest(article: UUID) {
val article = ArticleRef(article)
class Input(val content: String)
class Input(val content: String) {
fun validate() = Validation<Input> {
Input::content {
minLength(20)
maxLength(6000)
}
}.validate(this)
}
}
fun Route.createCommentArticle(repo: CommentArticleRepository, ac: CommentAccessControl) {
post<PostArticleCommentRequest> {
mustBeAuth()
call.receiveOrBadRequest<Input>().run {
CommentForUpdate(
target = it.article,
createdBy = citizen,
content = content
)
}.let { comment ->
ac.assert { canCreate(comment, citizenOrNull) }
repo.comment(comment)
call.receiveOrBadRequest<Input>()
.apply { validate().badRequestIfNotValid() }
.run {
CommentForUpdate(
target = it.article,
createdBy = citizen,
content = content
)
}.let { comment ->
ac.assert { canCreate(comment, citizenOrNull) }
repo.comment(comment)
call.respond(
HttpStatusCode.Created,
comment.toOutput()
)
}
call.respond(
HttpStatusCode.Created,
comment.toOutput()
)
}
}
}
}