aboutsummaryrefslogtreecommitdiff
path: root/src/main/scala/xyz/driver/core/rest/directives/Unmarshallers.scala
blob: 6c45d15449e1c65253721597b675e0fd1be5d5d3 (plain) (blame)
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
package xyz.driver.core
package rest
package directives

import java.util.UUID

import akka.http.scaladsl.marshalling.{Marshaller, Marshalling}
import akka.http.scaladsl.unmarshalling.Unmarshaller
import spray.json.{JsString, JsValue, JsonParser, JsonReader, JsonWriter}

/** Akka-HTTP unmarshallers for custom core types. */
trait Unmarshallers {

  implicit def idUnmarshaller[A]: Unmarshaller[String, Id[A]] =
    Unmarshaller.strict[String, Id[A]] { str =>
      Id[A](UUID.fromString(str).toString)
    }

  implicit def paramUnmarshaller[T](implicit reader: JsonReader[T]): Unmarshaller[String, T] =
    Unmarshaller.firstOf(
      Unmarshaller.strict((JsString(_: String)) andThen reader.read),
      stringToValueUnmarshaller[T]
    )

  implicit def revisionFromStringUnmarshaller[T]: Unmarshaller[String, Revision[T]] =
    Unmarshaller.strict[String, Revision[T]](Revision[T])

  val jsValueToStringMarshaller: Marshaller[JsValue, String] =
    Marshaller.strict[JsValue, String](value => Marshalling.Opaque[String](() => value.compactPrint))

  def valueToStringMarshaller[T](implicit jsonFormat: JsonWriter[T]): Marshaller[T, String] =
    jsValueToStringMarshaller.compose[T](jsonFormat.write)

  val stringToJsValueUnmarshaller: Unmarshaller[String, JsValue] =
    Unmarshaller.strict[String, JsValue](value => JsonParser(value))

  def stringToValueUnmarshaller[T](implicit jsonFormat: JsonReader[T]): Unmarshaller[String, T] =
    stringToJsValueUnmarshaller.map[T](jsonFormat.read)

}