简体   繁体   English

如何在Scala Akka-http中定义通用路由

[英]How can I define generic routing in scala akka-http

I wanted to create the reusable the generic routing in Scala Akka-HTTP so that I could use same generic routing for rest of the routing I defined. 我想在Scala Akka-HTTP中创建可重用的通用路由,以便可以将相同的通用路由用于我定义的其余路由。

So far, I could define routing as below that works perfectly. 到目前为止,我可以定义如下的完美路由。

class TestApi(val modules: Configuration with PersistenceService)(implicit executionContext: ExecutionContext) extends BaseApi with CirceSupport {
  override val oauth2DataHandler = modules.oauth2DataHandler

  val userDao = new TestService
  val testApi = pathPrefix("auth") {
    path("users") {
      pathEndOrSingleSlash {
        get {
          authenticateOAuth2Async[AuthInfo[OauthAccount]]("realm", oauth2Authenticator) {
            //auth => complete(userService.getAll().map(_.asJson))
            auth => complete(userDao.getAll().map(_.asJson))
          }
        }
      }
    } ~
    path("allUsers") {
      pathEndOrSingleSlash {
        post {
          entity(as[UserEntity1]) { userUpdate =>
            authenticateOAuth2Async[AuthInfo[OauthAccount]]("realm", oauth2Authenticator) {
              //auth => complete(userService.getAll().map(_.asJson))
              auth => complete(userDao.getAll().map(_.asJson))
            }
          }
        }
      }
    }
  } ~
    path("user" / "upload" / "file") {
      pathEndOrSingleSlash {
        post {
          entity(as[Multipart.FormData]) { fileData =>
            authenticateOAuth2Async[AuthInfo[OauthAccount]]("realm", oauth2Authenticator) {
              auth => {
                val fileName = UUID.randomUUID().toString
                val temp = System.getProperty("java.io.tmpdir")
                val filePath = "/var/www/html" + "/" + fileName
                complete (
                  FileHandler.processFile(filePath,fileData).map { fileSize =>
                    ("success", fileSize)
                    //HttpResponse(StatusCodes.OK, entity = s"File successfully uploaded. File size is $fileSize")
                  }.recover {
                    case ex: Exception => ("error", 0) //HttpResponse(StatusCodes.InternalServerError, entity = "Error in file uploading")
                  }.map(_.asJson)
                )
              }
            }
          }
        }
      }
    }
}

Here in the code I find pathEndOrSingleSlash and 在代码中,我找到pathEndOrSingleSlash

authenticateOAuth2Async[AuthInfo[OauthAccount]]("realm", oauth2Authenticator) {            
    auth => ...
}

repetative. 重复的。

I would like to get something like below to work with. 我想得到以下类似的东西。

get(url, function)
post(url, function)
put(url, function)

So that I could reuse the repetative code. 这样我就可以重复使用重复的代码。 How could I achieve the generic routing as defined? 如何实现定义的通用路由?

You can extract the authenticateOAuth2Async , path , and pathEndOrSingleSlash directives by using functional composition. 您可以使用功能组合来提取authenticateOAuth2AsyncpathpathEndOrSingleSlash指令。 You can write a higher order function that will provide the "common" framework and then calls a function that provides the particular functionality: 您可以编写一个高阶函数来提供“通用”框架,然后调用一个提供特定功能的函数:

def commonRoute(p : String, subRoute : AuthInfo[OauthAccount] => Route) = 
  authenticateOAuth2Async[AuthInfo[OauthAccount]]("realm", oauth2Authenticator) { auth =>
    path(p) {
      pathendOrSingleSlash {
        subRoute(auth)
      }
    }
  }

This can then be applied to your particular cases: 然后可以将其应用于您的特定情况:

//example code doesn't use the auth variable anywhere, thus the "_ =>"
val getRoute : AuthInfo[OauthAccount] => Route = 
  _ =>
    get {
      complete(userDao.getAll().map(_.asJson))
    }

val postAllUsersRoute : AuthInfo[OauthAccount] => Route =
  _ =>
    post {
      entity(as[UserEntity1]) { userUpdate =>
        complete(userDao.getAll().map(_.asJson)
      }
    }

And then combined to form your final Route : 然后合并形成您的最终Route

val testApi = pathPrefix("auth") {
  commonRoute("users", getRoute) ~ commonRoute("allUsers", postAllUersRoute)
}

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

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