/
Path.scala
370 lines (339 loc) · 12.2 KB
/
Path.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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
/*
* Copyright 2013-2020 http4s.org
*
* SPDX-License-Identifier: Apache-2.0
*
* Based on https://github.com/twitter/finagle/blob/6e2462acc32ac753bf4e9d8e672f9f361be6b2da/finagle-http/src/main/scala/com/twitter/finagle/http/path/Path.scala
* Copyright 2017, Twitter Inc.
*/
package org.http4s.dsl.impl
import cats.data._
import cats.data.Validated._
import cats.syntax.all._
import org.http4s._
import scala.util.Try
import cats.Foldable
import cats.Monad
import org.http4s.Uri.Path
import org.http4s.Uri.Path._
object :? {
def unapply[F[_]](req: Request[F]): Some[(Request[F], Map[String, collection.Seq[String]])] =
Some((req, req.multiParams))
}
/** File extension extractor */
object ~ {
/** File extension extractor for Path:
* Path("example.json") match {
* case Root / "example" ~ "json" => ...
*/
def unapply(path: Path): Option[(Path, String)] =
path match {
case Root => None
case parent / last =>
unapply(last).map { case (base, ext) =>
(parent / Path.Segment(base), ext)
}
}
/** File extension matcher for String:
* {{{
* "example.json" match {
* case => "example" ~ "json" => ...
* }}}
*/
def unapply(fileName: String): Option[(String, String)] =
fileName.lastIndexOf('.') match {
case -1 => Some((fileName, ""))
case index => Some((fileName.substring(0, index), fileName.substring(index + 1)))
}
}
object / {
def unapply(path: Path): Option[(Path, String)] =
if (path.endsWithSlash)
Some(path.dropEndsWithSlash -> "")
else
path.segments match {
case allButLast :+ last if allButLast.isEmpty =>
if (path.absolute)
Some(Root -> last.decoded())
else
Some(empty -> last.decoded())
case allButLast :+ last =>
Some(Path(allButLast, absolute = path.absolute) -> last.decoded())
case _ => None
}
}
object -> {
/** HttpMethod extractor:
* {{{
* (request.method, Path(request.path)) match {
* case Method.GET -> Root / "test.json" => ...
* }}}
*/
def unapply[F[_]](req: Request[F]): Some[(Method, Path)] =
Some((req.method, req.pathInfo))
}
class MethodConcat(val methods: Set[Method]) {
/** HttpMethod 'or' extractor:
* {{{
* val request: Request = ???
* request match {
* case (Method.GET | Method.POST) -> Root / "123" => ???
* }
* }}}
*/
def unapply(method: Method): Option[Method] =
Some(method).filter(methods)
}
/** Path separator extractor:
* {{{
* Path("/1/2/3/test.json") match {
* case "1" /: "2" /: _ => ...
* }}}
*/
object /: {
def unapply(path: Path): Option[(String, Path)] =
path.segments match {
case head +: tail => Some(head.decoded() -> Path(tail))
case _ => None
}
}
protected class PathVar[A](cast: String => Try[A]) {
def unapply(str: String): Option[A] =
if (!str.isEmpty)
cast(str).toOption
else
None
}
/** Integer extractor of a path variable:
* {{{
* Path("/user/123") match {
* case Root / "user" / IntVar(userId) => ...
* }}}
*/
object IntVar extends PathVar(str => Try(str.toInt))
/** Long extractor of a path variable:
* {{{
* Path("/user/123") match {
* case Root / "user" / LongVar(userId) => ...
* }}}
*/
object LongVar extends PathVar(str => Try(str.toLong))
/** UUID extractor of a path variable:
* {{{
* Path("/user/13251d88-7a73-4fcf-b935-54dfae9f023e") match {
* case Root / "user" / UUIDVar(userId) => ...
* }}}
*/
object UUIDVar extends PathVar(str => Try(java.util.UUID.fromString(str)))
/** Matrix path variable extractor
* For an example see [[https://www.w3.org/DesignIssues/MatrixURIs.html MatrixURIs]]
* This is useful for representing a resource that may be addressed in multiple dimensions where order is unimportant
*
* {{{
*
* object BoardVar extends MatrixVar("square", List("x", "y"))
* Path("/board/square;x=5;y=3") match {
* case Root / "board" / BoardVar(IntVar(x), IntVar(y)) => ...
* }
* }}}
*/
abstract class MatrixVar[F[_]: Foldable](name: String, domain: F[String]) {
private val domainList = domain.toList
def unapplySeq(str: String): Option[Seq[String]] =
if (str.nonEmpty) {
val firstSemi = str.indexOf(';')
if (firstSemi < 0 && (domain.nonEmpty || name != str)) None
else if (firstSemi < 0 && name == str) Some(Seq.empty[String])
// Matrix segment didn't match the expected name
else if (str.substring(0, firstSemi) != name) None
else {
val assocListOpt =
if (firstSemi >= 0)
Monad[Option].tailRecM(MatrixVar.RecState(str, firstSemi + 1, List.empty))(toAssocList)
else Some(List.empty[(String, String)])
assocListOpt.flatMap { assocList =>
domainList.traverse(dom => assocList.find(_._1 == dom).map(_._2))
}
}
} else None
private def toAssocList(
recState: MatrixVar.RecState): Option[Either[MatrixVar.RecState, List[(String, String)]]] =
// We can't extract anything else but there was a trailing ;
if (recState.position >= recState.str.length - 1)
Some(Right(recState.accumulated))
else {
val nextSplit = recState.str.indexOf(';', recState.position)
// This is the final ; delimited segment
if (nextSplit < 0)
toAssocListElem(recState.str, recState.position, recState.str.length)
.map(elem => Right(elem :: recState.accumulated))
// An internal empty ; delimited segment so just skip
else if (nextSplit == recState.position)
Some(Left(recState.copy(position = nextSplit + 1)))
else
toAssocListElem(recState.str, recState.position, nextSplit)
.map(elem =>
Left(
recState.copy(position = nextSplit + 1, accumulated = elem :: recState.accumulated)))
}
private def toAssocListElem(str: String, position: Int, end: Int): Option[(String, String)] = {
val delimSplit = str.indexOf('=', position)
val nextDelimSplit = str.indexOf('=', delimSplit + 1)
// if the segment does not contain an = inside then it is invalid
if (delimSplit < 0 || delimSplit === position || delimSplit >= end) None
// if the segment contains multiple = then it is invalid
else if (nextDelimSplit < end && nextDelimSplit >= 0) None
else Some(str.substring(position, delimSplit) -> str.substring(delimSplit + 1, end))
}
}
object MatrixVar {
private final case class RecState(str: String, position: Int, accumulated: List[(String, String)])
}
/** Multiple param extractor:
* {{{
* object A extends QueryParamDecoderMatcher[String]("a")
* object B extends QueryParamDecoderMatcher[Int]("b")
* val routes = HttpRoutes.of {
* case GET -> Root / "user" :? A(a) +& B(b) => ...
* }}}
*/
object +& {
def unapply(params: Map[String, collection.Seq[String]])
: Some[(Map[String, collection.Seq[String]], Map[String, collection.Seq[String]])] =
Some((params, params))
}
/** param extractor using [[QueryParamDecoder]]:
* {{{
* case class Foo(i: Int)
* implicit val fooDecoder: QueryParamDecoder[Foo] = ...
*
* object FooMatcher extends QueryParamDecoderMatcher[Foo]("foo")
* val routes = HttpRoutes.of {
* case GET -> Root / "closest" :? FooMatcher(2) => ...
* }}}
*/
abstract class QueryParamDecoderMatcher[T: QueryParamDecoder](name: String) {
def unapplySeq(params: Map[String, collection.Seq[String]]): Option[collection.Seq[T]] =
params
.get(name)
.flatMap(values =>
values.toList.traverse(s => QueryParamDecoder[T].decode(QueryParameterValue(s)).toOption))
def unapply(params: Map[String, collection.Seq[String]]): Option[T] =
params
.get(name)
.flatMap(_.headOption)
.flatMap(s => QueryParamDecoder[T].decode(QueryParameterValue(s)).toOption)
}
/** param extractor using [[QueryParamDecoder]]:
*
* {{{
* case class Foo(i: Int)
* implicit val fooDecoder: QueryParamDecoder[Foo] = ...
* implicit val fooParam: QueryParam[Foo] = ...
*
* object FooMatcher extends QueryParamDecoderMatcher[Foo]
* val routes = HttpRoutes.of {
* case GET -> Root / "closest" :? FooMatcher(2) => ...
* }}}
*/
abstract class QueryParamMatcher[T: QueryParamDecoder: QueryParam]
extends QueryParamDecoderMatcher[T](QueryParam[T].key.value)
abstract class OptionalQueryParamDecoderMatcher[T: QueryParamDecoder](name: String) {
def unapply(params: Map[String, collection.Seq[String]]): Option[Option[T]] =
params
.get(name)
.flatMap(_.headOption)
.traverse(s => QueryParamDecoder[T].decode(QueryParameterValue(s)))
.toOption
}
/** Flag (value-less) query param extractor
*/
abstract class FlagQueryParamMatcher(name: String) {
def unapply(params: Map[String, collection.Seq[String]]): Option[Boolean] =
Some(params.contains(name))
}
/** Capture a query parameter that appears 0 or more times.
*
* {{{
* case class Foo(i: Int)
* implicit val fooDecoder: QueryParamDecoder[Foo] = ...
* implicit val fooParam: QueryParam[Foo] = ...
*
* object FooMatcher extends OptionalMultiQueryParamDecoderMatcher[Foo]("foo")
* val routes = HttpRoutes.of {
* // matches http://.../closest?foo=2&foo=3&foo=4
* case GET -> Root / "closest" :? FooMatcher(Validated.Valid(Seq(Foo(2),Foo(3),Foo(4)))) => ...
*
* /*
* * matches http://.../closest?foo=2&foo=3&foo=4 as well as http://.../closest (no parameters)
* * or http://.../closest?foo=2 (single occurrence)
* */
* case GET -> Root / "closest" :? FooMatcher(is) => ...
* }}}
*/
abstract class OptionalMultiQueryParamDecoderMatcher[T: QueryParamDecoder](name: String) {
def unapply(
params: Map[String, collection.Seq[String]]): Option[ValidatedNel[ParseFailure, List[T]]] =
params.get(name) match {
case Some(values) =>
Some(values.toList.traverse(s => QueryParamDecoder[T].decode(QueryParameterValue(s))))
case None => Some(Valid(Nil)) // absent
}
}
abstract class OptionalQueryParamMatcher[T: QueryParamDecoder: QueryParam]
extends OptionalQueryParamDecoderMatcher[T](QueryParam[T].key.value)
/** param extractor using [[org.http4s.QueryParamDecoder]]. Note that this will return a
* [[ParseFailure]] if the parameter cannot be decoded.
*
* {{{
* case class Foo(i: Int)
* implicit val fooDecoder: QueryParamDecoder[Foo] = ...
*
* object FooMatcher extends ValidatingQueryParamDecoderMatcher[Foo]("foo")
* val routes: HttpRoutes.of = {
* case GET -> Root / "closest" :? FooMatcher(fooValue) =>
* fooValue.fold(
* nelE => BadRequest(nelE.toList.map(_.sanitized).mkString("\n")),
* foo => { ... }
* )
* }}}
*/
abstract class ValidatingQueryParamDecoderMatcher[T: QueryParamDecoder](name: String) {
def unapply(params: Map[String, collection.Seq[String]]): Option[ValidatedNel[ParseFailure, T]] =
params.get(name).flatMap(_.headOption).map { s =>
QueryParamDecoder[T].decode(QueryParameterValue(s))
}
}
/** param extractor using [[org.http4s.QueryParamDecoder]]. Note that this will _always_ match, but will return
* an Option possibly containing the result of the conversion to T
*
* {{{
* case class Foo(i: Int)
* implicit val fooDecoder: QueryParamDecoder[Foo] = ...
*
* case class Bar(i: Int)
* implicit val barDecoder: QueryParamDecoder[Bar] = ...
*
* object FooMatcher extends ValidatingQueryParamDecoderMatcher[Foo]("foo")
* object BarMatcher extends OptionalValidatingQueryParamDecoderMatcher[Bar]("bar")
*
* val routes = HttpRoutes.of {
* case GET -> Root / "closest" :? FooMatcher(fooValue) +& BarMatcher(barValue) =>
* ^(fooValue, barValue getOrElse 42.right) { (foo, bar) =>
* ...
* }.fold(
* nelE => BadRequest(nelE.toList.map(_.sanitized).mkString("\n")),
* baz => { ... }
* )
* }}}
*/
abstract class OptionalValidatingQueryParamDecoderMatcher[T: QueryParamDecoder](name: String) {
def unapply(
params: Map[String, collection.Seq[String]]): Some[Option[ValidatedNel[ParseFailure, T]]] =
Some {
params.get(name).flatMap(_.headOption).fold[Option[ValidatedNel[ParseFailure, T]]](None) {
s =>
Some(QueryParamDecoder[T].decode(QueryParameterValue(s)))
}
}
}