| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869 |
- package com.weEat.controllers
- import javax.inject.{Inject,Singleton}
- import play.api._
- import play.api.mvc._
- import play.api.libs.json._
- import scala.util.{Try,Success,Failure}
- import com.tflucke.webroutes.HTTPException
- import scala.concurrent.{ExecutionContext,Future}
- import com.weEat.models.{FoodNode => FoodNodeCollection}
- import com.weEat.shared.models.{UnitType,USDANode}
- import com.weEat.shared.models.UnitType._
- import com.weEat.services.MongoDBService
- import org.mongodb.scala.model.Filters._
- import org.mongodb.scala.result.UpdateResult
- import com.weEat.shared.models._
- import org.bson.types.ObjectId
- @Singleton
- class FoodController @Inject()(
- val controllerComponents: ControllerComponents,
- db: MongoDBService
- ) extends BaseController {
- implicit val ec = scala.concurrent.ExecutionContext.global
- import db.withCollection
- def get(id: String) = Action.async
- { implicit request: Request[AnyContent] =>
- withCollection(FoodNodeCollection) {collection =>
- collection.find(equal("id", id))
- .first()
- .toFuture()
- .transform({
- case Success(x) => Success(Ok(Json.toJson(x)))
- case Failure(x) => throw x
- })
- }.flatten
- }
- def query() = Action.async
- { implicit request: Request[AnyContent] =>
- withCollection(FoodNodeCollection) {collection =>
- collection.find()
- .toFuture()
- .transform({
- case Success(x) => Success(Ok(Json.toJson(x)))
- case Failure(x) => throw x
- })
- }.flatten
- }
- def add() = Action.async(parse.json)
- { implicit request: Request[JsValue] =>
- try {
- val food = request.body.as[FoodNode].withId(new ObjectId)
- withCollection(FoodNodeCollection) {collection =>
- collection.insertOne(food).map(res =>
- Ok(Json.toJson(food.withId(res.getInsertedId().asObjectId().getValue())))
- ).head()
- }.flatten
- }
- catch {
- case jsre: JsResultException => Future.successful(
- BadRequest(s"Could not parse json into a Food node.")
- )
- }
- }
- }
|