0

如何尽可能地折叠这些指令?

我能够将三个指令折叠到 mainHeader 中,但是如何也包括 authenticate 和 responseWithMediaType 呢?

val mainHeaders = cors & headerValueByName("Access_Token") & headerValueByName("Tenant_Name")

override def getLayer = path("api" / Segment / "model" / "layers") { modeledSystemName =>
    mainHeaders { (accessToken, tenantName) =>
      authenticate(validate(accessToken)) { authInfo =>
        respondWithMediaType(`application/json`) {
          get {
            onComplete(service.getlayers(modeledSystemName, tenantName)) {
              case Success(layers) => complete(layers)
              //case Success(None) => complete(NotFound, "Release version not found")
              case Failure(ex) => complete(InternalServerError, s"An error occurred: ${ex.getMessage}")
            }
          }
        }
      }
    }
  }
4

1 回答 1

2

喷涂路线超级组合,因此您可以随心所欲。例如,我会这样写这条路线:

val authWithHeader = headerValueByName("Access_Token")
  .flatMap(accessToken => authenticate(validate(accessToken)))

val authenticatedJsonRoute = cors &
  authWithHeader &
  headerValueByName("Tenant_Name") &
  respondWithMediaType(MediaTypes.`application/json`)

override val getLayer =
  (get & path("api" / Segment / "model" / "layers")) { modeledSystemName =>
    authenticatedJsonRoute { (authInfo, tenantName) =>
      onComplete(service.getlayers(modeledSystemName, tenantName)) {
        case Success(layers) => complete(layers)
        //case Success(None) => complete(NotFound, "Release version not found")
        case Failure(ex) => complete(InternalServerError, s"An error occurred: ${ex.getMessage}")
      }
    }
  }

让我解释一下这段代码。首先,我创建了读取标头值的指令authWithHeader,然后使用该值进行身份验证。它超级简单,所有魔术都由flatMap.

然后,我创建了authenticatedJsonRoute它只是其他简单指令的组合。组合魔术是用&运算符完成的(我在这种情况下将其发音为“然后”)并且这些指令将按顺序执行。

最后,我authenticatedJsonRoute在完整的路线中使用了我的组合指令 , getLayer

于 2016-01-25T09:36:08.310 回答