简体   繁体   English

如何取消喷涂指令

[英]How to collapse of Spray Directives

How can one collapse these directives as much as possible? 一个人如何尽可能地使这些指令崩溃?

I was able to collapse three directives into mainHeader but how can include authenticate and responseWithMediaType as well? 我能够将三个指令折叠到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}")
            }
          }
        }
      }
    }
  }

Spray routes are super compossible so you can do whatever you want. 喷涂路线非常复杂,因此您可以做任何想做的事情。 For example I would write this route like this: 例如,我将这样写这条路线:

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}")
      }
    }
  }

Let me explain this code. 让我解释一下这段代码。 First, I created the directive authWithHeader that reads header value and then do authentication with this value. 首先,我创建了指令authWithHeader ,该指令读取标头值,然后使用该值进行身份验证。 It is super simple and all magic done by flatMap . 它非常简单,并且所有的魔术都由flatMap完成。

Then, I created authenticatedJsonRoute which is just a composition of other simple directives. 然后,我创建了authenticatedJsonRoute ,它只是其他简单指令的组合。 Composition magic is done with & operator (I pronounce it as "and then" in this context) and those directives will be executed in order. 合成魔术是通过&运算符完成的(在这种情况下,我将其发音为“然后是”),并且这些指令将按顺序执行。

Lastly, I used my composed directive, authenticatedJsonRoute , in a complete route getLayer . 最后,我在完整的路由getLayer使用了我的组合指令authenticatedJsonRoute

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM