World.scala 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package models
  2. import play.api.db._
  3. import play.api.Play.current
  4. import anorm._
  5. import anorm.SqlParser._
  6. import play.api.libs.json._
  7. import play.api.libs.functional.syntax._
  8. case class World(id: Pk[Long], randomNumber: Long)
  9. object World {
  10. /**
  11. * Convert a World to Json object
  12. */
  13. implicit val toJson = new Writes[World] {
  14. def writes(w: World): JsValue = {
  15. Json.obj(
  16. "id" -> w.id.get,
  17. "randomNumber" -> w.randomNumber
  18. )
  19. }
  20. }
  21. /**
  22. * Parse a World from a ResultSet
  23. */
  24. val simpleRowParser = {
  25. get[Pk[Long]]("world.id") ~
  26. get[Long]("world.randomNumber") map {
  27. case id~randomNumber => World(id, randomNumber)
  28. }
  29. }
  30. /**
  31. * Retrieve a World by id.
  32. */
  33. def findById(id: Long): World = {
  34. DB.withConnection { implicit connection =>
  35. SQL("SELECT * FROM world WHERE id = {id}").on(
  36. "id" -> id
  37. ).as(World.simpleRowParser.single)
  38. }
  39. }
  40. }