Created
November 22, 2012 01:48
-
-
Save agnaldo4j/4128980 to your computer and use it in GitHub Desktop.
Removendo código duplicado com funções.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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