Last active
January 30, 2018 15:23
-
-
Save dcastro/6ba66e9d0a161dac0eb06481d838efc8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import monix.execution.Scheduler.Implicits.global | |
import monix.eval._ | |
import io.circe._ | |
import io.circe.generic.semiauto._ | |
import de.heikoseeberger.akkahttpcirce.ErrorAccumulatingCirceSupport._ | |
/** | |
POST localhost:9999/mock | |
{ | |
"request": { | |
"method": "GET", | |
"uri": "example" | |
}, | |
"response": { | |
"body" : {"x": 5}, | |
"code": 200 | |
} | |
} | |
GET localhost:9999/example | |
DELETE localhost:9999/mock | |
{ | |
"method": "GET", | |
"uri": "example" | |
} | |
*/ | |
val state: MVar[Map[Request, Response]] = MVar(Map()) | |
val defaultDirectives: Directive0 = | |
handleExceptions(handlers.exceptionHandler) & | |
handleRejections(handlers.rejectionHandler) & | |
cors(corsSettings) & | |
respondWithHeader(header) | |
val routes: Route = defaultDirectives { | |
path("mock") { | |
(post & entity(as[Setup])) { setup => | |
val action = | |
for { | |
map <- state.take | |
newMap = map.updated(setup.request, setup.response) | |
_ <- state.put(newMap) | |
} yield newMap | |
onSuccess(action.runAsync) { newMap => | |
complete(StatusCodes.OK -> newMap.toString) | |
} | |
} ~ | |
(delete & entity(as[Request])) { request => | |
val action = | |
for { | |
map <- state.take | |
newMap = map - request | |
_ <- state.put(newMap) | |
} yield newMap | |
onSuccess(action.runAsync) { newMap => | |
complete(StatusCodes.OK -> newMap.toString) | |
} | |
} | |
} ~ | |
(path(RemainingPath) & extractMethod) { (uri, method) => | |
onSuccess(state.read.runAsync) { map => | |
val request = Request(uri.toString, method.value) | |
map.get(request) match { | |
case Some(response) => complete(response.code -> response.body) | |
case _ => complete(StatusCodes.InternalServerError -> "Unexpected call") | |
} | |
} | |
} | |
} | |
case class Setup(request: Request, response: Response) | |
case class Request(uri: String, method: String) | |
case class Response(code: StatusCode, body: Json) | |
object Setup { implicit val setupDecoder: Decoder[Setup] = deriveDecoder[Setup] } | |
object Request { implicit val requestDecoder: Decoder[Request] = deriveDecoder[Request] } | |
object Response { | |
implicit val statusCodeDecoder: Decoder[StatusCode] = | |
Decoder.decodeInt.map(StatusCode.int2StatusCode) | |
implicit val responseDecoder: Decoder[Response] = deriveDecoder[Response] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment