Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass data between various parts of the pipeline in Ktor (Kotlin)

Tags:

kotlin

ktor

Am building an API and using intercept(ApplicationCallPipeline.Call){} to run some logic before each route execution. I need to pass data from the intercept() method to the called route and am setting data by using call.attributes.put() in the intercept() like this:

val userKey= AttributeKey<User>("userK") call.attributes.put(userKey, userData)

And retrieve userData with call.attributes[userKey] . What happens is that call.attributes[userKey] only works in the intercept() method where I have set the attribute. It doesn't work in the route where I need it. It throws me java.lang.IllegalStateException: No instance for key AttributeKey: userK

I wonder if am doing things in the right way

like image 397
Boris EKUE-HETTAH Avatar asked Jan 18 '26 11:01

Boris EKUE-HETTAH


1 Answers

Here is the simplest code reproducing what you describe:

class KtorTest {

    data class User(val name: String)

    private val userKey = AttributeKey<User>("userK")
    private val expected = "expected name"

    private val module = fun Application.() {
        install(Routing) {
            intercept(ApplicationCallPipeline.Call) {
                println("intercept")
                call.attributes.put(userKey, User(expected))
            }

            get {
                println("call")
                val user = call.attributes[userKey]
                call.respond(user.name)
            }

        }
    }

    @Test fun `pass data`() {
        withTestApplication(module) {
            handleRequest {}.response.content.shouldNotBeNull() shouldBeEqualTo expected
        }
    }

}

I intercept the call, put the user in the attributes, and finally respond with the user in the get request. The test passes.

What ktor version are you using and which engine?

like image 140
avolkmann Avatar answered Jan 21 '26 06:01

avolkmann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!