/
Jsonp.scala
52 lines (46 loc) · 1.39 KB
/
Jsonp.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
package play.api.libs
import play.api.libs.json.JsValue
import play.api.http.{ContentTypeOf, ContentTypes, Writeable}
import play.api.mvc.Codec
/**
* JSONP helper.
*
* Example of use, provided the following route definition:
* {{{
* GET /my-service Application.myService(callback: String)
* }}}
* The following action definition:
* {{{
* def myService(callback: String) = Action {
* val json = ...
* Ok(Jsonp(callback, json))
* }
* }}}
* And the following request:
* {{{
* GET /my-service?callback=foo
* }}}
* The response will have content type “text/javascript” and will look like the following:
* {{{
* foo({...});
* }}}
*
* Another example, showing how to serve either JSON or JSONP from the same action, according to the presence of
* a “callback” parameter in the query string:
* {{{
* def myService = Action { implicit request =>
* val json = ...
* request.queryString.get("callback").flatMap(_.headOption) match {
* case Some(callback) => Ok(Jsonp(callback, json))
* case None => Ok(json)
* }
* }
* }}}
*/
case class Jsonp(padding: String, json: JsValue)
object Jsonp {
implicit val contentTypeOf_Jsonp = ContentTypeOf[Jsonp](Some(ContentTypes.JAVASCRIPT))
implicit def writeableOf_Jsonp(implicit codec: Codec) = Writeable[Jsonp] { jsonp =>
codec.encode("%s(%s);".format(jsonp.padding, jsonp.json))
}
}