Created
November 11, 2021 13:59
-
-
Save khle/8fe94890277e1b5ddd20aab9a2684afe to your computer and use it in GitHub Desktop.
RequesterGQL.kt
This file contains hidden or 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 my.androidapp | |
import okhttp3.* | |
import okhttp3.MediaType.Companion.toMediaTypeOrNull | |
import okhttp3.RequestBody.Companion.toRequestBody | |
import okio.IOException | |
import org.json.JSONObject | |
import kotlin.coroutines.resume | |
import kotlin.coroutines.resumeWithException | |
import kotlin.coroutines.suspendCoroutine | |
private const val SHOW_ERROR_LIMIT = 20 | |
enum class Action { | |
GET, | |
POST, | |
PUT, | |
DELETE, | |
PATCH, | |
} | |
class RequesterGQL { | |
suspend fun <M> makeRequest(serviceUrl: String, headersMap: Map<String, String>, bodyJSON: JSONObject, action: Action, fromJson: (String) -> M?) : M { | |
val result: M = suspendCoroutine { cont -> | |
val client = OkHttpClient() | |
val requestBody = bodyJSON.toString() | |
.toRequestBody("application/json; charset=utf-8".toMediaTypeOrNull()) | |
val requestBuilder: Request.Builder = Request.Builder().url(serviceUrl) | |
headersMap.forEach { requestBuilder.addHeader(it.key, it.value) } | |
var request: Request = when (action) { | |
Action.GET -> requestBuilder.build() | |
Action.POST -> requestBuilder.post(requestBody).build() | |
Action.PUT -> requestBuilder.put(requestBody).build() | |
Action.DELETE -> requestBuilder.delete(requestBody).build() | |
Action.PATCH -> requestBuilder.patch(requestBody).build() | |
} | |
client.newCall(request).enqueue(object : Callback { | |
override fun onFailure(call: Call, e: IOException) { | |
cont.resumeWithException(Exception(e.message.let { e.message } | |
?: e.toString().take(SHOW_ERROR_LIMIT))) | |
} | |
override fun onResponse(call: Call, response: Response) { | |
response.use { | |
if (response.isSuccessful) { | |
val jsonBody = response.body?.let { it1 -> it1.string() } | |
try { | |
val maybeResult = jsonBody?.let { fromJson(it) } | |
maybeResult?.also { result -> | |
cont.resume(result) | |
} ?: run { | |
cont.resumeWithException(Exception("Unable to parse $jsonBody.take(SHOW_ERROR_LIMIT)")) | |
} | |
} catch (t: Throwable) { | |
cont.resumeWithException(Exception("$jsonBody: Unable to parse $t.toString().take(SHOW_ERROR_LIMIT)")) | |
} | |
} else { | |
cont.resumeWithException(Exception(response.message)) | |
} | |
} | |
} | |
}) | |
} | |
return result | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment