https://kotlinlang.org logo
#ktor
Title
# ktor
l

Luca Gentile

08/11/2021, 3:43 PM
Hello, I would like that when parsing a body request in
Copy code
call.receive<FooRequest>()
to sanitize all fields declared as String in
FooRequest
What would you suggest?
a

Aleksei Tirman [JB]

08/11/2021, 3:53 PM
The simplest thing would be to validate them after deserialization. Could you please describe your problem in more detail?
e

e5l

08/12/2021, 8:38 AM
Hey @Luca Gentile, you can write validation in the
init
block of the
FooRequest
l

Luca Gentile

08/12/2021, 9:13 AM
I was thinking of something like: "every time the object mapper should transform a value from the call to a String property of the FooRequest, sanitize the field"
e

e5l

08/12/2021, 9:13 AM
It depends on the serialization library you're using
l

Luca Gentile

08/12/2021, 9:14 AM
at the moment I'm using Jackson
e

e5l

08/12/2021, 9:14 AM
Yep, I guess only
kotlinx.serialization
allow you to do this in the init block, it should be default way in Jackson
l

Luca Gentile

08/12/2021, 9:16 AM
ok, but that way for every DTO like FooRequest used in my api, I need to write a sanitation for string properties
I would like to do something that does that just in time, maybe you have some ideas
so that
val dto = call.receive<AnyRequest>()
inside
dto
every String is already trimmed, html escaped etc.
no matter the <AnyRequest>
without the need via init block in every
FooRequest
BarRequest
a

Aleksei Tirman [JB]

08/12/2021, 11:54 AM
I didn't find any information on how you can do it with Jackson. You could probably use Kotlin reflection to sanitize all string fields after deserialization without introducing much code duplication.
l

Luca Gentile

08/12/2021, 11:58 AM
me neither. Yeah, probably I'll go that way
thanks!
6 Views