FoodController.scala 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package controllers
  2. import scala.concurrent.Await
  3. import scala.concurrent.duration.Duration
  4. import javax.inject._
  5. import models.{Food,Unit,Mass,Measure}
  6. import play.api.mvc._
  7. import play.api.libs.json._
  8. import play.api.test._
  9. import org.mongodb.scala.model.Filters
  10. import org.mongodb.scala.{MongoDatabase,MongoCollection,Observable,Completed}
  11. @Singleton
  12. class FoodController(collection: MongoCollection[Food], sync: Boolean = true) extends Controller {
  13. def this(db: MongoDatabase, sync: Boolean) {
  14. this(db.getCollection[Food]("Food"), sync)
  15. }
  16. def this() {
  17. this(MongoDB.con, false)
  18. }
  19. def put(): Action[JsValue] = Action(parse.json) { request: Request[JsValue] =>
  20. try {
  21. val food: Food = request.body.as[Food]
  22. val query: Observable[Completed] = collection.insertOne(food)
  23. if (sync)
  24. {
  25. Await.result(query.toFuture, Duration.Inf)
  26. }
  27. Ok(Json.toJson(food))
  28. }
  29. catch {
  30. case jsre: JsResultException => BadRequest(s"Could not parse json into Food.")
  31. }
  32. }
  33. def update(id: String): Action[JsValue] = Action(parse.json) { request: Request[JsValue] =>
  34. try {
  35. val query: Observable[Food] = collection.find(Filters.equal[String]("_id", id))
  36. val food: Food = Await.result(query.toFuture, Duration.Inf)
  37. val newJson: JsObject = Json.toJson(expFood) ++ request.body
  38. val save: Observable[Completed] = collection.save(food.as[Food])
  39. if (sync)
  40. {
  41. Await.result(query.toFuture, Duration.Inf)
  42. }
  43. Ok(newJson)
  44. }
  45. catch {
  46. case jsre: JsResultException => BadRequest(s"Could not parse json into Food.")
  47. }
  48. }
  49. def get(id: Int): Action[JsValue] = Action(parse.json) { request: Request[JsValue] =>
  50. Ok(Json.toJson(expFood))
  51. }
  52. def query(query: String = ""): Action[JsValue] = Action(parse.json) { request: Request[JsValue] =>
  53. Ok(Json.toJson(expFood))
  54. }
  55. def delete(id: Int): Action[JsValue] = Action(parse.json) { request: Request[JsValue] =>
  56. Ok(request.body)
  57. }
  58. }