Hi, my app is acting like a proxy between the clie...
# ktor
a
Hi, my app is acting like a proxy between the client app and server. A client makes a request, if cached data is valid i.e. not expired, I serve him that, otherwise I make a request to the server, get data, cache it, and then serve it to the client. I wrote some code, but it's not thread-safe. How can I improve this so I do not make unnecessary requests to the server?
Copy code
fun Application.module() {
    val client = HttpClient(OkHttp) {
        install(JsonFeature) {
            serializer = GsonSerializer()
        }
    }
    var cached: Data? = null
    routing {
        get("/") {
            if (cached == null) {
                val new = client.get<Data>("<https://my-host.com/message>")
                cached = new
            }
            if (cached!!.expires < System.currentTimeMillis()) {
                val new = client.get<Data>("<https://my-host.com/message>")
                cached = new
            }
            call.respond(cached!!.message)
        }
    }
}

data class Data(val expires: Long, val message: String)
a
Thanks!