Skip to content

Instantly share code, notes, and snippets.

@oharaandrew314
Last active March 16, 2022 02:02
Show Gist options
  • Save oharaandrew314/90e79df414eb55aa4a5b6168831eda34 to your computer and use it in GitHub Desktop.
Save oharaandrew314/90e79df414eb55aa4a5b6168831eda34 to your computer and use it in GitHub Desktop.
hexagonal-clients-original
class CatUi(private val cats: ClientV1) {
fun renderCatHtml(id: Int): String {
val cat = cats[id] ?: return "<h1>Cat $id not found</h1>"
val isBrown = if (cat.brown) "Yes" else "No"
val isGrey = if (cat.grey) "Yes" else "No"
val latestAppointment = cat.appointments.maxOrNull()
return """
<html><body>
<h1>${cat.name}</h1>
<h2>Owner: ${cat.ownerId}</h2>
<b>Is Brown:</b> $isBrown<br/>
<b>Is Grey:</b> $isGrey<br/>
<b>Breed:</b> ${cat.breed}<br/>
<b>Latest Appointment:</b> $latestAppointment<br/>
</body></html>
"""
}
}
fun main() {
val client = ClientV1("http://catdocs.com")
val ui = CatUi(client)
println(ui.renderCatHtml(123))
}
data class Cat(
val id: Int,
val name: String,
val ownerId: Int,
val ownerName: String,
val brown: Boolean,
val grey: Boolean,
val breed: Breed?,
val appointments: List<Instant>
)
enum class Breed { persian, american_short_hair, maine_coon }
class ClientV1(host: String) {
private val backend = ClientFilters.SetHostFrom(Uri.of(host))
.then(JavaHttpClient())
operator fun get(id: Int): Cat? {
val request = Request(Method.GET, "api/cats?cat_id=$id")
val response = backend(request)
if (!response.status.successful) throw IOException("Error getting cat: $response")
val body = response.bodyString()
if (body.isEmpty()) return null
val props = Properties()
body.reader().use { reader ->
props.load(reader)
}
return Cat(
id = id,
name = props.getProperty("name"),
ownerId = props.getProperty("owner_id").toInt(),
ownerName = props.getProperty("owner_name"),
brown = props.getProperty("brown") == "1",
grey = props.getProperty("grey") == "1",
breed = Breed.valueOf(props.getProperty("breed")),
appointments = props.getProperty("appointments")
.split(",")
.map { Instant.ofEpochSecond(it.toLong()) }
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment