Skip to content

Instantly share code, notes, and snippets.

@agnaldo4j
Created November 22, 2012 01:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save agnaldo4j/4128980 to your computer and use it in GitHub Desktop.
Save agnaldo4j/4128980 to your computer and use it in GitHub Desktop.
Removendo código duplicado com funções.
package controllers.nereida
import play.api._
import play.api.mvc._
import play.api.data._
import play.api.data.Forms._
import play.api.libs.json.{Json, JsValue}
import models.nereida.City
import persistence.Prevayler
import persistence.commands.city.{AddNewCity, DeleteCity, UpdateCity, FindAllCities, FindCityById}
import views._
object CityController extends Controller {
val cityMapping = ( "name" -> nonEmptyText )
val cityForm = Form(
mapping("name" -> nonEmptyText, "id" -> nonEmptyText)(City.apply)(City.unapply)
)
def index = Action { implicit request =>
val cities = Prevayler.system.executeQuery( FindAllCities() )
Created( Json.toJson(cities) )
}
def build = Action {
Ok(views.html.nereida.city.cityForm(cityForm));
}
def create = processJSONRequest {
implicit json => {
val city = Prevayler.system.executeTransaction( AddNewCity(json) )
Created(Json.toJson(city))
}
}
def show(id:String) = processQuery {
Prevayler.system.executeQuery( FindCityById(id) )
}
def edit(id:String) = processQuery {
Prevayler.system.executeQuery( FindCityById(id) )
}
def update(id:String) = processJSONRequest {
implicit json => {
val city = Prevayler.system.executeTransaction( UpdateCity(id, json) )
Created(Json.toJson(city))
}
}
def destroy(id:String) = Action { implicit request =>
val city = Prevayler.system.executeTransaction( DeleteCity(id) )
Ok(Json.toJson(city))
}
//aux functions
def processJSONRequest(innerFunction: JsValue => Result) = {
Action {
implicit request => {
Form(cityMapping).bindFromRequest.fold(
errors => BadRequest(errors.errorsAsJson),
value => {
request.body.asJson.map { json =>
innerFunction(json)
}.getOrElse {
BadRequest(Json.toJson(Map("error" -> "invalid json")))
}
}
)
}
}
}
def processQuery(innerFunction: => Option[City]) = {
Action {
innerFunction.map { city =>
Ok(views.html.nereida.city.cityForm(cityForm.fill( city )))
}.getOrElse {
BadRequest(Json.toJson(Map("error" -> "invalid json")))
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment