/
ProfileGateway.kt
51 lines (42 loc) · 1.63 KB
/
ProfileGateway.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package adapters
import com.fasterxml.jackson.databind.ObjectMapper
import domain.model.Profile
import domain.model.toEmail
import java.net.URI
import java.net.http.HttpClient.newHttpClient
import java.net.http.HttpRequest
import java.net.http.HttpRequest.BodyPublishers.ofString
import java.net.http.HttpResponse.BodyHandlers.discarding
import java.net.http.HttpResponse.BodyHandlers.ofString
class ProfileGateway(private val apiUrl: String) {
private val objectMapper = ObjectMapper()
private val newHttpClient = newHttpClient()
fun fetchProfile(id: String): Profile {
val httpRequest = HttpRequest.newBuilder()
.uri(URI.create("$apiUrl/profile/$id"))
.GET()
return newHttpClient.send(httpRequest.build(), ofString()).run {
check(statusCode() == 200)
body().toProfile()
}
}
private fun String.toProfile() =
objectMapper.readTree(this).let {
Profile(
id = it.get("id").textValue(),
email = it.get("email").textValue().toEmail()
)
}
fun saveProfile(profile: Profile) {
val httpRequest = HttpRequest.newBuilder()
.uri(URI.create("$apiUrl/profile"))
.header("Content-type", "application/json")
.POST(ofString(objectMapper.writeValueAsString(profile.toProfileRepresenter())))
val response = newHttpClient.send(httpRequest.build(), discarding())
check(response.statusCode() == 201) { "status is not 200 OK" }
}
private fun Profile.toProfileRepresenter() = mapOf(
"email" to email.value,
"id" to id,
)
}