[英]Scala + Reactivemongo: Controling custom readers/writers for REST-API
我正在研究在Scalatra中实现的REST-API,并使用reactmongo。 我的持久性模型是使用案例类实现的,而薄存储库层则通过DocumentReader / DocumentWriter(通过案例类伴随对象中的隐式转换器)对bson <->类映射使用通用方法。
case class Address(street: String, number: String, city: String, zip: String)
object Address{
implicit val addressHandler = Macros.handler[Address]
implicit val addressFmt = Json.format[Address]
}
第一个格式化程序将bson映射到case类,第二个格式化程序将其转换为json类(REST-API的输出格式)。
一切都很好,我对所有组件的集成程度非常满意。
不过,在许多情况下,我不需要对域对象(案例类实例)进行操作,而只想将来自数据库写入的数据流传输到http响应中。 在这些情况下,所有中间转换都是开销。 我还想控制公开哪些字段(我曾经在Java项目中使用过Yoga和Jackson)。
对此的可能解决方案是:
我想知道最好的方法是什么,是否有人在特定情况下有经验。 也许我什至错过了另一个不错的选择? 反馈非常欢迎。
要控制公开哪些字段,您可能必须编写一个Readers和Writers。 下面是从该项目https://github.com/luongbalinh/play-mongo中提取的示例。
import java.time.ZonedDateTime
case class User(override val id: Option[Long] = None,
firstName: String,
lastName: String,
age: Int,
active: Boolean,
createdDate: Option[ZonedDateTime] = None,
updatedDate: Option[ZonedDateTime] = None
) extends IdModel[User] {
override def withNewId(id: Long): User = this.copy(id = Some(id))
}
object User {
import play.api.libs.functional.syntax._
import play.api.libs.json._
implicit val userReads: Reads[User] = (
(JsPath \ "id").readNullable[Long] and
(JsPath \ "firstName").read[String] and
(JsPath \ "lastName").read[String] and
(JsPath \ "age").read[Int] and
(JsPath \ "active").read[Boolean] and
(JsPath \ "createdDate").readNullable[ZonedDateTime] and
(JsPath \ "updatedDate").readNullable[ZonedDateTime]
)(User.apply _)
implicit val userWrites: Writes[User] = (
(JsPath \ "id").writeNullable[Long] and
(JsPath \ "firstName").write[String] and
(JsPath \ "lastName").write[String] and
(JsPath \ "age").write[Int] and
(JsPath \ "active").write[Boolean] and
(JsPath \ "createdDate").writeNullable[ZonedDateTime] and
(JsPath \ "updatedDate").writeNullable[ZonedDateTime]
)(unlift(User.unapply))
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.