-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
HttpClient.scala
332 lines (273 loc) · 9.96 KB
/
HttpClient.scala
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
package japgolly.webapputil.http
import japgolly.univeq.UnivEq
import japgolly.webapputil.general.{AbstractMultiStringMap, LazyVal}
object HttpClient { outer =>
trait LibraryTypes {
final type Body = outer.Body
final val Body = outer.Body
final val ContentType = outer.ContentType
final type Headers = outer.Headers
final val Headers = outer.Headers
final type Method = outer.Method
final val Method = outer.Method
final type Request = outer.Request
final val Request = outer.Request
final type Response = outer.Response
final val Response = outer.Response
final type ResponseBody = outer.ResponseBody
final val ResponseBody = outer.ResponseBody
final type Status = outer.Status
final val Status = outer.Status
final type UriParams = outer.UriParams
final val UriParams = outer.UriParams
}
type WithEffect[F[_]] = Request => F[Response]
trait HttpClientType[F[_]] {
final type HttpClient = WithEffect[F]
}
trait Module[F[_]] extends HttpClientType[F] with LibraryTypes {
val HttpClient: HttpClient
}
object Module {
def apply[F[_]](f: Request => F[Response]): Module[F] =
new Module[F] {
override val HttpClient = f
}
}
// ===================================================================================================================
object ContentType {
final val Binary = "application/octet-stream"
final val Json = "application/json"
final val JsonUtf8 = "application/json;charset=UTF-8"
final val Form = "application/x-www-form-urlencoded"
def is(contentType: String): String => Boolean = {
val len = contentType.length
c => c.startsWith(contentType) && (
c.length == len // exact match
|| c(len) == ';' // prefix
)
}
val isJson = is(Json)
}
final class Headers(asVector: Vector[(String, String)], isNormalised: Boolean)
extends AbstractMultiStringMap[Headers](asVector, isNormalised) {
override protected def create(asVector: Vector[(String, String)], isNormalised: Boolean = false) =
new Headers(asVector, isNormalised)
def withContentType(value: String) = add("Content-Type", value)
def withContentTypeBinary = withContentType(ContentType.Binary)
def withContentTypeForm = withContentType(ContentType.Form)
def withContentTypeJson = withContentType(ContentType.Json)
def withContentTypeJsonUtf8 = withContentType(ContentType.JsonUtf8)
}
object Headers extends AbstractMultiStringMap.Module[Headers] {
override def fromVector(v: Vector[(String, String)]): Headers =
new Headers(v, isNormalised = false)
}
final class UriParams(asVector: Vector[(String, String)], isNormalised: Boolean)
extends AbstractMultiStringMap[UriParams](asVector, isNormalised) {
override protected def create(asVector: Vector[(String, String)], isNormalised: Boolean = false) =
new UriParams(asVector, isNormalised)
def asString: String =
if (isEmpty)
""
else {
val sb = new java.lang.StringBuilder
var first = true
for (x <- asVector) {
import x.{_1 => k, _2 => v}
if (first)
first = false
else
sb.append('&')
sb.append(UrlEncoder.encode(k))
if (v != null) {
sb.append('=')
sb.append(UrlEncoder.encode(v))
}
}
sb.toString
}
}
object UriParams extends AbstractMultiStringMap.Module[UriParams] {
override def fromVector(v: Vector[(String, String)]): UriParams =
new UriParams(v, isNormalised = false)
def parse(body: String): UriParams =
if ((body == null) || body.isEmpty)
empty
else {
// TODO: Could be more optimised
var ps = empty
val frags = body.split('&')
var frag = null: String
var key = null: String
var value = null: String
var i = 0
var j = 0
while (i < frags.length) {
frag = frags(i)
j = frag.indexOf('=')
if (j >= 0) {
key = UrlEncoder.decode(frag.take(j))
value = UrlEncoder.decode(frag.drop(j + 1))
ps = ps.add(key, value)
} else {
key = UrlEncoder.decode(frag)
ps = ps.add(key, null)
}
i += 1
}
ps
}
}
final case class Method(asString: String)
object Method {
val CONNECT = apply("CONNECT")
val DELETE = apply("DELETE")
val GET = apply("GET")
val HEAD = apply("HEAD")
val OPTIONS = apply("OPTIONS")
val PATCH = apply("PATCH")
val POST = apply("POST")
val PUT = apply("PUT")
val TRACE = apply("TRACE")
}
sealed trait Body {
def isNormalised: Boolean = true
def normalised: Body = this
}
object Body {
def apply(body: String, contentType: String = null): Body =
contentType match {
case ContentType.Form =>
if (body == null)
Form.empty
else
Form(UriParams.parse(body))
case _ =>
val s = if (body == null) "" else body
Str(s, Option(contentType))
}
final case class Form(params: UriParams) extends Body {
def contentType = ContentType.Form
def add (key: String, value: String) = Form(params.add(key, value))
def delete(key: String) = Form(params.delete(key))
def get (key: String) = params.get(key)
override def isNormalised =
params.isNormalised
override def normalised: Form =
if (isNormalised) this else Form(params.normalised)
}
object Form extends AbstractMultiStringMap.Module[Form] {
override def fromVector(v: Vector[(String, String)]): Form =
new Form(UriParams.fromVector(v))
}
final case class Str(content: String, contentType: Option[String]) extends Body {
def isEmpty: Boolean =
content.isEmpty && contentType.isEmpty
def isContentTypeJson = contentType.exists(ContentType.isJson)
def isContentTypeJsonOrEmpty = contentType.forall(ContentType.isJson)
}
val empty: Str =
Str("", None)
val emptyLazy: LazyVal[Str] =
LazyVal.pure(empty)
}
final case class Request(method : Method,
uri : String,
uriParams: UriParams,
headers : Headers,
body : Body,
) {
def isNormalised: Boolean = (
uriParams.isNormalised &&
headers .isNormalised &&
body .isNormalised
)
def normalised: Request =
if (isNormalised) this else normalise
private lazy val normalise: Request =
copy(
uriParams = uriParams.normalised,
headers = headers .normalised,
body = body .normalised,
)
override def hashCode = {
val n = normalised
(
n.method,
n.uri,
n.uriParams,
n.headers,
n.body,
).hashCode
}
override def equals(a: Any) =
a match {
case b: Request =>
val x = normalised
val y = b.normalised
(
x.method == y.method &&
x.uri == y.uri &&
x.uriParams == y.uriParams &&
x.headers == y.headers &&
x.body == y.body
)
case _ => false
}
}
trait RequestCtors[+A] {
def apply(method : Method,
uri : String,
uriParams: UriParams = UriParams.empty,
headers : Headers = Headers.empty,
body : Body = Body.empty,
): A
@inline final def get(uri : String,
uriParams: UriParams = UriParams.empty,
headers : Headers = Headers.empty,
body : Body = Body.empty,
): A =
apply(Method.GET, uri, uriParams, headers, body)
@inline final def post(uri : String,
uriParams: UriParams = UriParams.empty,
headers : Headers = Headers.empty,
body : Body = Body.empty,
): A =
apply(Method.POST, uri, uriParams, headers, body)
}
object Request extends RequestCtors[Request] {
def apply(method : Method,
uri : String,
uriParams: UriParams = UriParams.empty,
headers : Headers = Headers.empty,
body : Body = Body.empty,
): Request =
new Request(method, uri, uriParams, headers, body)
}
final case class Status(code: Int) extends AnyVal {
def is1xx = code >= 100 && code < 200
def is2xx = code >= 200 && code < 300
def is3xx = code >= 300 && code < 400
def is4xx = code >= 400 && code < 500
def is5xx = code >= 500 && code < 600
def isSuccess = is2xx || (code == 304)
}
final case class Response(status : Status,
body : LazyVal[ResponseBody] = ResponseBody.emptyLazy,
headers: Headers = Headers.empty,
)
type ResponseBody = Body.Str
object ResponseBody {
def apply(content: String, contentType: Option[String]): ResponseBody =
Body.Str(content, contentType)
def empty : ResponseBody = Body.empty
def emptyLazy: LazyVal[ResponseBody] = Body.emptyLazy
}
implicit def univeqBody : UnivEq[Body ] = UnivEq.derive
implicit def univeqBodyStr : UnivEq[Body.Str ] = UnivEq.derive
implicit def univeqMethod : UnivEq[Method ] = UnivEq.force
implicit def univeqRequest : UnivEq[Request ] = UnivEq.derive
implicit def univeqResponse: UnivEq[Response ] = UnivEq.derive
implicit def univeqStatus : UnivEq[Status ] = UnivEq.derive
}