-
Notifications
You must be signed in to change notification settings - Fork 0
/
RpcSupport.scala
52 lines (42 loc) · 1.58 KB
/
RpcSupport.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
package com.thoughtworks.akka.http
import akka.http.scaladsl.model.{MediaTypes, _}
import akka.http.scaladsl.server.Directives._
import com.thoughtworks.Extractor._
import scala.concurrent.Future
import akka.http.scaladsl.marshalling.Marshaller
import akka.http.scaladsl.unmarshalling.Unmarshaller
/**
* @author 杨博 (Yang Bo) <pop.atry@gmail.com>
*/
trait RpcSupport extends autowire.Server[upickle.Js.Value, upickle.default.Reader, upickle.default.Writer] {
implicit private def upickleJsValueMarshaller = {
Marshaller.StringMarshaller.wrap[upickle.Js.Value, MessageEntity](MediaTypes.`application/json`)(_.toString)
}
implicit private def upickleJsValueUnmarshaller = {
Unmarshaller.stringUnmarshaller.map(upickle.json.read)
}
final def write[Result](r: Result)(implicit writer: upickle.default.Writer[Result]) = {
writer.write(r)
}
final def read[Result](p: upickle.Js.Value)(implicit reader: upickle.default.Reader[Result]) = {
reader.read(p)
}
final def rpc(packagePrefix: String*)(routes: PartialFunction[Request, Future[upickle.Js.Value]]) = {
path(Segments) { segments =>
entity(as[upickle.Js.Value]) {
case upickle.Js.Obj(keyValuePairs@_*) =>
autowire.Core.Request(packagePrefix ++ segments, keyValuePairs.toMap) match {
case routes.extract(response) =>
complete {
response
}
case _ =>
reject
}
case _ =>
complete(HttpResponse(StatusCodes.BadRequest))
}
}
}
}
object RpcSupport extends RpcSupport