https://kotlinlang.org logo
Docs
Join the conversationJoin Slack
Channels
100daysofcode
100daysofkotlin
100daysofkotlin-2021
advent-of-code
aem
ai
alexa
algeria
algolialibraries
amsterdam
android
android-architecture
android-databinding
android-studio
androidgithubprojects
androidthings
androidx
androidx-xprocessing
anime
anko
announcements
apollo-kotlin
appintro
arabic
argentina
arkenv
arksemdevteam
armenia
arrow
arrow-contributors
arrow-meta
ass
atlanta
atm17
atrium
austin
australia
austria
awesome-kotlin
ballast
bangladesh
barcelona
bayarea
bazel
beepiz-libraries
belgium
berlin
big-data
books
boston
brazil
brikk
budapest
build
build-tools
bulgaria
bydgoszcz
cambodia
canada
carrat
carrat-dev
carrat-feed
chicago
chile
china
chucker
cincinnati-user-group
cli
clikt
cloudfoundry
cn
cobalt
code-coverage
codeforces
codemash-precompiler
codereview
codingame
codingconventions
coimbatore
collaborations
colombia
colorado
communities
competitive-programming
competitivecoding
compiler
compose
compose-android
compose-desktop
compose-hiring
compose-ios
compose-mp
compose-ui-showcase
compose-wear
compose-web
connect-audit-events
corda
cork
coroutines
couchbase
coursera
croatia
cryptography
cscenter-course-2016
cucumber-bdd
cyprus
czech
dagger
data2viz
databinding
datascience
dckotlin
debugging
decompose
decouple
denmark
deprecated
detekt
detekt-hint
dev-core
dfw
docs-revamped
dokka
domain-driven-design
doodle
dsl
dublin
dutch
eap
eclipse
ecuador
edinburgh
education
effective-kotlin
effectivekotlin
emacs
embedded-kotlin
estatik
event21-community-content
events
exposed
failgood
fb-internal-demo
feed
firebase
flow
fluid-libraries
forkhandles
forum
fosdem
fp-in-kotlin
framework-elide
freenode
french
fritz2
fuchsia
functional
funktionale
gamedev
ge-kotlin
general-advice
georgia
geospatial
german-lang
getting-started
github-workflows-kt
glance
godot-kotlin
google-io
gradle
graphic
graphkool
graphql
graphql-kotlin
graviton-browser
greece
grpc
gsoc
gui
hackathons
hacktoberfest
hamburg
hamkrest
helios
helsinki
hexagon
hibernate
hikari-cp
hire-me
hiring
hongkong
hoplite
http4k
hungary
hyderabad
image-processing
india
indonesia
inkremental
intellij
intellij-plugins
intellij-tricks
internships
introduce-yourself
io
ios
iran
israel
istanbulcoders
italian
jackson-kotlin
jadx
japanese
jasync-sql
java-to-kotlin-refactoring
javadevelopers
javafx
javalin
javascript
jdbi
jhipster-kotlin
jobsworldwide
jpa
jshdq
juul-libraries
jvm-ir-backend-feedback
jxadapter
k2-early-adopters
kaal
kafka
kakao
kalasim
kapt
karachi
karg
karlsruhe
kash_shell
kaskade
kbuild
kdbc
kgen-doc-tools
kgraphql
kinta
klaxon
klock
kloudformation
kmdc
kmm-español
kmongo
knbt
knote
koalaql
koans
kobalt
kobweb
kodein
kodex
kohesive
koin
koin-dev
komapper
kondor-json
kong
kontent
kontributors
korau
korean
korge
korim
korio
korlibs
korte
kotest
kotest-contributors
kotless
kotlick
kotlin-asia
kotlin-beam
kotlin-by-example
kotlin-csv
kotlin-data-storage
kotlin-foundation
kotlin-fuel
kotlin-in-action
kotlin-inject
kotlin-latam
kotlin-logging
kotlin-multiplatform-contest
kotlin-mumbai
kotlin-native
kotlin-pakistan
kotlin-plugin
kotlin-pune
kotlin-roadmap
kotlin-samples
kotlin-sap
kotlin-serbia
kotlin-spark
kotlin-szeged
kotlin-website
kotlinacademy
kotlinbot
kotlinconf
kotlindl
kotlinforbeginners
kotlingforbeginners
kotlinlondon
kotlinmad
kotlinprogrammers
kotlinsu
kotlintest
kotlintest-devs
kotlintlv
kotlinultimatechallenge
kotlinx-datetime
kotlinx-files
kotlinx-html
kotrix
kotson
kovenant
kprompt
kraph
krawler
kroto-plus
ksp
ktcc
ktfmt
ktlint
ktor
ktp
kubed
kug-leads
kug-torino
kvision
kweb
lambdaworld_cadiz
lanark
language-evolution
language-proposals
latvia
leakcanary
leedskotlinusergroup
lets-have-fun
libgdx
libkgd
library-development
linkeddata
lithuania
london
losangeles
lottie
love
lychee
macedonia
machinelearningbawas
madrid
malaysia
mathematics
meetkotlin
memes
meta
metro-detroit
mexico
miami
micronaut
minnesota
minutest
mirror
mockk
moko
moldova
monsterpuzzle
montreal
moonbean
morocco
motionlayout
mpapt
mu
multiplatform
mumbai
munich
mvikotlin
mvrx
myndocs-oauth2-server
naming
navigation-architecture-component
nepal
new-mexico
new-zealand
newname
nigeria
nodejs
norway
npm-publish
nyc
oceania
ohio-kotlin-users
oldenburg
oolong
opensource
orbit-mvi
osgi
otpisani
package-search
pakistan
panamá
pattern-matching
pbandk
pdx
peru
philippines
phoenix
pinoy
pocketgitclient
polish
popkorn
portugal
practical-functional-programming
proguard
prozis-android-backup
pyhsikal
python
python-contributors
quasar
random
re
react
reaktive
realm
realworldkotlin
reductor
reduks
redux
redux-kotlin
refactoring-to-kotlin
reflect
refreshversions
reports
result
rethink
revolver
rhein-main
rocksdb
romania
room
rpi-pico
rsocket
russian
russian_feed
russian-kotlinasfirst
rx
rxjava
san-diego
science
scotland
scrcast
scrimage
script
scripting
seattle
serialization
server
sg-user-group
singapore
skia-wasm-interop-temp
skrape-it
slovak
snake
sofl-user-group
southafrica
spacemacs
spain
spanish
speaking
spek
spin
splitties
spotify-mobius
spring
spring-security
squarelibraries
stackoverflow
stacks
stayhungrystayfoolish
stdlib
stlouis
strife-discord-lib
strikt
students
stuttgart
sudan
swagger-gradle-codegen
swarm
sweden
swing
swiss-user-group
switzerland
talking-kotlin
tallinn
tampa
teamcity
tegal
tempe
tensorflow
terminal
test
testing
testtestest
texas
tgbotapi
thailand
tornadofx
touchlab-tools
training
tricity-kotlin-user-group
trójmiasto
truth
tunisia
turkey
turkiye
twitter-feed
uae
udacityindia
uk
ukrainian
uniflow
unkonf
uruguay
utah
uuid
vancouver
vankotlin
vertx
videos
vienna
vietnam
vim
vkug
vuejs
web-mpp
webassembly
webrtc
wimix_sentry
wwdc
zircon
Powered by Linen
arrow
  • i

    ivanmorgillo

    11/19/2021, 4:58 PM
    Hi all, I'm trying to introduce Optics to an existing Android project [...]
    l
    s
    t
    • 4
    • 12
  • s

    Satyam Agarwal

    11/20/2021, 3:56 PM
    Hei @simon.vergauwen ! Long post, sorry for that. So a few days ago I had to suffer a little embarrassment when a colleague pointed out the obvious mistake in the helper api i built to do database operations functionally. 🙈😅🤣 here is the code :
    typealias ErrorOr<A> = Either<Throwable, A>
    
    suspend inline fun <reified A> Db.useTxn(noinline f: suspend (Handle) -> ErrorOr<A>): ErrorOr<A> = withContext(IO) {
            Either
                .catch { this@useTxn.open().begin() }
                .flatMap { handle -> bracketCase(acquire = { handle }, use = f, release = { h, e -> h.closeTxn(e) }) }
    }
    
    suspend fun Handle.closeTxn(e: ExitCase): ErrorOr<Unit> {
        return Either.catch {
            guarantee(
                {
                    when (e) {
                        is ExitCase.Completed -> this.commit().close()
                        is ExitCase.Cancelled -> this.rollback().close()
                        is ExitCase.Failure -> this.rollback().close()
                    }
                },
                { this.close() }
            )
        }
    }
    Problem with this code is that it will never come to ExitCase.Failure as arrow-kt checks on what exception is thrown and then handles result :
    val res = try {
      use(acquired)
    } catch (e: CancellationException) {
      runReleaseAndRethrow(e) { release(acquired, ExitCase.Cancelled(e)) }
    } catch (t: Throwable) {
      runReleaseAndRethrow(t.nonFatalOrThrow()) { release(acquired, ExitCase.Failure(t.nonFatalOrThrow())) }
    }
    We changed from
    bracketCase
    to
    Resource
    with throwing exception inside use , but to mitigate the above flaw, with
    bracketCase
    it will roughly look like this :
    suspend inline fun <reified A> Db.useTxn(noinline f: suspend (Handle) -> ErrorOr<A>): ErrorOr<A> = withContext(IO) {
        Either
            .catch { this@useTxn.open().begin() }
            .flatMap { handle ->
                Either.catch {
                    bracketCase(
                        acquire = { handle },
                        use = { h -> f(h).fold({ error -> throw error }, ::identity) },
                        release = { h, e -> h.closeConn(e) }
                    )
                }
            }
    }
    This problem occured when I migrated from
    IO<A>
    to suspend () -> Either<Throwable, A> We have fixed in our code base like this, but *It would have been awesome we got Either based apis for bracketCase and Resource. * Just wanted to highlight how can we easily mess up things 😄 🙈
    👍 1
    p
    s
    • 3
    • 18
  • s

    SecretX

    11/20/2021, 8:54 PM
    What is the most idiomatic way of flattening a
    Option<Pair<A, Option<B>>>
    to
    Option<Pair<A, B>>
    using arrow? This is the code were I want to apply that
    fun playerDisconnect(player: Player) {
        activeDungeons.remove(player.uniqueId) // returns a String?
            ?.let { dungeonRepo.getDungeon(it) } // returns an Option<Dungeon>
            ?.tap {
                dungeonRepo.getLastLevel(it)  // I need to somehow zip the "Dungeon" with this Option<Level> (returned by the getLastLevel), and use both, or none of the two, if there's no last level
                // filter the result using levelSpawnsManager#isLevelComplete, passing the Level I just got as argument
                // then run these methods after
                levelSpawnsManager.cancelDungeonSpawns(dungeon)
                levelSpawnsManager.resetCompletedLevels(dungeon)
                player.runLogoffCommands(dungeon)
            }
    }
    s
    p
    • 3
    • 3
  • s

    Stewart Stewart

    11/21/2021, 9:24 PM
    Does Arrow provide support for partial functions? (Not partially-_applied_/curried functions) eg., in
    eitherAB.handleError
    I might want to handle
    A
    with a
    B
    under certain conditions or for certain subtypes of
    A
    . instead, I’d have to
    handleErrorWith
    and have a catch-all case re-wrapping in Left.
    • 1
    • 2
  • a

    Alvaro Blazquez checa

    11/23/2021, 9:09 AM
    Hi guys I need to migrate this to arrow 1.0:
    Validated.applicative(validationSemigroup).tupled(Valid("foo"), Valid("bar")).fix()
    s
    • 2
    • 13
  • m

    Marko Novakovic

    11/23/2021, 1:37 PM
    either
    block offers nice syntax but it’s `suspend`ed. is there non-`suspend`ed version or I have to use
    flatMap
    and
    map
    ?
    t
    • 2
    • 2
  • i

    Ivan Lorenz

    11/23/2021, 4:57 PM
    Hi all, I am having a hard time trying to switch my OOP testing style using mocks to FP with extension functions and receivers as implicit dependencies. Using @raulraja gist https://gist.github.com/raulraja/e82e352c10f7e158758ff48aca733d3c let’s say we want to implement a different behaviour in a testing scope for
    fun RedisConnection.saveRedisSession(session: Session): Save<Unit>
    How can we achieve that? I understand that this is a impossible approach because extension functions are resolved statically. Then, how to mock o test double them? Or the real problem is we should not need to mock functions used by other functions? Then what to test? 😄 Sorry for the mess but switching paradigms is a tough brain task. Thank you very much in advance.
    p
    • 2
    • 46
  • i

    ipolyzos

    11/23/2021, 4:59 PM
    hey yo all (not sure if this is the best channel) - but newcomer here in the kotlin community and i was wondering if there is anything similar to akka streams, fs2 and zio-streams from Scala for handling data streams and combine them with tools like pulsar and kafka
    p
    s
    • 3
    • 5
  • m

    Milse113

    11/25/2021, 9:14 PM
    How do I make a type that can only contain strings matching a certain regex using Arrow Analysis?
    a
    • 2
    • 4
  • j

    jean

    11/26/2021, 7:52 AM
    fun fetchById(id: String?) = Either.catch(::onApiError) {
        id ?: return Either.Left(InOrderError.ApiError)
        ...
    }
    is there an nicer way to guard the nullability of Id in this case? I found
    left()
    but it doesn’t let me pass a type of error
    s
    • 2
    • 4
  • s

    Shalom Halbert

    11/27/2021, 6:09 PM
    Is the formatting corrupted? Source For example:
    <ul><li>Parse a string into an integer</li><li>Calculate the reciprocal</li><li>Convert the reciprocal into a string</li></ul>
    s
    r
    • 3
    • 4
  • s

    Shalom Halbert

    11/27/2021, 10:25 PM
    Does anyone have suggestions for efficiently asserting that an
    Either<Exception, Any>
    with
    left
    equal to a caught
    Exception
    is equal to an expected value?
    s
    • 2
    • 9
  • s

    Shalom Halbert

    11/28/2021, 3:55 AM
    That yields the following solution the the example above
    fun doSomething() = IllegalAccessException("message").left()
    
        @Test
        fun sample() {
            doSomething().shouldBeLeftThrowableWithMessage<IllegalAccessException>("message")
        }
    s
    s
    i
    • 4
    • 15
  • d

    dnowak

    11/29/2021, 12:34 AM
    Hi, I’ve tried my best to convert examples from the book “Domain Modeling Made Functional Tackle Software Complexity with Domain-Driven Design and F#” to Kotlin based on Arrow. The result is here: https://github.com/dnowak/domain-modeling-made-functional-in-kotlin I would be grateful for any hints on making the code more idiomatic regarding FP & Arrow.
    :arrow: 6
    😮 1
    ❤️ 2
    s
    s
    • 3
    • 3
  • g

    Gemy

    11/29/2021, 11:32 AM
    Hello guys 👋 I'm I the only one having this issue with the Docs? I can't see the code snippets. I thought the problem was on my machine so I used a VPN and still can't see the snippets 😕
    t
    s
    • 3
    • 13
  • t

    Ties

    12/01/2021, 9:33 AM
    I also gave a talk about arrow at kotlin dev days amsterdam last week, it is about the either monad and some basic optics if anyone finds this useful 🙂

    https://www.youtube.com/watch?v=Wojgv2MeMGU▾

    🙌🏼 1
    👏🏼 1
    👏 1
    👍 1
    👀 2
    🙌 4
    i
    s
    p
    • 4
    • 19
  • f

    Filip Piechowski

    12/02/2021, 12:18 PM
    Hello @raulraja are there any updates on what’s the future of HKT and the status of compiler plugins?
    r
    • 2
    • 1
  • p

    Philipp Mayer

    12/03/2021, 11:00 AM
    Hi there, I want to migrate a gradle project to Kotlin 1.6. The project makes use of the optics dsl, which uses kapt, which does not support 1.6(?). My question is: Can I replace the kapt part somehow with ksp? I’m not that familiar with it (we only have kapt for the optics dsl in the project) and couldn’t find any hint in the docs. Any thoughts on this? Thanks in advance!
    s
    t
    j
    • 4
    • 12
  • s

    Stewart Stewart

    12/03/2021, 9:46 PM
    Is there a built-in variant of Either/Validated
    catch
    that only handles specific exceptions and throws the rest?
    t
    g
    • 3
    • 3
  • e

    Emil Kantis

    12/03/2021, 10:03 PM
    I feel stupid.. is there no way to do
    Either.leftOrNull()
    ? For instance if I have a
    List<Either<A,B>>
    and want to map that into a
    List<A>
    ?
    s
    i
    • 3
    • 5
  • t

    thanh

    12/04/2021, 2:14 PM
    also it seems the docs here
    <https://github.com/arrow-kt/arrow/blob/main/CONTRIBUTING.md#steps>
    are outdated.
    cd arrow-libs/core
    ./gradlew build
    doesn't work any more
    s
    s
    • 3
    • 14
  • p

    pakoito

    12/06/2021, 11:43 AM
    If I were to introduce Optics into an existing project today, would it be through kapt, ksp, or a compiler plugin?
    s
    • 2
    • 3
  • i

    ipolyzos

    12/06/2021, 2:35 PM
    are there any good github repos with code samples or any talks specifically on arrow fx?
    s
    p
    i
    • 4
    • 14
  • d

    Daniel Berg

    12/07/2021, 2:00 AM
    Hi folks, is there support to create custom instances of Monads? Is that done using the meta package?
    s
    r
    • 3
    • 11
  • t

    than_

    12/07/2021, 2:30 PM
    Hi, playing with Schedule and I'm trying to create a schedule that waits 15 minutes, performs some task returning Boolean and if false repeats (wait's 15 minutes, performs some task ...).
    Schedule.identity<Boolean>().delay { Duration.minutes(15) }.whileOutput(::identity)
    Unfortunately this executes instantly. Is there a way to create this scheduler (other that putting kotlinx.coroutines.delay in the repeat function)?
    s
    • 2
    • 3
  • s

    simon.vergauwen

    12/07/2021, 3:03 PM
    https://twitter.com/vergauwen_simon/status/1468234383412891649?s=20 Shameless… 😬
    👍🏼 1
    👏 12
    😍 11
    👍 3
    :kotlin-intensifies: 8
    t
    i
    • 3
    • 14
  • i

    ibcoleman

    12/07/2021, 8:41 PM
    Hi All! Did arrow 1.0 eliminate Tuple3 for some reason or am I doing something wrong? Can’t resolve that, though Tuple4 through Tuple22 resolve just fine.
    s
    • 2
    • 1
  • v

    Vitali Plagov

    12/09/2021, 2:39 PM
    Hi all! Could you please help me with using Optics? I’m trying to solve the issue with deep copy of data class. My
    build.gradle
    has this:
    plugins {
        id "org.jetbrains.kotlin.kapt" version "1.6.0"
    }
    dependencies {
        implementation "io.arrow-kt:arrow-core:1.0.1"
        implementation "io.arrow-kt:arrow-optics:1.0.1"
        kapt "io.arrow-kt:arrow-meta:1.0.1"
    }
    Then, all data classes are annotated with
    @optics
    and have a companion object
    // showing a simple data class for brevity reasons
    @optics
    data class Mapping(
        val type: MappingType,
        val values: List<String>
    ) {
        companion object
    }
    Next, in my class when I’m trying to do this:
    val updatedMapping = Mapping.
    no fields (
    type
    or
    values
    ) are shown after
    .
    Am I missing something?
    s
    t
    • 3
    • 11
  • s

    simon.vergauwen

    12/15/2021, 9:36 AM
    Not sure if it’s been shared here, but me and @Alejandro Serrano Mena are talking tonight on a Webinar about Ktor with Arrow. https://blog.jetbrains.com/kotlin/2021/12/server-side-with-kotlin-webinar-series-vol-4/
    🙌🏼 1
    💯 2
    👍🏼 1
    👍 6
    :arrow: 6
    🙌 11
    s
    m
    • 3
    • 3
  • s

    Shalom Halbert

    12/15/2021, 12:11 PM
    Are there any common practices for making code that uses Arrow easier to read? Maybe some linter rules? This would be for improving the dev experience for devs who aren't accustomed to Arrow, or similar frameworks.
    t
    • 2
    • 4
Powered by Linen
Title
s

Shalom Halbert

12/15/2021, 12:11 PM
Are there any common practices for making code that uses Arrow easier to read? Maybe some linter rules? This would be for improving the dev experience for devs who aren't accustomed to Arrow, or similar frameworks.
t

tavish pegram

12/15/2021, 6:29 PM
I’ve had this discussion with my team recently and we are converging on a particular style. I can share some of the discussion and code examples if that is helpful (no linter though so its all convention). I also would appreciate feedback!
Tried to refactor this in a way that

Respects a consistent level of abstraction in each function
Keeps the "top-level" abstraction declarative and for the most part hiding the sad path (though I did leave in a single mapErrors fn in each call
Hides the "glue" or "adapter" functions that make all the different types fit together.
I'm currently wrestling with the idea that

Arrow and FP is good and provides super generic good tools like Either, map, flatMap, etc. that we can use to implement pretty much anything in a Good Way.
Those same tools are "low level" and distracting when reading the code
So what I'm messing around with is trying to keep the main bits of behavior in each file/class at a high level of abstraction (of course, what "high-level abstraction" means depends on the context. In this example its high level to talk about HTTP responses and JSON. In a Payment service, that would be considered low level). We do this by adding a bunch of private extension functions that hide the "glue" which is normally needed to fit all these different types together while giving them expressive and clear names (approaching a DSL, yay!), and keeping the functions small enough that they are easy to update and reason about in isolation (hopefully, its what I was going for).

Another way of thinking about it is that we are taking these great super generic lego pieces and fitting them together into larger (though still modular) "solutions" that we paint with concrete function names before finally composing those concrete pieces together at the "top"
Before
class AffirmClient(
    private val httpClient: HttpClient,
    // @Value("\${affirm.au.private_key}")
    private val affirmAuPrivateKey: String,
    // @Value("\${affirm.au.public_key}")
    private val affirmAuPublicKey: String,
    // @Value("\${affirm.au.hostname}")
    private val affirmAuApiUrl: String,
) {
    private val logger = KotlinLogging.logger { }

    suspend fun authorizeTransaction(
        partnerPaymentMethodId: String,
        metadata: Metadata,
    ): Either<AuthedError, AuthorizeTransactionResponse> =
        Either.catch {
            httpClient.postJson(
                url = "${affirmAuApiUrl}api/v1/transactions",
                request = AuthorizeTransactionRequest(
                    transactionId = partnerPaymentMethodId,
                    orderId = metadata.orderId,
                ),
                auth = getAuthHeader(),
            )
        }.mapLeft {
            AuthedError.AuthFailureError(it.message)
        }.flatMap {
            <http://logger.info|logger.info> { "AffirmClient.authorizeTransaction response: ${it.body}" }

            if (it.code == 200) {
                AuthorizeTransactionResponse.fromHTTPBody(it.body).right()
            } else {
                AuthedError.AuthFailureError(message = it.body.optString("message").toString()).left()
            }
        }

    suspend fun captureTransaction(
        authorizationToken: String
    ): Either<CapturedError, CaptureTransactionResponse> =
        Either.catch {
            httpClient.postJson(
                url = "${affirmAuApiUrl}api/v1/transactions/$authorizationToken/capture",
                auth = getAuthHeader(),
            )
        }.mapLeft {
            CapturedError.CaptureActionError(it.message)
        }.flatMap {
            <http://logger.info|logger.info> { "AffirmClient.captureTransaction response: ${it.body}" }

            if (it.code == 200) {
                CaptureTransactionResponse.fromHTTPBody(it.body).right()
            } else {
                CapturedError.CaptureActionError(
                    message = it.body.optString("message").toString()
                ).left()
            }
        }

    suspend fun refundTransaction(
        confirmationId: String,
        amount: Int,
    ): Either<RefundError, RefundTransactionResponse> =
        Either.catch {
            httpClient.postJson(
                url = "${affirmAuApiUrl}api/v1/transactions/$confirmationId/refund",
                request = RefundTransactionRequest(amount = amount),
                auth = getAuthHeader(),
            )
        }.mapLeft {
            RefundError.RefundFailureError(it.message)
        }.flatMap {
            <http://logger.info|logger.info> { "AffirmClient.refundTransaction response: ${it.body}" }

            if (it.code == 200) {
                RefundTransactionResponse.fromHTTPBody(it.body).right()
            } else {
                RefundError.RefundFailureError(
                    message = it.body.optString("message").toString()
                ).left()
            }
        }

    suspend fun voidTransaction(
        confirmationId: String
    ): Either<VoidError, Unit> =
        Either.catch {
            httpClient.postJson(
                url = "${affirmAuApiUrl}api/v1/transactions/$confirmationId/void",
                auth = getAuthHeader(),
            )
        }.mapLeft {
            VoidError.VoidFailureError(it.message)
        }.flatMap {
            <http://logger.info|logger.info> { "AffirmClient.voidTransaction response: ${it.body}" }

            if (it.code == 200) {
                Unit.right()
            } else {
                VoidError.VoidFailureError(
                    message = it.body.optString("message").toString()
                ).left()
            }
        }

    private fun getAuthHeader(): HttpHeader =
        HttpHeader(key = affirmAuPublicKey, value = affirmAuPrivateKey)
}
After
class AffirmClient(
    private val httpClient: HttpClient,
    private val affirmAuPrivateKey: String,
    private val affirmAuPublicKey: String,
    private val affirmAuApiUrl: String,
) {
    @Loggable
    suspend fun authorizeTransaction(
        partnerPaymentMethodId: String,
        metadata: Metadata,
    ): Either<AuthedError, AuthorizeTransactionResponse> =
        <http://httpClient.post|httpClient.post>(
            url = "${affirmAuApiUrl}api/v1/transactions",
            request = AuthorizeTransactionRequest(
                transactionId = partnerPaymentMethodId,
                orderId = metadata.orderId,
            ),
            auth = getAuthHeader(),
        )
            .mapAuthErrors()
            .parseAuthorizeResponse()

    @Loggable
    suspend fun captureTransaction(
        authorizationToken: String
    ): Either<CapturedError, CaptureTransactionResponse> =
        <http://httpClient.post|httpClient.post>(
            url = "${affirmAuApiUrl}api/v1/transactions/$authorizationToken/capture",
            auth = getAuthHeader(),
        )
            .mapCaptureErrors()
            .parseCaptureResponse()

    @Loggable
    suspend fun refundTransaction(
        confirmationId: String,
        amount: Int,
    ): Either<RefundError, RefundTransactionResponse> =
        <http://httpClient.post|httpClient.post>(
            url = "${affirmAuApiUrl}api/v1/transactions/$confirmationId/refund",
            request = RefundTransactionRequest(amount = amount),
            auth = getAuthHeader(),
        )
            .mapRefundErrors()
            .parseRefundResponse()

    @Loggable
    suspend fun voidTransaction(
        confirmationId: String
    ): Either<VoidError, Unit> =
        <http://httpClient.post|httpClient.post>(
            url = "${affirmAuApiUrl}api/v1/transactions/$confirmationId/void",
            auth = getAuthHeader(),
        )
            .mapVoidErrors()
            .parseVoidResponse()

    private fun getAuthHeader(): HttpHeader =
        HttpHeader(key = affirmAuPublicKey, value = affirmAuPrivateKey)
}

