Question

I'm trying to write a little rest api using spray-routing and elastic-search (with elastic4s) in order to improve my scala level. Here is my routes definition :

package com.example

import akka.actor.Actor
import spray.routing._
import com.example.core.control.CrudController

class ServiceActor extends Actor with Service {
  def actorRefFactory = context
  def receive = runRoute(routes)
}

trait Service extends HttpService {

  val crudController = new CrudController()
  val routes = {
      path("ads" / IntNumber) { id =>
      get {
          ctx =>
              ctx.complete(
                crudController.getFromElasticSearch
              )
      }
      }
  }
}

Here is my crudController :

class CrudController extends elastic4s
{

    def getFromElasticSearch : String = {
    val something: Future[SearchResponse] = get
    something onComplete {
        case Success(p) => println(p)
        case Failure(t) => println("An error has occured: " + t)
    }
    "{value:hey} \n"
    }
}

the method getFromElasticSearch encapsulates a call to the library elastic4s, via my trait get.

trait elastic4s {
    def get: Future[SearchResponse] = {
    val client = ElasticClient.local
    client execute { search in "ads"->"categories" }
    }

This library return a Future[SearchResponse] object via the method client.execute

I want my method getFromElasticSearch to be able to apply some modifications to the searchResponse (like validation, serialization..), maybe like this :

def getFromElasticSearch : String = {
    val something: Future[SearchResponse] = get
    something onComplete {
        case Success(p) => someOperations(p)
        case Failure(t) => println("An error has occured: " + t)
    }
    "{value:hey} \n"
}

def someOperations(response: SearchResponse) : String = {
    println(" Doing some operations " + response)
    "result of operations"
}

But how can I send the output String of "someOperations()" to the complete method of my spray-routing routes declaration ? (Instead of returning "{value:hey} \n") What's the best way of doing it ?

Was it helpful?

Solution

Spray have FutureMarshaller, so you can return Future itself.

def getFromElasticSearch: Future[String] = {
  val result: Future[SearchResponse] = get
  result onFailure {
     case t: Throwable => println("An error has occured: " + t)
  }
  result.map(someOperation)
}

OTHER TIPS

Should it not simply follow the pattern shown in the manual?

 case Success(p) => complete(someOperations(p))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top