Skip to content

Instantly share code, notes, and snippets.

View RoRoche's full-sized avatar

Romain Rochegude RoRoche

View GitHub Profile
import okhttp3.Response
class WithBodyRestRequest(origin: RestRequest) : RestRequest.Wrap(origin) {
override fun response(): Response {
val response = super.response()
if (response.body != null) {
return response
} else {
throw NoBodyRestResponseException()
}
import okhttp3.Response
class SuccessfulRestRequest(origin: RestRequest) : RestRequest.Wrap(origin) {
override fun response(): Response {
val response = super.response()
if (response.isSuccessful) {
return response
} else {
throw RestRequestFailureException(response)
}
D/GetReposRequest: response - started
D/GetReposRequest: response - done with Response{protocol=http/1.1, code=200, message=OK, url=https://api.github.com/users/RoRoche/repos}
val repos: List<Repo> = JsonRepos(
WithBodyRestRequest(
SuccessfulRestRequest(
LoggableRequest(
GetReposRequest(
client = client,
baseUrl = "https://api.github.com/",
user = "RoRoche"
)
)
import android.util.Log
import okhttp3.Response
class LoggableRequest(
origin: RestRequest,
private val tag: String = origin.javaClass.simpleName
) : RestRequest.Wrap(origin) {
override fun response(): Response {
Log.d(tag, "response - started")
val response = super.response()
val repos: List<Repo> = JsonRepos(
GetReposRequest(
client = client,
baseUrl = "https://api.github.com/",
user = "RoRoche"
)
)
import okhttp3.Response
import org.json.JSONArray
class JsonRepos(private val repos: List<Repo>) : List<Repo> by repos {
constructor(json: String) : this(JSONArray(json))
constructor(jsonArray: JSONArray) : this(
(0 until jsonArray.length())
.map(jsonArray::getJSONObject)
.map { JsonRepo(it) }
import org.json.JSONObject
class JsonRepo(private val jsonObject: JSONObject) : Repo {
override fun id(): Long = jsonObject.getLong("id")
override fun name(): String = jsonObject.getString("name")
override fun description(): String = jsonObject.getString("description")
interface Repo {
fun id(): Long
fun name(): String
fun description(): String
fun url(): String
}
import okhttp3.Call
import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
class GetReposRequest(private val call: Call) : RestRequest {
constructor(client: OkHttpClient, baseUrl: String, user: String) : this(
client,