@Loggable
private fun <http://HttpClient.post|HttpClient.post>(
    url: String,
    request: HttpRequest? = null,
    auth: HttpHeader? = null,
): Either<Throwable, HttpResponse> =
    Either.catch {
        this.postJson(
            url = url,
            request = request,
            auth = auth,
        )
    }

private fun <B> Either<Throwable, B>.mapAuthErrors() =
    this.mapLeft { AuthedError.AuthFailureError(it.message) }

private fun Either<AuthedError, HttpResponse>.parseAuthorizeResponse() = this.flatMap {
    when (it.code == 200) {
        true ->
            AuthorizeTransactionResponse
                .fromHTTPBody(it.body)
                .right()
        false -> AuthedError.AuthFailureError(
            message = it.body.optString("message").toString()
        ).left()
    }
}

private fun <B> Either<Throwable, B>.mapCaptureErrors() =
    this.mapLeft { CapturedError.CaptureActionError(it.message) }

private fun Either<CapturedError, HttpResponse>.parseCaptureResponse() = this.flatMap {
    when (it.code == 200) {
        true ->
            CaptureTransactionResponse
                .fromHTTPBody(it.body)
                .right()
        false -> CapturedError.CaptureActionError(
            message = it.body.optString("message").toString()
        ).left()
    }
}

private fun <B> Either<Throwable, B>.mapRefundErrors() =
    this.mapLeft { RefundError.RefundFailureError(it.message) }

private fun Either<RefundError, HttpResponse>.parseRefundResponse() = this.flatMap {
    when (it.code == 200) {
        true ->
            RefundTransactionResponse
                .fromHTTPBody(it.body)
                .right()
        false -> RefundError.RefundFailureError(
            message = it.body.optString("message").toString()
        ).left()
    }
}

private fun <B> Either<Throwable, B>.mapVoidErrors() =
    this.mapLeft { VoidError.VoidFailureError(it.message) }

private fun Either<VoidError, HttpResponse>.parseVoidResponse() = this.flatMap {
    when (it.code == 200) {
        true -> Unit.right()
        false -> VoidError.VoidFailureError(
            message = it.body.optString("message").toString()
        ).left()
    }
}
s

Shalom Halbert

12/16/2021, 9:50 PM
I can’t discern if that approach scales well or not. It’s definitely a good option.
View count: 3