首页 > 解决方案 > 如何在 Clojure 中调用分页的 REST API?

问题描述

我正在尝试将一些工作的 Ruby 代码转换为调用分页 REST API 并累积数据的 Clojure。Ruby 代码最初基本上是调用 API,检查是否有pagination.hasNextPage密钥,并将pagination.endCursor用作查询字符串参数,以便在while循环中完成的下一个 API 调用。这是简化的Ruby 代码(删除了日志记录/错误处理代码等):

def request_paginated_data(url)
  results = []

  response = # ... http get url
  response_data = response['data']

  results << response_data

  while !response_data.nil? && response.has_key?('pagination') && response['pagination'] && response['pagination'].has_key?('hasNextPage') && response['pagination']['hasNextPage'] && response['pagination'].has_key?('endCursor') && response['pagination']['endCursor']
    response = # ... http get url + response['pagination']['endCursor']
    response_data = response['data']

    results << response_data
  end

  results

end

这是我的 Clojure 代码的开头:

(defn get-paginated-data [url options]
  {:pre [(some? url) (some? options)]}
  (let [body (:body @(client/get url options))]
    (log/debug (str "body size =" (count body)))
    (let [json (json/read-str body :key-fn keyword)]
      (log/debug (str "json =" json))))
      ;; ???
      )

我知道我可以clojure.lang.PersistentArrayMap使用json 在 json 中查找一个键contains?,但是,我不确定如何编写其余代码......

标签: httpfunctional-programmingclojurepagination

解决方案


你可能想要这样的东西:

(let [data    (json/read-str body :key-fn keyword)
      hnp     (get-in data [:pagination :hasNextPage])
      ec      (get-in data [:pagination :endCursor])
      continue? (and hnp ec)  ]
  (println :hnp hnp)
  (println :ec ec)
  (println :cont continue?)

...)

拉出嵌套位并打印一些调试信息。仔细检查 json 到 clojure 的转换是否按预期获得了“CamelCase”关键字,并在必要时进行修改以匹配。


您可能会发现我最喜欢的模板项目很有帮助,尤其是最后的文档列表。请务必阅读 Clojure 备忘单!


推荐阅读