我有基于JSON和play框架的scala REST服务。我有用户案例类
case class User(_id: BSONObjectID, username: String,password: String,creationTime: org.joda.time.DateTime)
和
object User{
val userReads: Reads[User] = (
(JsPath \ "username").read[String] (minLength[String](4) keepAnd maxLength[String] (32) ) and
(JsPath \ "password").read[String] (minLength[String](8) keepAnd maxLength[String] (32) )
?????)(User.apply _)
val userWrites: Writes[User] = ....
implicit val userFormat: Format[User] = Format (userReads, userWrites)
}
在注册期间(通过REST API),我需要验证传入的json。我只需要用户名和密码,我不需要_id,creationTime等。如何正确写入读取,写入只验证字段的子集(请完成读取和重放" ?????&# 34;关于你的代码)?
答案 0 :(得分:2)
定义一个单独的class
,让我们说RegistrationUser
并为此class
定义JSON读取和写入:
case class RegistrationUser(userName: String, password: String)
在DB层中,您可以拥有如下类:
case class DbUser(_id: BSONObjectID,
username: String,
password: String,
creationTime: org.joda.time.DateTime)
然后你可以像这样在这些类之间进行映射:
def saveUserToDb(registrationUser: RegistrationUser): Unit = {
val dbUser = DbUser(
_id = BSONObjectID.generate,
username = registrationUser.username,
password = registrationUser.password,
creationTime = DateTime.now
)
// Now you have your DbUser and you can save it to Mongo as you did before
}
您不必在整个应用程序中使用相同的模型。为各个层提供单独的模型是非常有效的 - UI,服务,数据库......