仅公开 REST JSON 服务中的字段子集。玩框架,scala
Expose only field subset in REST JSON Service. Play framework, scala
我有基于 JSON 和 play 框架的 scala REST 服务。我有用户案例 class
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 等。如何正确编写读取、写入以仅验证字段的子集(请完成读取并在您的代码中替换“??????”)?
定义一个单独的 class
,比方说 RegistrationUser
并为此 class
定义 JSON 读取和写入:
case class RegistrationUser(userName: String, password: String)
在数据库层你可以有这样的class:
case class DbUser(_id: BSONObjectID,
username: String,
password: String,
creationTime: org.joda.time.DateTime)
然后您可以像这样在这些 class 之间映射:
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、服务、数据库、...
我有基于 JSON 和 play 框架的 scala REST 服务。我有用户案例 class
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 等。如何正确编写读取、写入以仅验证字段的子集(请完成读取并在您的代码中替换“??????”)?
定义一个单独的 class
,比方说 RegistrationUser
并为此 class
定义 JSON 读取和写入:
case class RegistrationUser(userName: String, password: String)
在数据库层你可以有这样的class:
case class DbUser(_id: BSONObjectID,
username: String,
password: String,
creationTime: org.joda.time.DateTime)
然后您可以像这样在这些 class 之间映射:
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、服务、数据库、...