restapi(2)- generic restful CRUD:通用的restful风格数据库表维护工具

   研究关于restapi的初衷是想搞一套通用的平台数据表维护http工具。前面谈过身份验证和使用权限、文件的上传下载,这次来到具体的数据库表维护。我们在这篇示范里设计一套通用的对平台每一个数据表的标准维护方式。http服务端数据表维护CRUD有几个标准的部分组成:Model,Repository,Route。我们先看看这几个类型的基类:

trait ModelBase[M,E] { def to: M => E def from: E => M } trait RepoBase[M] { def getById(id: Long) : Future[Option[M]] def getAll : Future[Seq[M]] def filter(expr: M => Boolean): Future[Seq[M]] def save(row: M) : Future[AnyRef] def deleteById(id: Long) : Future[Int] def updateById(id: Long, row: M) : Future[Int] } abstract class RouteBase[M](val pathName: String, repository: RepoBase[M])( implicit m: Manifest[M]) extends Directives with JsonConverter { val route = path(pathName) { get { complete(futureToJson(repository.getAll)) } ~ post { entity(as[String]) { json => val extractedEntity = fromJson[M](json) complete(futureToJson(repository.save(extractedEntity))) } } } ~ path(pathName / LongNumber) { id => get { complete(futureToJson(repository.getById(id))) } ~ put { entity(as[String]) { json => val extractedEntity = fromJson[M](json) complete(futureToJsonAny(repository.updateById(id, extractedEntity))) } } ~ delete { complete(futureToJsonAny(repository.deleteById(id))) } } }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zwggjf.html