https://kotlinlang.org logo
Title
u

user

04/18/2019, 1:41 PM
How to create reusable interceptors in ktor? In ktor, it appears the way to do customized permissions checks is through interceptors, like so: route("/portal") { route("articles") { … } route("admin") { intercept(ApplicationCallPipeline.Features) { … } // verify admin privileges route("article/{id}") { … } // manage article with {id} route("profile/{id}") { … } // manage profile with {id} } } What is the best way to extract the interceptor logic for reuse for other routes elsewhere in the codebase?
h

hdarritchon

04/20/2019, 7:16 AM
Hi, sorry to be late 🙂 In my code, I made routes, some routes have an interceptor to measure and log the time of the execution where as others not. So I have made a function to do so following the exemple in the documentation (https://ktor.io/advanced/pipeline/route.html#) and then I have but this function around a block of routes that needed to be measured. Please find my code below 😉
install(Routing) {
        val konfig = HoconKonfigAdapter()
        val contextPath = konfig.get("ktor.deployment.context-path")
        route("$contextPath/api/v1") {
            val registry = feature(Metrics).registry

            healthEndPoints()
            metricsEndPoints(registry)
            routeWithMeasureTime {
                catalogSiEndPoints()
                reunionCatalogEditoEndPoints()
                telesurveillanceCatalogEditoEndPoints()
                catalogLegacyEndPoints()
            }
        }
    }
all the routes inside the block routeWithMeasureTime will be intercepted and measured. The other one, no. Hope it helps event so late 😉