How to use response method of com.github.kittinunf.fuel.core.requests.private class

Best Fuel code snippet using com.github.kittinunf.fuel.core.requests.private.response

Zendesk.kt

Source:Zendesk.kt Github

copy

Full Screen

...69}70sealed class ZendeskRequest<out T : ZendeskApiBody>(71    val method: Method,72    val path: String,73    val responseType: KClass<out T>,74    open val body: ZendeskApiBody = ZendeskApiBody.EmptyBody75) {76    open fun get(basePath: String) = Fuel.request(method, basePath + path, null)77        .apply {78            this@ZendeskRequest.body.toOption().map { jsonBody(gson.toJson(it)) }79        }80    data class GetSections(val categoryId: Long) : ZendeskRequest<ZendeskApiBody.SectionsBody>(81        GET, "/categories/$categoryId/sections.json", ZendeskApiBody.SectionsBody::class82    )83    data class CreateSection(val categoryId: Long, val section: NewSection) :84        ZendeskRequest<ZendeskApiBody.ExistingSectionBody>(85            POST,86            "/categories/$categoryId/sections.json",87            ZendeskApiBody.ExistingSectionBody::class,88            ZendeskApiBody.NewSectionBody(section)89        )90    data class DeleteSection(val sectionId: Long) : ZendeskRequest<ZendeskApiBody.EmptyBody>(91        DELETE,92        "/sections/$sectionId.json",93        ZendeskApiBody.EmptyBody::class94    )95    data class CreateArticle(val article: Article) : ZendeskRequest<ZendeskApiBody.ArticleBody>(96        POST,97        "/sections/${article.parentSectionId}/articles.json",98        ZendeskApiBody.ArticleBody::class,99        ZendeskApiBody.ArticleBody(article)100    )101    data class GetArticles(val sectionId: Long) : ZendeskRequest<ZendeskApiBody.ArticlesBody>(102        GET,103        "/sections/$sectionId/articles.json",104        ZendeskApiBody.ArticlesBody::class105    )106    data class UploadAttachedImage(val filePath: String) : ZendeskRequest<ZendeskApiBody.AttachmentBody>(107        POST,108        "/articles/attachments.json",109        ZendeskApiBody.AttachmentBody::class110    ) {111        override fun get(basePath: String): UploadRequest = super.get(basePath).upload()112            .add(FileDataPart(name = "file", file = File(filePath)))113            .add(InlineDataPart(name = "inline", content = "true"))114    }115    data class LinkAttachedImage(val articleId: Long, val attachmentIds: List<Long>) :116        ZendeskRequest<ZendeskApiBody.EmptyBody>(117            POST,118            "/articles/$articleId/bulk_attachments.json",119            ZendeskApiBody.EmptyBody::class,120            ZendeskApiBody.AttachmentIdsBody(attachmentIds)121        )122    data class GetArticleTranslations(val articleId: Long, val locale: String) :123        ZendeskRequest<ZendeskApiBody.TranslationsBody>(124            GET,125            "/articles/$articleId/translations.json",126            ZendeskApiBody.TranslationsBody::class127        )128    data class UpdateArticleTranslation(val translation: Translation) :129        ZendeskRequest<ZendeskApiBody.EmptyBody>(130            PUT,131            "/articles/${translation.sourceId}/translations/${translation.locale}.json",132            ZendeskApiBody.EmptyBody::class,133            ZendeskApiBody.TranslationBody(translation)134        )135}136class Zendesk(137    val url: String,138    val user: String,139    val password: String,140    val categoryId: Long,141    val pattern: String? = null142) {143    fun createSectionOrOverwriteIfExist(section: NewSection) =144        (pattern?.let {145            getSectionWithPattern(it, section.parentSectionId)146        } ?: getSection(section.name, section.parentSectionId))147            .flatMap {148                DeleteSection(it.id)149                    .run()150                    .handleErrorWith {151                        when (it) {152                            is ResourceDoesNotExist -> Unit.right()153                            else -> it.left()154                        }155                    }156                    .also { println("Section for version ${section.name} already exists. Deleting it.") }157                    .map { section }158            }159            .handleErrorWith {160                when (it) {161                    is ResourceDoesNotExist -> section.right()162                    else -> it.left()163                }164            }.flatMap { createSection(it) }165            .map { it.id }166    fun createArticle(article: Article) =167        uploadImages(article)168            .map { attachmentsMapping ->169                attachmentsMapping toT article.replaceImgUrlWithAttachmentUrl(attachmentsMapping)170            }171            .flatmapTupleRight(::postArticle)172            .flatMap { (attachments, articleId) ->173                if (attachments.isNotEmpty())174                    linkAttachmentsToArticle(attachments.values, articleId)175                else176                    Either.right(article)177            }178    fun publishSection(section: ExistingSection) =179        getArticles(section.id)180            .flatMap { articles ->181                articles.map {182                    publishArticle(it)183                }.sequence(Either.applicative()).fix()184            }185            .map { Unit }186    private fun getArticleTranslations(articleId: Long) =187        ZendeskRequest.GetArticleTranslations(articleId, "en-us").run()188            .map {189                it.translations190            }191    private fun getArticles(sectionId: Long) =192        ZendeskRequest.GetArticles(sectionId).run()193            .map {194                it.articles195            }196    private fun updateTranslation(translation: Translation) =197        ZendeskRequest.UpdateArticleTranslation(translation).run()198    private fun publishArticle(article: Article) =199        article.id.rightIfNotNull { HtmlToZendeskError.MissingArticleId }200            .flatMap { getArticleTranslations(it) }201            .flatMap { translations ->202                translations.map { translation ->203                    updateTranslation(translation.copy(draft = false))204                }.sequence(Either.applicative()).fix()205            }206            .map { Unit }207    private fun uploadArticleImage(path: String) =208        ZendeskRequest.UploadAttachedImage(path).run()209            .map { it.articleAttachment }210    private fun uploadImages(article: Article) =211        article.getBodyImages()212            .map { it to uploadArticleImage("${article.path.parent}/$it") }213            .map { (imgName, uploadResult) ->214                uploadResult.fold({215                    it.left()216                }, {217                    (imgName to it).right()218                })219            }220            .sequence(Either.applicative()).fix().map { it.fix().toMap() }221    private fun linkAttachmentsToArticle(attachments: Collection<ArticleAttachment>, articleId: Long) =222        ZendeskRequest.LinkAttachedImage(articleId, attachments.map(ArticleAttachment::id)).run()223    private fun postArticle(article: Article) =224        ZendeskRequest.CreateArticle(article).run()225            .flatMap {226                it.article.id.rightIfNotNull {227                    UnexpectedRequestResult("The id of the article that has been created is not set. $it ")228                }229            }230    fun getSection(name: String, parentSectionId: Long? = null) =231        ZendeskRequest.GetSections(categoryId).run()232            .flatMap {233                it.sections.firstOrNone { it.name == name && it.parentSectionId == parentSectionId }234                    .toEither { ResourceDoesNotExist }235            }236    private fun getSectionWithPattern(pattern: String, parentSectionId: Long? = null) =237        ZendeskRequest.GetSections(categoryId).run()238            .flatMap {239                it.sections.firstOrNone { section ->240                    pattern.toRegex().containsMatchIn(section.name) && section.parentSectionId == parentSectionId241                }.toEither { ResourceDoesNotExist }242            }243    private fun createSection(section: NewSection) =244        ZendeskRequest.CreateSection(categoryId, section)245            .run()246            .map { it.section }247    class ZendeskResponseDeserializable2<T : ZendeskApiBody>(val responseType: KClass<out T>) :248        ResponseDeserializable<T> {249        override fun deserialize(content: String): T = when (responseType) {250            ZendeskApiBody.EmptyBody::class -> ZendeskApiBody.EmptyBody as T251            else -> gson.fromJson(content, responseType.java)252        }253    }254    private fun <T : ZendeskApiBody> ZendeskRequest<T>.run(requestConfigBlock: Request.() -> Unit = {}) =255        get(url)256            .apply(requestConfigBlock)257            .also { println(it) }258            .authentication()259            .basic(user, password)260            .responseObject(ZendeskResponseDeserializable2(responseType))261            .third262            .fold(263                { it.right() },264                {265                    when (it.response.statusCode) {266                        404 -> ResourceDoesNotExist.left()267                        else -> UnexpectedRequestError(it).left()268                    }269                })270}271private fun <A, B, C, D> Either<A, Tuple2<B, C>>.flatmapTupleRight(block: (C) -> Either<A, D>) = flatMap {272    it.map(block).sequence(Either.applicative()).fix().map { it.fix() }273}...

Full Screen

Full Screen

Deserializable.kt

Source:Deserializable.kt Github

copy

Full Screen

...22 * @see ResponseDeserializable23 */24interface Deserializable<out T : Any> {25    /**26     * Deserialize [response] into [T]27     *28     * @param response [Response] the incoming response29     * @return [T] the instance of [T]30     */31    fun deserialize(response: Response): T32}33interface ResponseDeserializable<out T : Any> : Deserializable<T> {34    override fun deserialize(response: Response): T {35        response.body.toStream().use { stream ->36            return deserialize(stream)37                ?: deserialize(stream.reader())38                ?: reserialize(response, stream).let {39                    deserialize(response.data)40                        ?: deserialize(String(response.data))41                        ?: throw FuelError.wrap(IllegalStateException(42                            "One of deserialize(ByteArray) or deserialize(InputStream) or deserialize(Reader) or " +43                                "deserialize(String) must be implemented"44                        ))45                }46        }47    }48    private fun reserialize(response: Response, stream: InputStream): Response {49        val length = response.body.length50        response.body = DefaultBody.from({ stream }, length?.let { l -> { l } })51        return response52    }53    /**54     * Deserialize into [T] from an [InputStream]55     *56     * @param inputStream [InputStream] source bytes57     * @return [T] deserialized instance of [T] or null when not applied58     */59    fun deserialize(inputStream: InputStream): T? = null60    /**61     * Deserialize into [T] from a [Reader]62     *63     * @param reader [Reader] source bytes64     * @return [T] deserialized instance of [T] or null when not applied65     */66    fun deserialize(reader: Reader): T? = null67    /**68     * Deserialize into [T] from a [ByteArray]69     *70     * @note it is more efficient to implement the [InputStream] variant.71     *72     * @param bytes [ByteArray] source bytes73     * @return [T] deserialized instance of [T] or null when not applied74     */75    fun deserialize(bytes: ByteArray): T? = null76    /**77     * Deserialize into [T] from a [String]78     *79     * @note it is more efficient to implement the [Reader] variant.80     *81     * @param content [String] source bytes82     * @return [T] deserialized instance of [T] or null when not applied83     */84    fun deserialize(content: String): T? = null85}86/**87 * Deserialize the [Response] to the [this] into a [T] using [U]88 *89 * @see ResponseResultHandler90 *91 * @param deserializable [U] the instance that performs deserialization92 * @param handler [ResponseResultHandler<T>] handler that has a [Result]93 * @return [CancellableRequest] the request that can be cancelled94 */95fun <T : Any, U : Deserializable<T>> Request.response(deserializable: U, handler: ResponseResultHandler<T>): CancellableRequest =96    response(deserializable,97        { request, response, value -> handler(request, response, Result.Success(value)) },98        { request, response, error -> handler(request, response, Result.Failure(error)) }99    )100/**101 * Deserialize the [Response] to the [this] into a [T] using [U]102 *103 * @see ResultHandler104 *105 * @param deserializable [U] the instance that performs deserialization106 * @param handler [ResultHandler<T>] handler that has a [Result]107 * @return [CancellableRequest] the request that can be cancelled108 */109fun <T : Any, U : Deserializable<T>> Request.response(deserializable: U, handler: ResultHandler<T>): CancellableRequest =110    response(deserializable,111        { _, _, value -> handler(Result.Success(value)) },112        { _, _, error -> handler(Result.Failure(error)) }113    )114/**115 * Deserialize the [Response] to the [this] into a [T] using [U]116 *117 * @see ResponseHandler118 *119 * @param deserializable [U] the instance that performs deserialization120 * @param handler [ResponseHandler<T>] handler that has dedicated paths for success and failure121 * @return [CancellableRequest] the request that can be cancelled122 */123fun <T : Any, U : Deserializable<T>> Request.response(deserializable: U, handler: ResponseHandler<T>): CancellableRequest =124    response(deserializable,125        { request, response, value -> handler.success(request, response, value) },126        { request, response, error -> handler.failure(request, response, error) }127    )128/**129 * Deserialize the [Response] to the [this] into a [T] using [U]130 *131 * @see Handler132 *133 * @param deserializable [U] the instance that performs deserialization134 * @param handler [Handler<T>] handler that has dedicated paths for success and failure135 * @return [CancellableRequest] the request that can be cancelled136 */137fun <T : Any, U : Deserializable<T>> Request.response(deserializable: U, handler: Handler<T>): CancellableRequest =138    response(deserializable,139        { _, _, value -> handler.success(value) },140        { _, _, error -> handler.failure(error) }141    )142/**143 * Deserialize the [Response] to the [this] into a [T] using [U]144 *145 * @note not async, use the variations with a handler instead.146 *147 * @throws Exception if there is an internal library error, not related to Network or Deserialization148 *149 * @param deserializable [U] the instance that performs deserialization150 * @return [ResponseResultOf<T>] the response result of151 */152fun <T : Any, U : Deserializable<T>> Request.response(deserializable: U): ResponseResultOf<T> {153    // First execute the network request and catch any issues154    val rawResponse = runCatching { toTask().call() }155        .onFailure { error ->156            FuelError.wrap(error, Response.error(url)).also {157                return Triple(this, it.response, Result.error(it))158            }159        }160        .getOrThrow()161    // By this time it should have a response, but deserialization might fail162    return runCatching { Triple(this, rawResponse, Result.Success(deserializable.deserialize(rawResponse))) }163        .recover { error -> Triple(this, rawResponse, Result.Failure(FuelError.wrap(error, rawResponse))) }164        .getOrThrow()165}166/**167 * Ignore the response result168 *169 * Use this method to avoid huge memory allocation when using [com.github.kittinunf.fuel.core.requests.download]170 * to a large download and without using the result [ByteArray]171 *172 * @see [com.github.kittinunf.fuel.core.Request.response]173 *174 * @note not async, use the variations with a handler instead.175 *176 * @throws Exception if there is an internal library error, not related to Network177 */178fun Request.responseUnit(): ResponseResultOf<Unit> = response(EmptyDeserializer)179private fun <T : Any, U : Deserializable<T>> Request.response(180    deserializable: U,181    success: (Request, Response, T) -> Unit,182    failure: (Request, Response, FuelError) -> Unit183): CancellableRequest {184    val asyncRequest = RequestTaskCallbacks(185        request = this,186        onSuccess = { response ->187            // The network succeeded but deserialization might fail188            val deliverable = Result.of<T, Exception> { deserializable.deserialize(response) }189            executionOptions.callback {190                deliverable.fold(191                    { success(this, response, it) },192                    { failure(this, response, FuelError.wrap(it, response).also { error ->193                        Fuel.trace { "[Deserializable] unfold failure: \n\r$error" } })194                    }195                )196            }197        },198        onFailure = { error, response ->199            executionOptions.callback {200                failure(this, response, error.also { error ->201                    Fuel.trace { "[Deserializable] callback failure: \n\r$error" }202                })203            }204        }205    )206    return CancellableRequest.enableFor(this, future = executionOptions.submit(asyncRequest))207}208/**209 * Await [T] or throws [FuelError]210 * @return [T] the [T]211 */212@Throws(FuelError::class)213suspend fun <T : Any, U : Deserializable<T>> Request.await(deserializable: U): T {214    val response = suspendable().await()215    return runCatching { deserializable.deserialize(response) }216        .onFailure { throw FuelError.wrap(it, response) }217        .getOrThrow()218}219/**220 * Await the task or throws [FuelError] in current coroutine context.221 *222 * Use this method to avoid huge memory allocation when using [com.github.kittinunf.fuel.core.requests.download]223 * to a large file without using response result224 *225 * To run method in different coroutine context, use `com.github.kittinunf.fuel.coroutines.awaitUnit` in `fuel-coroutines` module226 */227@Throws(FuelError::class)228suspend fun Request.awaitUnit(): Unit = await(EmptyDeserializer)229/**230 * Await [T] or [FuelError]231 * @return [ResponseOf<T>] the [Result] of [T]232 */233@Throws(FuelError::class)234suspend fun <T : Any, U : Deserializable<T>> Request.awaitResponse(deserializable: U): ResponseOf<T> {235    val response = suspendable().await()236    return runCatching { Triple(this, response, deserializable.deserialize(response)) }237        .onFailure { throw FuelError.wrap(it, response) }238        .getOrThrow()239}240/**241 * Await [T] or [FuelError]242 * @return [Result<T>] the [Result] of [T]243 */244suspend fun <T : Any, U : Deserializable<T>> Request.awaitResult(deserializable: U): Result<T, FuelError> {245    val initialResult = suspendable().awaitResult()246    return serializeFor(initialResult, deserializable).map { (_, t) -> t }247}248/**249 * Await [T] or [FuelError]250 * @return [ResponseResultOf<T>] the [ResponseResultOf] of [T]251 */252suspend fun <T : Any, U : Deserializable<T>> Request.awaitResponseResult(deserializable: U): ResponseResultOf<T> {253    val initialResult = suspendable().awaitResult()254    return serializeFor(initialResult, deserializable).let {255            Triple(this,256                it.fold({ (response, _) -> response }, { error -> error.response }),257                it.map { (_, t) -> t }258            )259        }260}261private fun <T : Any, U : Deserializable<T>> serializeFor(result: Result<Response, FuelError>, deserializable: U) =262    result.map { (it to deserializable.deserialize(it)) }263        .mapError <Pair<Response, T>, Exception, FuelError> {264            FuelError.wrap(it, result.getOrElse { Response.error() })265        }...

Full Screen

Full Screen

App.kt

Source:App.kt Github

copy

Full Screen

...11import io.ktor.features.CallLogging12import io.ktor.features.callIdMdc13import io.ktor.http.*14import io.ktor.request.*15import io.ktor.response.header16import io.ktor.response.respond17import io.ktor.response.respondBytes18import io.ktor.routing.Routing19import no.nav.helse.dusseldorf.ktor.core.DefaultProbeRoutes20import no.nav.helse.dusseldorf.ktor.core.log21import no.nav.helse.dusseldorf.ktor.core.logRequests22import org.slf4j.Logger23import org.slf4j.LoggerFactory24import java.io.ByteArrayInputStream25import java.net.URI26import java.util.*27private val logger: Logger = LoggerFactory.getLogger("nav.App")28private const val navCallIdHeader = "Nav-Call-Id"29private val monitoringPaths = listOf("isalive", "isready")30fun main(args: Array<String>): Unit  = io.ktor.server.netty.EngineMain.main(args)31fun Application.helseReverseProxy() {32    val mappings = Environment().getMappings()33    install(Routing) {34        DefaultProbeRoutes()35    }36    intercept(ApplicationCallPipeline.Monitoring) {37        call.request.log(templateQueryParameters = true)38    }39    install(CallId) {40        retrieve { call ->41            call.request.header(HttpHeaders.XCorrelationId) ?: call.request.header(navCallIdHeader)42        }43    }44    install(CallLogging) {45        callIdMdc("correlation_id")46        mdc("request_id") {"generated-${UUID.randomUUID()}"}47        logRequests(templateQueryParameters = true)48    }49    intercept(ApplicationCallPipeline.Call) {50        if (!call.request.isMonitoringRequest()) {51            if (!call.request.hasValidPath()) {52                call.respondErrorAndLog(HttpStatusCode.BadGateway, "Invalid requested path.")53            } else if (!call.request.isMonitoringRequest())  {54                val destinationApplication = call.request.firstPathSegment()55                logger.trace("destinationApplication = '$destinationApplication'")56                val destinationPath = call.request.pathWithoutFirstPathSegment()57                logger.trace("destinationPath = '$destinationPath'")58                val httpMethod = call.request.httpMethod59                logger.trace("httpMethod = '$httpMethod'")60                if (!mappings.containsKey(destinationApplication)) {61                    call.respondErrorAndLog(HttpStatusCode.BadGateway, "Application '$destinationApplication' not configured.")62                } else  {63                    val parameters = call.request.queryParameters.toFuel()64                    val headers = call.request.headers.toFuel()65                    val body = call.receiveOrNull<ByteArray>()66                    val destinationUrl = produceDestinationUrl(destinationPath,67                        mappings.getValue(destinationApplication)68                    )69                    logger.trace("destinationUrl = '$destinationUrl'")70                    val httpRequest = initializeRequest(71                        httpMethod = httpMethod,72                        url = destinationUrl,73                        parameters = parameters74                    )75                        .header(headers)76                        .timeout(20_000)77                        .timeoutRead(20_000)78                    if (body != null) {79                        httpRequest.body( {ByteArrayInputStream(body) })80                    }81                    val (_, response, result) = httpRequest.awaitByteArrayResponseResult()82                    result.fold(83                        { success -> call.forward(response, success)},84                        { failure ->85                            if (-1 == response.statusCode) {86                                logger.error(failure.toString())87                                call.respondErrorAndLog(HttpStatusCode.GatewayTimeout, "Unable to proxy request.")88                            } else {89                                call.forward(response, failure.errorData)90                            }91                        }92                    )93                }94            }95        }96    }97}98private suspend fun ApplicationCall.forward(99    clientResponse: Response,100    body: ByteArray101) {102    clientResponse.headers.forEach { key, value ->103        if (!HttpHeaders.isUnsafe(key)) {104            value.forEach { response.header(key, it) }105        }106    }107    respondBytes(108        bytes = body,109        status = HttpStatusCode.fromValue(clientResponse.statusCode),110        contentType = clientResponse.contentType()111    )112}113private fun Response.contentType(): ContentType {114    val clientContentTypesHeaders = header(HttpHeaders.ContentType)115    return if (clientContentTypesHeaders.isEmpty()) ContentType.Text.Plain else ContentType.parse(clientContentTypesHeaders.first())116}117private fun Headers.toFuel(): Map<String, Any> {118    val fuelHeaders = mutableMapOf<String, Any>()...

Full Screen

Full Screen

CategoriesTest.kt

Source:CategoriesTest.kt Github

copy

Full Screen

2import com.github.kittinunf.fuel.Fuel3import com.github.kittinunf.fuel.core.Response4import com.github.kittinunf.fuel.core.ResponseResultOf5import com.github.kittinunf.fuel.core.requests.DefaultRequest6import com.github.kittinunf.fuel.jackson.responseObject7import com.github.kittinunf.result.Result8import io.mockk.every9import io.mockk.junit5.MockKExtension10import io.mockk.mockk11import io.mockk.mockkObject12import org.junit.jupiter.api.Assertions.assertNotNull13import org.junit.jupiter.api.Assertions.assertTrue14import org.junit.jupiter.api.BeforeEach15import org.junit.jupiter.api.Test16import org.junit.jupiter.api.extension.ExtendWith17import placy.api.Categories18import placy.dto.Category19import placy.dto.requests.DefaultRequestDTO20import java.net.URL...

Full Screen

Full Screen

client.kt

Source:client.kt Github

copy

Full Screen

...7import com.github.kittinunf.fuel.core.ResponseHandler8import com.github.kittinunf.fuel.core.extensions.authentication9import com.github.kittinunf.fuel.core.requests.CancellableRequest10import com.github.kittinunf.fuel.gson.jsonBody11import com.github.kittinunf.fuel.gson.responseObject12private val title = Title("Termine")13data class Title(val raw: String)14data class Content(val raw: String)15data class Page(val title: Title, val content: Content)16private fun Request.authenticate(userData: UserData) = authentication().basic(userData.username, userData.password)17fun updateEventsPage(userData: UserData, events: Events, handler: ResponseHandler<Page>): CancellableRequest {18    val raw = buildString { render(events) }19    val page = Page(title, Content(raw))20    return Fuel.post(userData.calendarUrl)21        .authenticate(userData)22        .jsonBody(page)23        .responseObject(handler)24}...

Full Screen

Full Screen

http.kt

Source:http.kt Github

copy

Full Screen

...10    val request = Fuel.get(url)11    token?.let {12        request.header(Headers.AUTHORIZATION, "token $it")13    }14    return request.response()15}16fun postRequest(url: String, jsonBody: String? = null, token: String? = null): ResponseResultOf<ByteArray> {17    val request = Fuel.post(url)18    token?.let {19        request.header(Headers.AUTHORIZATION, "token $it")20    }21    jsonBody?.let {22        request.body(it)23    }24    return request.response()25}26fun Response.getBody(): String = this.body().asString(this.headers[Headers.CONTENT_TYPE].lastOrNull())27fun Response.isOK(): Boolean = this.statusCode == HttpStatus.OK...

Full Screen

Full Screen

GalleryRepository.kt

Source:GalleryRepository.kt Github

copy

Full Screen

2import com.github.kittinunf.fuel.Fuel3import com.github.kittinunf.fuel.core.FuelError4import com.github.kittinunf.fuel.core.Request5import com.github.kittinunf.fuel.core.requests.tryCancel6import com.github.kittinunf.fuel.gson.responseObject7import com.yoesuv.networkkotlin2.data.EndPoint8import com.yoesuv.networkkotlin2.menu.gallery.models.GalleryModel9import com.yoesuv.networkkotlin2.utils.debugPrintStackTrace10class GalleryRepository {11    private lateinit var requestGallery: Request12    fun getListGallery(onSuccess:(GalleryModel) -> Unit, onError:(FuelError) -> Unit) {13        requestGallery = Fuel.get(EndPoint.LIST_GALLERY).responseObject<GalleryModel> { _, _, result ->14            result.fold({15                onSuccess(it)16            }, {17                onError(it)18                debugPrintStackTrace(it)19            })20        }21    }22    fun cleared() {23        requestGallery.tryCancel(true)24    }25}...

Full Screen

Full Screen

WisataRepository.kt

Source:WisataRepository.kt Github

copy

Full Screen

2import com.github.kittinunf.fuel.Fuel3import com.github.kittinunf.fuel.core.FuelError4import com.github.kittinunf.fuel.core.Request5import com.github.kittinunf.fuel.core.requests.tryCancel6import com.github.kittinunf.fuel.gson.responseObject7import com.magang.kelilingapp.model.Wisata8class WisataRepository {9    private var URL = "https://wisatasurabayaapi.herokuapp.com/api"10    private lateinit var requestGallery: Request11    fun getWisataList(onSuccess:(Wisata) -> Unit, onError:(FuelError) -> Unit) {12        requestGallery = Fuel.get(URL).responseObject<Wisata> { _, _, result ->13            result.fold({14                onSuccess(it)15            }, {16                onError(it)17            })18        }19    }20    fun cleared() {21        requestGallery.tryCancel(true)22    }23}

Full Screen

Full Screen

response

Using AI Code Generation

copy

Full Screen

1fun <T> Result<T, FuelError>.response(): Response<T> = Response(this)2val data = result.data()3val error = result.error()4val string = result.asString()5val jsonObject = result.asJsonObject()6val jsonArray = result.asJsonArray()7val inputStream = result.asInputStream()8val file = result.asFile("file.txt")

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful