Last active
May 25, 2024 10:18
-
-
Save dacr/dbfc8d455da5b33b0cb33c5ac981de0d to your computer and use it in GitHub Desktop.
ZIO live session - Writing a more complex application / published by https://github.com/dacr/code-examples-manager #fb874ad4-4adc-489a-95ba-5c16198a8782/d93879241261ea16476233b5fce3487f704ec5d1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// summary : ZIO live session - Writing a more complex application | |
// keywords : scala, zio, live, demo, pure-functional, @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 : fb874ad4-4adc-489a-95ba-5c16198a8782 | |
// created-on : 2021-09-26T16:27:18+02:00 | |
// managed-by : https://github.com/dacr/code-examples-manager | |
// run-with : scala-cli $file | |
// --------------------- | |
//> using scala "3.4.2" | |
//> using dep "dev.zio::zio:2.0.13" | |
//> using dep "com.softwaremill.sttp.client3::async-http-client-backend-zio:3.8.15" | |
//> using dep "com.softwaremill.sttp.client3::zio-json:3.8.15" | |
//> using dep "fr.janalyse::zio-worksheet:2.0.13.0" | |
//> using dep "org.slf4j:slf4j-simple:2.0.7" | |
// --------------------- | |
import zio.* | |
import zio.json.* | |
import zio.worksheet.* | |
import sttp.client3.ziojson.* | |
import sttp.client3.* | |
import sttp.client3.asynchttpclient.zio.* | |
case class ClientInfo(clientIP: String, userAgent: String) | |
object ClientInfo: | |
implicit val codec: JsonCodec[ClientInfo] = DeriveJsonCodec.gen | |
// ----------------------------------------------------------------------------------------- | |
val app = | |
for | |
_ <- ZIO.log("Application starts") | |
backend <- ZIO.service[SttpBackend[Task, Any]] | |
response <- backend.send(basicRequest.get(uri"https://mapland.fr/clientInfo").response(asJson[ClientInfo])) | |
clientInfo <- ZIO.from(response.body) | |
_ <- ZIO.log(s"my ip is ${clientInfo.clientIP}") | |
_ <- ZIO.log("Application ends") | |
yield clientInfo | |
app.provideLayer(AsyncHttpClientZioBackend.layer()).unsafeRun | |
// ----------------------------------------------------------------------------------------- | |
val stub = | |
AsyncHttpClientZioBackend.stub | |
.whenRequestMatches(_.uri.toString() == "https://mapland.fr/clientInfo") | |
.thenRespond("""{"clientIP":"127.0.0.1","userAgent":"curl/42"}""") | |
app.provideLayer(ZLayer.succeed(stub)).unsafeRun |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment