/
HttpEndpointA.scala
56 lines (44 loc) · 1.8 KB
/
HttpEndpointA.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
package net.ndolgov.akkahttptest.web
import java.util.concurrent.TimeUnit
import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.Directives.{as, complete, entity, onComplete, path, pathPrefix, post, withRequestTimeout}
import akka.http.scaladsl.server.Route
import net.ndolgov.akkahttptest.service.{TestRequestA, TestServiceA}
import org.slf4j.LoggerFactory
import scala.concurrent.duration.Duration
import scala.util.{Failure, Success}
import HttpEndpoints._
import ServiceAJsonMarshaller._
/** ServiceA HTTP end point */
class HttpEndpointA(service: TestServiceA, requestTimeoutMs: Int) {
private val logger = LoggerFactory.getLogger(this.getClass)
private val prefix = pathPrefix("akkahttp" / "test")
private val maxRequestDuration = Duration.create(requestTimeoutMs, TimeUnit.MILLISECONDS)
private val exceptionHandler = unexpectedExceptionHandler(logger)
private val rejectionHandler = garbledRequestHandler(logger)
/** @return all Routes supported by this HTTP end point */
def endpointRoutes(): Route = prefix {
process
}
private def process: Route =
handleExceptions(exceptionHandler) {
post {
path("testservicea") {
handleRejections(rejectionHandler) {
entity(as[TestRequestA]) { request: TestRequestA =>
withRequestTimeout(maxRequestDuration)
onComplete(service.process(request)) {
case Success(response) =>
complete(response)
case Failure(e) =>
val message = "Unexpectedly failed to process request"
logger.error(message, e)
complete(httpErrorResponse(StatusCodes.InternalServerError, message))
}
}
}
}
}
}
}