Skip to content

Instantly share code, notes, and snippets.

@xasima
Last active August 29, 2015 14:21
Show Gist options
  • Select an option

  • Save xasima/adee2a1a31f924b870aa to your computer and use it in GitHub Desktop.

Select an option

Save xasima/adee2a1a31f924b870aa to your computer and use it in GitHub Desktop.
Finch usage to transfer custom headers
// Let change finch example to specify custom http-headers (let call them CTPPHeader) per models
object model {
trait ToJsonWithHeaders {
def toJson: Json
// provide specific headers per model file
def getTemplate :String
}
case class User(val id: Long, val name: String) extends ToJsonWithHeaders {
override def toJson = User.encodeJson(this)
// this would be used later to generate specific http headers: 'x-template' -> 'user'
override def getTemplate = "user"
}
// Some code parts are omitted which are the same with finch-example
implicit class SeqToJson[A](s: Service[A, Seq[ToJsonWithHeaders]]) extends Service[A, ToJsonWithHeaders] {
private[server] def seqToJson(seq: Seq[ToJsonWithHeaders]) = new ToJsonWithHeaders {
def toJson: Json = Json.array(seq.map { _.toJson }: _*)
// Needs to specify templates anyway, so follow the approach when
// 'template' is for single model entity, 'templateSeq' for the Seq[entity], and 'empty' for the empty collection
def getTemplate = if(seq.isEmpty) "empty" else seq(0).getTemplate+"Seq"
}
def apply(req: A): Future[ToJsonWithHeaders] = s(req) map seqToJson
}
}
def okWithCustomHeaders[A, B <:ToJsonWithHeaders](req:B): ResponseBuilder =
Ok.withHeaders( "x-template" -> req.getTemplate)
class TurnIntoHttpWithHeaders[A<:ToJsonWithHeaders](val e: EncodeResponse[A]) extends Service[A, HttpResponse] {
def apply(req: A): Future[HttpResponse] = okWithCustomHeaders(req)(req)(e).toFuture
}
/**
* A service that converts an encoded object into HTTP response with status ''OK'' using an implicit
* [[io.finch.response.EncodeResponse EncodeResponse]].
*/
object TurnIntoHttpWithHeaders {
def apply[A<:ToJsonWithHeaders](implicit e: EncodeResponse[A]): Service[A, HttpResponse] = new TurnIntoHttpWithHeaders[A](e)
}
// EncodeResponse for Json implicit conversion
implicit val encodeToJson = EncodeResponse[ToJsonWithHeaders]("text/html") { _.toJson.toString}
import endpoint._
val api: Service[AuthRequest, ToJsonWithHeaders] = restEndpoint
import model._
val backend: Service[HttpRequest, HttpResponse] =
handleExceptions ! authorize ! (api ! TurnIntoHttpWithHeaders[ToJsonWithHeaders])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment