Created
June 21, 2018 21:45
-
-
Save andrey-skl/9425ecff502c90f4305e457a5e5890a9 to your computer and use it in GitHub Desktop.
KotlinJS Fetch with coroutines
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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