Skip to content

Instantly share code, notes, and snippets.

@andrey-skl
Created June 21, 2018 21:45
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrey-skl/9425ecff502c90f4305e457a5e5890a9 to your computer and use it in GitHub Desktop.
Save andrey-skl/9425ecff502c90f4305e457a5e5890a9 to your computer and use it in GitHub Desktop.
KotlinJS Fetch with coroutines
package app
import kotlinx.coroutines.experimental.await
import org.w3c.fetch.*
import kotlin.browser.window
import kotlin.js.json
class FetchError(message: String, status: Number, response: dynamic) : Error(message)
suspend fun makeError(res: Response): FetchError {
try {
val errorResponse: dynamic = res.json().await()
return FetchError("Request failed", res.status, errorResponse)
} catch (e: Exception) {
val errorResponse = res.text().await()
return FetchError("Request failed", res.status, errorResponse)
}
}
suspend fun <T> request(url: String, method: String = "GET", body: dynamic = null): T {
val res = window.fetch(url, object : RequestInit {
override var method: String? = method
override var body: dynamic = body
override var headers: dynamic = json("Accept" to "application/json")
}).await()
return if (res.ok) res.json().await() as T else throw makeError(res)
}
fun main(args: Array<String>) {
launch {
val loadedUser = request<User>("https://a2pi.github.com/users/huston007")
console.log(loadedUser)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment