11package lmirabal.bank.http
22
3+ import dev.forkhandles.result4k.Failure
4+ import dev.forkhandles.result4k.Result
5+ import dev.forkhandles.result4k.Success
36import lmirabal.bank.Bank
47import lmirabal.bank.model.Amount
58import lmirabal.bank.model.BankAccount
69import lmirabal.bank.model.BankAccountId
10+ import lmirabal.bank.model.NotEnoughFunds
711import org.http4k.core.HttpHandler
812import org.http4k.core.Method.GET
913import org.http4k.core.Method.POST
1014import org.http4k.core.Request
15+ import org.http4k.core.Response
16+ import org.http4k.core.Status
1117import org.http4k.core.with
1218
1319class BankHttpClient (val http : HttpHandler ) : Bank {
@@ -22,18 +28,23 @@ class BankHttpClient(val http: HttpHandler) : Bank {
2228 }
2329
2430 override fun deposit (id : BankAccountId , amount : Amount ): BankAccount {
25- return changeBalanceAction(BANK_ACCOUNT_DEPOSIT_PATH , id, amount)
31+ val response = changeBalanceAction(BANK_ACCOUNT_DEPOSIT_PATH , id, amount)
32+ return bankAccountLens(response)
2633 }
2734
28- override fun withdraw (id : BankAccountId , amount : Amount ): BankAccount {
29- return changeBalanceAction(BANK_ACCOUNT_WITHDRAWAL_PATH , id, amount)
35+ override fun withdraw (id : BankAccountId , amount : Amount ): Result <BankAccount , NotEnoughFunds > {
36+ val response = changeBalanceAction(BANK_ACCOUNT_WITHDRAWAL_PATH , id, amount)
37+ return when (response.status) {
38+ Status .OK -> Success (bankAccountLens(response))
39+ Status .BAD_REQUEST -> Failure (notEnoughFundsLens(response))
40+ else -> throw Exception (" Not expected: $response " )
41+ }
3042 }
3143
32- private fun changeBalanceAction (actionPath : String , id : BankAccountId , amount : Amount ): BankAccount {
33- val response = http(
44+ private fun changeBalanceAction (actionPath : String , id : BankAccountId , amount : Amount ): Response {
45+ return http(
3446 Request (POST , BANK_ACCOUNTS_BASE_URL + actionPath)
3547 .with (accountIdLens of id, amountLens of amount)
3648 )
37- return bankAccountLens(response)
3849 }
3950}
0 commit comments