1
0

Cards.scala 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package controllers
  2. import play.api._
  3. import play.api.mvc._
  4. import play.api.data._
  5. import play.api.data.Forms._
  6. import play.api.libs.json._
  7. import models._
  8. object Cards extends Controller {
  9. val cardMapping = mapping(
  10. "word" -> text,
  11. "taboo" -> seq(text).transform(_.toSet, (set: Set[String]) => set.toSeq)
  12. )(Card.apply)(Card.unapply)
  13. val cardForm = Form(cardMapping)
  14. val cardsForm = Form(seq(cardMapping))
  15. def add = Action(parse.json) { implicit request =>
  16. cardForm.bindFromRequest.fold(
  17. { case error => BadRequest("invalid format") },
  18. { case card =>
  19. Card.add(card)
  20. Ok("ok")
  21. }
  22. )
  23. }
  24. def exists(word: String) = Action {
  25. Ok(Json.obj(
  26. "word" -> word,
  27. "exists" -> Card.exists(word)
  28. ))
  29. }
  30. def load = Action(parse.json) { implicit request =>
  31. cardsForm.bindFromRequest.fold(
  32. { case error => BadRequest("invalid format") },
  33. { case cards =>
  34. cards.foreach { card =>
  35. Card.add(card)
  36. }
  37. Ok("ok")
  38. }
  39. )
  40. }
  41. def dump = Action {
  42. Ok(Json.toJson(Card.list()))
  43. }
  44. var cardPool = CardPool.get()
  45. def random = Action {
  46. if(!cardPool.hasNext) {
  47. cardPool = CardPool.get()
  48. }
  49. Ok(Json.toJson(cardPool.next()))
  50. }
  51. }