@@ -2,20 +2,24 @@ package client
22
33import arrow.core.Either
44import arrow.core.left
5+ import arrow.core.raise.Raise
56import arrow.core.right
7+ import bind
68import co.touchlab.kermit.Logger
9+ import ensure
710import io.ktor.client.call.body
811import io.ktor.client.request.HttpRequestBuilder
912import io.ktor.client.request.get
1013import io.ktor.client.request.parameter
1114import io.ktor.client.statement.HttpResponse
1215import io.ktor.http.encodedPath
16+ import io.ktor.http.isSuccess
1317import io.ktor.http.takeFrom
1418import models.CardDto
1519import models.ListResp
1620import models.SetDto
1721
18- interface ScryfallApi {
22+ interface ScryfallApi : AutoCloseable {
1923 suspend fun cardNamed (name : String ): Either <String , CardDto >
2024 suspend fun searchCard (searchParam : String ): Either <String , List <CardDto >>
2125 suspend fun sets (): Either <String , List <SetDto >>
@@ -26,7 +30,12 @@ suspend inline fun <reified T> HttpResponse.toEither(): Either<String, T> = when
2630 else -> this .body<String >().left()
2731}
2832
29- class ScryfallApiImpl : ScryfallApi {
33+ context(_: Raise <Throwable >)
34+ inline fun <T > catch (block : () -> T ): T {
35+ return Either .catch (block).bind()
36+ }
37+
38+ class ScryfallApiImpl : ScryfallApi , AutoCloseable {
3039 private val client = newKtorClient()
3140 override suspend fun cardNamed (name : String ): Either <String , CardDto > {
3241 val response = client.get {
@@ -37,6 +46,25 @@ class ScryfallApiImpl : ScryfallApi {
3746 return response.toEither()
3847 }
3948
49+ // This NEEDS to be called or it will hold up the couroutine scope of suspend fun main
50+ override fun close () {
51+ client.close()
52+ }
53+
54+ context(_: Raise <Throwable >)
55+ suspend fun searchCardRaise (searchParam : String ): List <CardDto > {
56+ return catch {
57+ val response = client.get {
58+ scryfall(" $CardApiBase$Search " )
59+ parameter(" q" , searchParam)
60+ }
61+ ensure(response.status.isSuccess()) {
62+ IllegalStateException (response.body<String >())
63+ }
64+ response.body<ListResp <CardDto >>().data
65+ }
66+ }
67+
4068 override suspend fun searchCard (searchParam : String ): Either <String , List <CardDto >> {
4169 val resp: HttpResponse = client.get {
4270 scryfall(" $CardApiBase$Search " )
0 commit comments