【问题标题】:Propagate / delegate path value to child routes akka http将路径值传播/委托给子路由 akka http
【发布时间】:2016-10-11 22:53:49
【问题描述】:

我想要一个接收IntNumber 的基本路由,并与数据库进行一些检查以了解值是否正确,然后如果值正确,我想将该值传播到子路由。

基本路线

class BaseServiceRoute extends PathDirectives with SecurityDirectives {

  val baseUserRoute = pathPrefix("user" / IntNumber)

}

如何对值 IntNumber 进行一些检查并将值委托给子路由?指令?

儿童路线

class CategoryServiceRoute(implicit executionContext: ExecutionContext) extends BaseServiceRoute {

val route = baseUserRoute { userId =>
  pathPrefix("category") {
    pathEndOrSingleSlash {
      get {
        complete(s"$userId")
      }
    } ~
      path(LongNumber) { categoryId =>
        get {
          complete(s"$categoryId")
        } ~
          post {
            complete("Hello category post")
          }
      }
     }
    }
   }

谢谢

【问题讨论】:

    标签: scala akka spray akka-http


    【解决方案1】:

    最佳实践建议只是嵌套路由,以便您仍然可以像这样从外部路由访问值:

    pathPrefix("user" / IntNumber) { userId =>
      pathPrefix("category") {
        pathEndOrSingleSlash {
          get {
            complete(s"$userId")
          }
        }
      }
    }
    

    但是,您似乎想将路线分成多个部分,这很好。在这种情况下,只需将子路由设为def:

    def childRoute(userId: Int): Route =
      pathPrefix("category") {
        pathEndOrSingleSlash {
          get {
            complete(s"$userId")
          }
        }
      }
    

    然后像这样使用它:

    baseUserRoute(childRoute)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-17
      • 1970-01-01
      相关资源
      最近更新 更多