Skip to content

Instantly share code, notes, and snippets.

@yllan
Last active December 20, 2015 19:29
Show Gist options
  • Select an option

  • Save yllan/6183400 to your computer and use it in GitHub Desktop.

Select an option

Save yllan/6183400 to your computer and use it in GitHub Desktop.
Demonstrate a strange behavior of WS.
import scala.util._
import scala.concurrent._
import scala.concurrent.duration._
import play.api.libs.json._
import play.api.libs.ws._
case class GistFile(val filename: String, val content: String)
case class Gist(val token: String) {
def jsonStringForGist(description: String, public: Boolean, files: Set[GistFile]): String = {
val filesJson = Json.toJson(files.map(gf ⇒ (gf.filename -> Json.obj("content" -> gf.content))).toMap)
val gistJson = Json.obj(
"description" -> description,
"public" -> public,
"files" -> filesJson
)
Json.stringify(gistJson)
}
def createGist(description: String, public: Boolean, file: GistFile): Future[Try[String]] =
createGist(description, public, Set(file))
def createGist(description: String, public: Boolean, files: Set[GistFile]): Future[Try[String]] = {
import scala.concurrent.ExecutionContext.Implicits.global
val respF: Future[Response] = WS.url("https://api.github.com/gists")
.withHeaders("Authorization" -> s"token $token")
.post(jsonStringForGist(description, public, files))
respF.map((resp: Response) => Try {
(resp.json \ "html_url").as[String]
})
}
}
object Test extends App {
import play.api.libs.concurrent.Execution.Implicits._
val shortContent = Random.alphanumeric.take(160).grouped(80).map(_.mkString).mkString("\n")
val longContent = Random.alphanumeric.take(1024 * 100).grouped(80).map(_.mkString).mkString("\n")
val token = "fillyourgithubtoken"
val f1 = Gist(token).createGist("short gist example", true, GistFile("short.txt", shortContent))
val f2 = Gist(token).createGist("long gist example", true, GistFile("long.txt", longContent))
// Await.result(f2, 60.seconds) match {
// case Success(url) => println("url: " + url)
// case Failure(e) => println("e: " + e)
// }
f2 onSuccess {
case Success(url) => println("url: " + url)
case Failure(e) => println("e: " + e)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment