This repository has been archived by the owner on Nov 7, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathPostgrestHttpClientApache.kt
65 lines (53 loc) · 2.54 KB
/
PostgrestHttpClientApache.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package io.supabase.postgrest.http
import io.supabase.postgrest.json.PostgrestJsonConverter
import org.apache.hc.client5.http.classic.methods.HttpUriRequestBase
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient
import org.apache.hc.core5.http.ClassicHttpResponse
import org.apache.hc.core5.http.HttpStatus
import org.apache.hc.core5.http.Method
import org.apache.hc.core5.http.io.HttpClientResponseHandler
import org.apache.hc.core5.http.io.entity.EntityUtils
import org.apache.hc.core5.http.io.entity.StringEntity
import java.net.URI
/**
* Default implementation of the [PostgrestHttpClient] used by the PostgrestDefaultClient.
*
* Uses closable apache HTTP-Client 5.x.
*/
class PostgrestHttpClientApache(
private val httpClient: () -> CloseableHttpClient,
private val jsonConverter: PostgrestJsonConverter
) : PostgrestHttpClient {
override fun execute(uri: URI, method: Method, headers: Map<String, String>, body: Any?): PostgrestHttpResponse {
return httpClient().use { httpClient ->
val httpRequest = HttpUriRequestBase(method.name, uri)
body?.apply {
val dataAsString = jsonConverter.serialize(body)
httpRequest.entity = StringEntity(dataAsString)
}
headers.forEach { (name, value) -> httpRequest.addHeader(name, value) }
return@use httpClient.execute(httpRequest, responseHandler(headers))
}
}
private fun responseHandler(requestHeaders: Map<String, String>): HttpClientResponseHandler<PostgrestHttpResponse> {
return HttpClientResponseHandler<PostgrestHttpResponse> { response ->
throwIfError(response)
val body = response.entity?.let { EntityUtils.toString(it) }
val responseHeaders = response.headers.map { it.name to it.value }.toMap()
val count = extractCount(responseHeaders, requestHeaders)
return@HttpClientResponseHandler PostgrestHttpResponse(
status = response.code,
body = body,
count = count
)
}
}
private fun throwIfError(response: ClassicHttpResponse) {
val status = response.code
val statusSuccessful = status >= HttpStatus.SC_SUCCESS && status < HttpStatus.SC_REDIRECTION
if (!statusSuccessful) {
val entityAsString = response.entity?.let { EntityUtils.toString(it) }
throw PostgrestHttpException(status, entityAsString)
}
}
}