Filip Andersen
10/14/2024, 8:00 AMAleksei Tirman [JB]
10/14/2024, 8:52 AMFilip Andersen
10/14/2024, 9:04 AMfun Route.exampleRoute() {
route("users/apikey") {
exampleRouteGet()
}
}
fun Route.exampleRouteGet() {
val userService: UserService by inject<UserService>()
val client: HttpClient by inject<HttpClient>()
get("") {
val principal = call.principal<JWTPrincipal>()
checkNotNull(principal) { "Principal is null" }
val userId: String = principal.payload.getClaim("userId").asString()
val token = call.request.parseAuthorizationHeader().toString().removePrefix("Bearer ")
val apiKey = userService.findApiKey(userId, token)
val response = client.get("someurlexample.com") {
headers.append("X-Api-Key", apiKey)
}
/**
* Send result back to frontend
*/
}
}
Service layer:
class UserService(private val userCache: UserCache, private val httpClient: HttpClient) {
suspend fun findApiKey(userId: String, token: String): String {
val apiKey = userCache.readUserApiCache(userId)
if (apiKey != null) return apiKey
val response = httpClient.get("someotherapi.com/apikey") {
bearerAuth(token)
}
/**
* Handle result and store in cache
*/
return apiKey
}
}
Anthony Legay
10/14/2024, 9:30 AMcontext(ApplicationCall)
class UserService(private val userCache: UserCache, private val httpClient: HttpClient) {
suspend fun findApiKey(userId: String): String {
val apiKey = userCache.readUserApiCache(userId)
if (apiKey != null) return apiKey
val response = httpClient.get("someotherapi.com/apikey") {
// here you can access the request from the call
bearerAuth(request.authorization())
}
/**
* Handle result and store in cache
*/
return apiKey
}
}
Also, notice the helper request.authorization()
from the call instance. This helps to retrieve the bearer easily
Given you’re using Koin, you may have to annotate the method instead of the entire class with the context()
. I don’t know if it would work that way.Filip Andersen
10/14/2024, 3:39 PM