2017-04-18 71 views
0

我對scala中的函數式編程相對較新。我遇到了流動的方法。我一直無法弄清楚它在做什麼?作爲使用scala語法的參數的函數

def getPostsByFilters = (authenticatedPublicApiPostArticleAction andThen rateLimitedApiAction).async(BodyParsers.parse.tolerantJson) { implicit request => 
    implicit val apiKey = Some(request.apiKey) 
    request.body.validate[ArticlePostQuery] fold(
     errors => futureBadRequest(errors.toString()), 
     articleQuery => verifyPostQueryParams(articleQuery, verifiedApiRequest => { 
     val PostsNetwork = PostsNetwork(true, verifiedApiRequest.contentType, verifiedApiRequest.orderBy) 
     apiArticleService.findApiArticlesWithPostRequest(verifiedApiRequest, PostsNetwork) map (articles => wrapUpResultsToJson(ApiPosts(articles))) 
     })) 
    } 

它是在一個玩API控制器和方法被映射到在該路由文件POST請求。

我知道它需要一個json發佈請求並返回一個json響應,但是有人可以解釋實際發生的事情,以及是否有方法來重構它以使其更具可讀性?

回答

2

免責聲明:我不熟悉這段代碼。我的回覆是試圖幫助破譯方法調用,試圖幫助您更好地理解它。

這種方法似乎在做一些事情。

  1. 認證和速率限制 - 這是由

    authenticatedPublicApiPostArticleAction andThen rateLimitedApiAction 
    

    andThen用於從左至右撰寫功能來完成。因此,首先驗證正在做,然後速率限制

  2. Asynchrnous JSON解析:

    async(BodyParsers.parse.tolerantJson) 
    

    試圖解析HTTP請求的身體作爲一個JSON關於在Content-Type頭通過。

  3. 驗證身體:

    request.body.validate[ArticlePostQuery] 
    

    這似乎是驗證體(JSON)的ArticlePostQuery結構(我假定這樣的情況類)相匹配。 驗證方法返回JsResult,這是一個ADT(代數數據類型),它可以是JsSuccessJsErrorfold方法用於處理錯誤案例(第一個函數)或成功案例(第二個函數)。奉結果

  4. 如果是前者發生時,API返回的錯誤狀態代碼(我假設某種與錯誤400錯誤的請求:

    errors => futureBadRequest(errors.toString()) 
    

    如果後者發生這試圖驗證所有的查詢參數存在:

    articleQuery => verifyPostQueryParams(articleQuery, verifiedApiRequest 
    

    如果它們確實存在,它調用下面的thunk:

    val PostsNetwork = 
        PostsNetwork(
        true, 
        verifiedApiRequest.contentType, 
        verifiedApiRequest.orderBy 
    ) 
    
    apiArticleService 
        .findApiArticlesWithPostRequest(verifiedApiRequest, PostsNetwork) 
        .map(articles => wrapUpResultsToJson(ApiPosts(articles))) 
    })) 
    

    檢索文章帖子。然後,它將映射到結果上以返回ApiPosts對象的JSON結果。