how to apply Form validators on object - forms

I have an API in Scala. When I want to create a new User, i need validators on some fields (UserName, FirstName, LastName). I can't find a solution to apply the Form on my case class User. I thought using (User.apply) this will override automatically my User class, but this isn't happening.
User.scala
case class User(
id: Int = 0,
userName: String,
firstName: String,
lastName: String
)
object User {
import play.api.libs.json._
implicit val jsonWrites = Json.writes[User]
implicit val userReads = Json.reads[User]
def tupled = (User.apply _).tupled
}
// Form validator for post requests
object UserForm {
val form: Form[User] = Form(
mapping(
"id" -> number,
"userName" -> text(minLength = 5),
"firstName" -> text(minLength = 5),
"lastName" -> nonEmptyText
)(User.apply)(User.unapply)
)
}
UsersController.scala
def create = Action(parse.json) { implicit request => {
val userFromJson = Json.fromJson[User](request.body)
userFromJson match {
case JsSuccess(user: User, path: JsPath) => {
var createdUser = Await.result(usersRepository.create(user), Duration.Inf)
Ok(Json.toJson(createdUser))
}
case error # JsError(_) => {
println(error)
InternalServerError(Json.toJson("Can not create user"))
}
}
}
}
UsersRepository.scala
def create(user: User): Future[User] = {
val insertQuery = dbUsers returning dbUsers.map(_.id) into ((x, id) => x.copy(id = id))
val query = insertQuery += user
db.run(query)
}
(UsersRepository doesn't matter so much in this problem)
So, when I read the json, I think there need to apply the form validators
val userFromJson = Json.fromJson[User](request.body)
but nothing happening. Another problem is if I send from client a null parameter, will get an error, can not read and create an User.
For example :
"firstName": "" - empty userName will pass
"firstName": null - will fail
This depends on how is configured the User class in client (Angular), with the field null or empty in constructor. I prefer to set it null, even if is a string, if is not a required field (better NULL value in database, than an empty cell)

Try to use this:
request.body.validate[User]
One other thing, you shouldn't use
var createdUser = Await.result(usersRepository.create(user), Duration.Inf)
So use val´s over var´s and the other thing, you don't need to force the future to resolve, use it like this:
val createdUser = usersRepository.create(user)
createdUser.map(Ok(Json.toJson(_)))
And your action should be async.

Find a solution, my Form need to be part of object User, and not to be another object.
object User {
import play.api.libs.json._
implicit val jsonWrites = Json.writes[User]
implicit val userReads = Json.reads[User]
val form: Form[User] = Form(
mapping(
"id" -> number,
"userName" -> text(minLength = 2),
"firstName" -> text(minLength = 4),
"lastName" -> nonEmptyText
)(User.apply)(User.unapply)
)
def tupled = (User.apply _).tupled
}
and the method in Controller became :
def create = Action(parse.json) { implicit request => {
User.form.bindFromRequest.fold(
formWithErrors => BadRequest(Json.toJson("Some form fields are not validated.")),
success => {
val userFromJson = Json.fromJson[User](request.body)
userFromJson match {
case JsSuccess(user: User, path: JsPath) => {
val createdUser = Await.result(usersRepository.create(user), Duration.Inf)
Ok(Json.toJson(createdUser))
}
case error#JsError(_) => {
println(error)
InternalServerError(Json.toJson("Can not create user"))
}
}
}
)
}
}
I know, I need to format my code ... using IntelliJ is so annoying after Visual Studio :(

Related

How to get array from a json formatted form in Scala?

I am new to SCALA where I am going to develop an API with PLAY and SLICK.
I am going fetch an array (json formatted all the values are in integer) from a form via a web request like as follows:-
Request data:
{"ids": [1,2,3,4,5,6,7,8,9]}
Now I would like to fetch the form array data. Therefore I have declare a Form in my controller as:-
case class IdsForm(ids: Array[Int])
private val idsForm: Form[IdsForm] = Form(
mapping(
"ids" -> ????
)(IdsForm.apply)(IdsForm.unapply)
)
Now Would like to print all the elements in that array. Hence declare a function as follows:-
def getIds() = Action.async(parse.json) {
implicit request => idsForm.bind(request.body).fold(
formWithErrors => Future.successful(BadRequest(formWithErrors.toString)),
form => {
val ids = form.ids
// Print all the array elements
for ( x <- ids ) {
println( x )
}
val responseBody = Json.obj(
"status" -> 200,
"message" -> Json.toJson("Successfully printed")
)
Ok(responseBody)
}
)
}
Please let me know, what to put instead of "ids" -> ???? on my code. In case of single number I have putted "id" -> number. I don't know what to put instead of ???? in "ids" -> ????
You shouldn't use a form to submit JSON... Here you have example how to do it. Although, you could upload a JSON file if you want?
For example(I didn't test this), your data class:
case class MyData(ids: List[Int])
object MyData { implicit val myDataJsonFormat: Json.format[MyData] }
Your controller route:
def uploadJson = Action(parse.json) { request =>
val dataResult = request.body.validate[MyData]
dataResult.fold(
errors => { BadRequest(........) },
data => {
// do whatever with data....
Ok(....)
}
)
}
I use my code as:-
case class IdsForm(ids: Seq[Int])
private val idsForm: Form[IdsForm] = Form(
mapping(
"ids" -> seq[number]
)(IdsForm.apply)(IdsForm.unapply)
)
And the function is:-
def getIds() = Action.async(parse.json) {
implicit request => idsForm.bind(request.body).fold(
formWithErrors => Future.successful(BadRequest(formWithErrors.toString)),
form => {
val ids = form.ids
// Print all the array elements
for ( x <- 0 to ids.length - 1 ) {
println( ids(x) )
}
val responseBody = Json.obj(
"status" -> 200,
"message" -> Json.toJson("Successfully printed")
)
Ok(responseBody)
}
)
}
It works fine. Is it ok?

Play Framework:Error type mismatch; found :Int required: play.api.mvc.Result

I am trying to save form values to a database, and play I am getting the error:
type mismatch; found :Int required: play.api.mvc.Result
And here is my code :
Application.scala
import play.api._
import play.api.mvc._
import play.api.data._
import play.api.data.Forms._
import views.html.defaultpages.badRequest
import play.api.data.validation.Constraints._
import models.User
import models.UserData
object Application extends Controller {
val RegisterForm = Form(
mapping(
"fname" -> nonEmptyText(1, 20),
"lname" -> nonEmptyText(1, 20),
"email" -> email,
"userName" -> nonEmptyText(1, 20),
"password" -> nonEmptyText(1, 20),
"age" -> number,
"choice" -> text,
"gender" -> text
)(User.apply)(User.unapply)
.verifying("Ag should be greater then or equal to 18", model => model.age match {
case (age) => age >= 18
})
)
def index = Action {
Ok(views.html.index(RegisterForm))
}
def register = Action { implicit request =>
RegisterForm.bindFromRequest().fold(
hasErrors => BadRequest(views.html.index(hasErrors)),
success => {
User.save(success)
}
)
}
}
User.scala
import anorm._
import play.api.db.DB
import anorm.SqlParser._
import play.api.Play.current
case class User (
fname: String,
lname: String,
email: String,
userName: String,
password: String,
age: Int,
choice: String,
gender: String
)
object User {
val userinfo = {
get[String]("fname") ~
get[String]("lname") ~
get[String]("email") ~
get[String]("userName") ~
get[String]("password") ~
get[Int]("age") ~
get[String]("choice") ~
get[String]("gender") map {
case fname~lname~email~userName~password~age~choice~gender =>
User(fname, lname, email, userName, password, age, choice, gender)
}
}
def save(ud: User) = {
DB.withConnection { implicit c =>
SQL ("insert into userinfo(fname,lname,email,userName,password,age,choice,gender) values ({fname},{lname},{email},{userName},{password},{age},{choice},{gender})")
.on('fname -> ud.fname, 'lname ->ud.lname ,'email ->ud.email, 'userName->ud.userName , 'password->ud.password ,'age->ud.age, 'choice->ud.choice,'gender->ud.gender)
.executeUpdate()
}
}
}
i took help from the scala cook book for this save functions but i am having problem as i am new in play scala maybe the mistake was minor one so please help me,all i want is to store all the input values in DB which was entered in the form
The problem is with your controller function register:
def register = Action { implicit request =>
RegisterForm.bindFromRequest().fold(
hasErrors => BadRequest(views.html.index(hasErrors)),
success => {
// You need to return a `Result` here..
// Maybe redirect to login?
// Redirect("/login")
User.save(success)
}
)
}
The problem is that User.save returns an Int, and the controller function is expecting a Result, like Ok(..), Redirect(...), etc. You need to do something with the result of User.save to return a Result.
It would be better if you used executeInsert() instead of executeUpdate(), as executeInsert returns Option[Long] by default--which will help you determine if the save was successful.
e.g.:
def save(ud: User): Option[Long] = {
DB.withConnection {implicit c =>
SQL("insert into userinfo(fname,lname,email,userName,password,age,choice,gender) values ({fname},{lname},{email},{userName},{password},{age},{choice},{gender})")
.on('fname -> ud.fname, 'lname ->ud.lname ,'email ->ud.email, 'userName->ud.userName , 'password->ud.password ,'age->ud.age, 'choice->ud.choice,'gender->ud.gender)
.executeInsert()
}
}
Then within your controller function use it like this:
def register = Action { implicit request =>
RegisterForm.bindFromRequest().fold(
hasErrors => BadRequest(views.html.index(hasErrors)),
success => {
User.save(success) map { newId =>
Redirect("/login") // or whatever you want this to do on success
} getOrElse {
InternalServerError("Something has gone terribly wrong...")
}
}
)
}
You can replace my placeholder results with something a little more meaningful in your application.
The save(ud:User) method returns the integer value. Action should always return Result, so write
success => {
val result = User.save(success)
Ok(result.toString)
}

Form binding with custom mapping to object - how?

I have these case class
case class Blog(id:Long, author:User, other stuff...)
case class Comment(id:Long, blog:Blog, comment:String)
and a form on the client side that submits the data
blog_id:"5"
comment:"wasssup"
I'm writing some simple code to let a user add a comment to a blog.
The user is logged in so the his user_id is not needed from the client side, we know who he is...
I would like to bind the blog_id to a Blog object loaded from db, and if it doesn't exist show an error.
The examples on play framework docs are not helpful.
They only show mappings for forms that represent a single Object and all of its fields.
Here I'm representing a tuple of a (b:Blog, comment:String) and for the Blog I'm only supplying it's id.
I'd like to have a mapping that would provide me with the conversion + validation + error messages, so i can write something like:
val form = Form(
tuple(
"blog_id" -> blogMapping,
"comment" -> nonEmptyText
)
)
form.bindFromRequest().fold(...
formWithErrors => {...
}, {
case (blog, comment) => {do some db stuff to create the comment}
...
The "blogMapping" wlil work like other mappings, it will bind the posted data to an object, in our case a blog loaded from db, and in case it's not successful it will provide an error that we can use on the formWithErrors => clause.
I'm not sure how to accomplish this, the docs are kinda lacking here...
any help is appreciated!
I ended up looking at how playframwork's current bindings look like and implementing something similar, but for Blog:
implicit def blogFromLongFormat: Formatter[Blog] = new Formatter[Blog] {
override val format = Some(("Blog does not exist", Nil))
def bind(key: String, data: Map[String, String]) = {
scala.util.control.Exception.allCatch[Long] either {
data.get(key).map(s => {
val blog_id = s.toLong
val blog = Daos.blogDao.retrieve(blog_id)
blog.map(Right(_)).getOrElse(Left(Seq(FormError(key, "Blog not found", Nil))))
}).get
} match {
case Right(e:Either[Seq[FormError],Blog]) => e
case Left(exception) => Left(Seq(FormError(key, "Invalid Blog Id", Nil)))
case _ => Left(Seq(FormError(key, "Error in form submission", Nil)))
}
}
def unbind(key: String, value: Blog) = Map(key -> value.id.toString)
}
val blogFromLongMapping: Mapping[Blog] = Forms.of[Blog]
To me, this doesn't really look like a binding problem.
The issue is around the Model-View-Controller split. Binding is a Controller activity, and it's about binding web data (from your View) to your data model (for use by the Model). Querying the data, on the other hand, would very much be handled by the Model.
So, the standard way to do this would be something like the following:
// Defined in the model somewhere
def lookupBlog(id: Long): Option[Blog] = ???
// Defined in your controllers
val boundForm = form.bindFromRequest()
val blogOption = boundForm.value.flatMap {
case (id, comment) => lookupBlog(id)
}
blogOption match {
case Some(blog) => ??? // If the blog is found
case None => ??? // If the blog is not found
}
However, if you are determined to handle database lookup in your binding (I'd strongly advise against this, as it will lead to spaghetti code in the long run), try something like the following:
class BlogMapping(val key: String = "") extends Mapping[Blog] {
val constraints = Nil
val mappings = Seq(this)
def bind(data: Map[String, String]) = {
val blogOpt = for {blog <- data.get(key)
blog_id = blog.toLong
blog <- lookupBlog(blog_id)} yield blog
blogOpt match {
case Some(blog) => Right(blog)
case None => Left(Seq(FormError(key, "Blog not found")))
}
}
def unbind(blog: Blog) = (Map(key -> blog.id.toString), Nil)
def withPrefix(prefix: String) = {
new BlogMapping(prefix + key)
}
def verifying(constraints: Constraint[Blog]*) = {
WrappedMapping[Blog, Blog](this, x => x, x => x, constraints)
}
}
val blogMapping = new BlogMapping()
val newform = Form(
tuple(
"blog_id" -> blogMapping,
"comment" -> nonEmptyText
)
)
// Example usage
val newBoundForm = newform.bindFromRequest()
val newBoundBlog = newBoundForm.get
The main thing we've done is to create a custom Mapping subclass. This can be a good idea under some circumstances, but I'd still recommend the first approach.
You can do it all in the form definition.
I have made some simple scala classes and objects from your example.
models/Blog.scala
package models
/**
* #author maba, 2013-04-10
*/
case class User(id:Long)
case class Blog(id:Long, author:User)
case class Comment(id:Long, blog:Blog, comment:String)
object Blog {
def findById(id: Long): Option[Blog] = {
Some(Blog(id, User(1L)))
}
}
object Comment {
def create(comment: Comment) {
// Save to DB
}
}
controllers/Comments.scala
package controllers
import play.api.mvc.{Action, Controller}
import play.api.data.Form
import play.api.data.Forms._
import models.{Comment, Blog}
/**
* #author maba, 2013-04-10
*/
object Comments extends Controller {
val form = Form(
mapping(
"comment" -> nonEmptyText,
"blog" -> mapping(
"id" -> longNumber
)(
(blogId) => {
Blog.findById(blogId)
}
)(
(blog: Option[Blog]) => Option(blog.get.id)
).verifying("The blog does not exist.", blog => blog.isDefined)
)(
(comment, blog) => {
// blog.get is always possible since it has already been validated
Comment(1L, blog.get, comment)
}
)(
(comment: Comment) => Option(comment.comment, Some(comment.blog))
)
)
def index = Action { implicit request =>
form.bindFromRequest.fold(
formWithErrors => BadRequest,
comment => {
Comment.create(comment)
Ok
}
)
}
}

Scala Type Mismatch

I am having a problem with type mismatch.
type mismatch; found : Option[models.User] required: models.User
def authenticate = Action { implicit request =>
signinForm.bindFromRequest.fold(
formWithErrors => BadRequest(html.signin(formWithErrors)),
user => Redirect(routes.Application.active).withSession(Security.username -> User.getUserName(user))
)
}
How can I force the function to accept Option[models.User] or can I convert the models.User into an Option?
The error occurs here: User.getUserName(user). getUserName requires models.User types.
===============================================
Update with all code used:
From User.scala
def authenticate(email: String, password: String) : Option[User] = {
(findByEmail(email)).filter { (user => BCrypt.checkpw(password, user.password)) }
}
def findByEmail(email: String) : Option[User] = {
UserDAO.findOne(MongoDBObject("email" -> email))
}
From Application.scala
val signinForm = Form {
mapping(
"email" -> nonEmptyText,
"password" -> text)(User.authenticate)(_.map(user => (user.email, "")))
.verifying("Invalid email or password", result => result.isDefined)
}
def authenticate = Action { implicit request =>
signinForm.bindFromRequest.fold(
formWithErrors => BadRequest(html.signin(formWithErrors)),
user => Redirect(routes.Application.active).withSession(Security.username -> User.getUserName(user.get))
)
}
To de-option an Option[User] into a User, you can do one of the following:
1) The unsafe way. Only do this if you are sure that optUser is not None.
val optUser: Option[User] = ...
val user: User = optUser.get
2) The safe way
val optUser: Option[User] = ...
optUser match {
case Some(user) => // do something with user
case None => // do something to handle the absent user
}
3) The monadic safe way
val optUser: Option[User] = ...
optUser.map(user => doSomething(user))
The biggest thing is that, if it's possible that optUser might actually be None, you need to figure out what you actually want to happen in the case that there is no User object.
There's a lot more information about Option in other StackOverflow questions if you'd like to read more.

Scala + Play -> Type mismatch; found : anorm.RowParser Required: anorm.ResultSetParser[Option[models.User]]

SOLUTION: I could not figure our how to return the non-exists for of Option[User] so in the case of not user found I create a dummy user object and reason on it from the controller (feels awful but working...):
from Application.scala
val loginForm = Form(
tuple(
"email" -> text,
"password" -> text
) verifying ("Invalid email or password", result => result match {
case (email, password) => (User.authenticate(email, password).map{_.id}.getOrElse(0) != 0)
})
)
AS OPPOSED TO:
val loginForm = Form(
tuple(
"email" -> text,
"password" -> text
) verifying ("Invalid email or password", result => result match {
case (email, password) => User.authenticate(email, password).isDefined
})
)
++++++++++++++++++ ORIGINAL 2 ++++++++++++++++++
Thanks for the advice! I have made some change and seem to be getting closer however I can't figure out how to return an undefinded Option[user]. I have also tried case _ => null, See below:
From User.scala
case class User(id: Int, email: String, name: String, password: String)
object User {
// -- Parsers
/**
* Parse a User from a ResultSet
*/
val userParser = {
get[Option[Int]]("uid")~
get[Option[String]]("email")~
get[Option[String]]("fname")~
get[Option[String]]("pbkval") map {
case (uid~email~name~pbkval) => validate(uid,email, name, pbkval)
}
}
/**
* Retrieve a User from email.
*/
def findByEmail(email: String): Option[User] = {
DB.withConnection { implicit connection =>
SQL("select * from get_pbkval({email})").on(
'email -> email
).as(userParser.singleOpt)
}
}
/**
* Authenticated user session start.
*/
def authenticate(email: String, password: String): Option[User] = {
DB.withConnection { implicit connection =>
SQL(
"""
select * from get_pbkval({email})
"""
).on(
'email -> email
).as(userParser.singleOpt)
}
}
/**
* Validate entry and create user object.
*/
def validate(uid: Option[Int], email: Option[String], fname: Option[String], pbkval: Option[String]): User = {
val uidInt : Int = uid.getOrElse(0)
val emailString: String = email.getOrElse(null)
val fnameString: String = fname.getOrElse(null)
val pbkvalString: String = pbkval.getOrElse(null)
User(uidInt, emailString, fnameString, pbkvalString)
}
I guess it is clear that I am not really getting something fundamental here.. I have read through http://www.playframework.org/modules/scala-0.9.1/anorm and searched around for hours.. any help would be much appreciated!
You didn't specify which rows to map. After your row mapper, put a * to signify which rows to map. While you're at it, I find it easier to define my row mapper in a separate val. Something like this.
val user = {
get[Option[Int]]("uid")~
get[Option[String]]("email")~
get[Option[String]]("fname")~
get[Option[String]]("pbkval") map {
case uid~email~name~password => validate(uid,email, name, password)
}
}
def authenticate(email: String, password: String): Option[User] = {
DB.withConnection { implicit connection =>
SQL(
"""
select * from get_pbkval({email})
"""
).on(
'email -> email
).as(user *)
}
}
def validate(uid: Option[Int], email: Option[String], fname: Option[String], pbkval: Option[String]): Option[User] = {
if (uid != None) {
val uidInt : Int = uid.getOrElse(0)
val emailString: String = email.getOrElse(null)
val fnameString: String = fname.getOrElse(null)
val pbkvalString: String = pbkval.getOrElse(null)
User(uidInt, emailString, fnameString, pbkvalString)
} else { return null}
}
Note the "as" method now has two arguments, your row mapper (which is now defined as a val "user", and a "*" signifying that you want to map all of the rows.