http - 如何在 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?
,但是,我不确定如何编写其余代码......
解决方案
你可能想要这样的东西:
(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 备忘单!
推荐阅读
- sql - 根据查询结果查询设置变量
- python - shell_exec 执行不好
- ide - 在哪里使用 Nim (linux) 编程?
- javascript - JavaScript 函数将打开 div 标签;然而,第二个 JavaScript 函数不会关闭它
- r - 如何计算r中一组中一个值与所有其他值之间的平均差异
- jquery - 将动态href url更改为jquery中的另一个值
- r - 在 dplyr mutate 中返回多列
- android - 默认 FirebaseApp 未在此进程 com.myapp 中初始化。确保首先调用 FirebaseApp.initializeApp(Context)
- jquery - Wordpress Ajax POST 错误 403 admin-ajax.php
- javascript - 当输入中有文本时,如何切换元素上的类?