-
Notifications
You must be signed in to change notification settings - Fork 10
/
ResponseBuilder.scala
55 lines (38 loc) · 1.85 KB
/
ResponseBuilder.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
package util
import argo.format.PrettyJsonFormatter
import argo.jdom.JsonNodeFactories.{`object` => obj, _}
import argo.jdom.JsonRootNode
import com.twitter.finagle.http.Response
import com.twitter.util.Future
import org.jboss.netty.buffer.ChannelBuffers._
import org.jboss.netty.handler.codec.http.HttpResponseStatus
import org.jboss.netty.util.CharsetUtil._
import util.ResponseBuilder.formatter
object ResponseBuilder {
implicit def toFuture(builder: ResponseBuilder): Future[Response] = builder.toFuture
private val formatter = new PrettyJsonFormatter()
def apply(): ResponseBuilder = new ResponseBuilder()
def Ok = new ResponseBuilder().withCode(HttpResponseStatus.OK)
def Ok(content: String) = new ResponseBuilder().withCode(HttpResponseStatus.OK).withContent(content)
def Ok(content: JsonRootNode) = new ResponseBuilder().withCode(HttpResponseStatus.OK).withContent(content)
def Error(status: HttpResponseStatus, message: String) = new ResponseBuilder().withCode(status).withContent(obj(field("message", string(message))))
def Error(status: HttpResponseStatus, error: Throwable) = new ResponseBuilder().withCode(status).withContent(formatter.format(errorToJson(error)))
private def errorToJson(error: Throwable) = obj(field("message", string(Option(error.getMessage).getOrElse(error.getClass.getName))))
}
class ResponseBuilder private() {
private val response = Response()
def withCode(code: HttpResponseStatus): ResponseBuilder = {
response.setStatusCode(code.getCode)
this
}
def withContent(jsonContent: JsonRootNode): ResponseBuilder = {
response.setContentTypeJson()
withContent(formatter.format(jsonContent))
}
def withContent(content: String): ResponseBuilder = {
response.setContent(copiedBuffer(content, UTF_8))
this
}
def toFuture: Future[Response] = Future.value(response)
def build = response
}