Skip to content

Instantly share code, notes, and snippets.

@dacr
Last active October 8, 2023 08:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dacr/a0eeaca15ade6dd6e9a0615df040ffdc to your computer and use it in GitHub Desktop.
Save dacr/a0eeaca15ade6dd6e9a0615df040ffdc to your computer and use it in GitHub Desktop.
ZIO learning - playing with sttp async http client and zio json / published by https://github.com/dacr/code-examples-manager #a8985bb9-774a-4ac5-8452-4f0ad58709d0/615049928d3667a60cc7404630ebaba73968559e
// summary : ZIO learning - playing with sttp async http client and zio json
// keywords : scala, zio, learning, json, pure-functional, async, sttp, @testable
// publish : gist
// authors : David Crosson
// license : Apache NON-AI License Version 2.0 (https://raw.githubusercontent.com/non-ai-licenses/non-ai-licenses/main/NON-AI-APACHE2)
// id : a8985bb9-774a-4ac5-8452-4f0ad58709d0
// created-on : 2021-04-18T20:55:55Z
// managed-by : https://github.com/dacr/code-examples-manager
// run-with : scala-cli $file
// ---------------------
//> using scala "3.3.1"
//> using dep "dev.zio::zio:2.0.13"
//> using dep "fr.janalyse::zio-worksheet:2.0.13.0"
//> using dep "com.softwaremill.sttp.client4::async-http-client-backend-zio:4.0.0-M5"
//> using dep "com.softwaremill.sttp.client4::zio-json:4.0.0-M5"
//> using dep "org.slf4j:slf4j-nop:2.0.7"
// ---------------------
import zio.*
import zio.worksheet.*
import zio.json.*
import sttp.client4.*
import sttp.client4.asynchttpclient.zio.*
import sttp.client4.testing.SttpBackendStub
import sttp.client4.ziojson.*
case class ClientInfo(
clientIP: String,
userAgent: String
) derives JsonCodec
def run(): Unit = {
// -------------------------------------------------------------
// THE APPLICATION LOGIC
val logic = for {
backend <- ZIO.service[SttpBackend[Task, Any]]
request = basicRequest.get(uri"https://mapland.fr/clientInfo").response(asJson[ClientInfo])
response <- backend.send(request)
clientInfo <- ZIO.from(response.body)
_ <- Console.printLine(clientInfo.userAgent)
_ <- Console.printLine(clientInfo.toJsonPretty)
} yield ()
// -------------------------------------------------------------
// EXECUTED USING REAL STTP ENVIRONNEMENT
{
val httpClientLayer = AsyncHttpClientZioBackend.layer()
logic.provide(httpClientLayer).unsafeRun
}
// -------------------------------------------------------------
// EXECUTED USING STUBBED STTP ENVIRONNEMENT
{
val stub =
AsyncHttpClientZioBackend.stub
.whenRequestMatches(_.uri.toString() == "https://mapland.fr/clientInfo")
.thenRespond("""{"clientIP":"127.0.0.1","userAgent":"curl/42"}""")
val stubbedLogic = logic.provide(ZLayer.succeed(stub))
stubbedLogic.unsafeRun
}
}
run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment