Clojure/LISP REST客户端设计

Sib*_*ibi 3 lisp clojure

从OOP背景来看,我对Clojure中推荐的API设计方法存有疑问.例如,在OOP语言(这里是Python)中,为了使用某些API,我会这样做:

api = someWebService()
api.setWriteApiKey(WRITE_API_KEY)
api.sampleloadSong('file.mp3')
Run Code Online (Sandbox Code Playgroud)

在上面的示例中,我设置了一次API密钥并一次又一次地调用关联的方法,而无需再次传递API密钥.在Clojure或任何其他LISP系列语言中推荐的方法是什么?

我是否需要在每个函数调用中传递密钥,如下所示:

(sampleloadSong "WRITE_API_KEY" "file.mp3")
Run Code Online (Sandbox Code Playgroud)

或者还有其他更好的方法.

Art*_*ldt 5

为了防止您描述的重复问题,您可以创建一个返回记住键的api函数的函数(关闭它们)

(defn make-client [key] (partial api key))
Run Code Online (Sandbox Code Playgroud)

然后在你的程序中:

(let [api-fn (make-client WRITE_API_KEY)]
  (api-fn :sample-song "song.mp3")
  ...
  (api-fn  :delete-song "other-song.mp3"))
Run Code Online (Sandbox Code Playgroud)

虽然很多人认为最好将配置映射作为每个api调用的第一个参数.

 (api {:key WRITE_API_KEY} ....)
Run Code Online (Sandbox Code Playgroud)

还有另一种常见方法,人们将密钥定义为动态可绑定符号,并要求调用者适当地绑定它:

(def *api-key* :unset)

(defn api .... use *api-key* )
Run Code Online (Sandbox Code Playgroud)

来自调用者的命名空间:

(binding [*api-key* WRITE_API_KEY]
   (api :add-song "foo.mp3"))
Run Code Online (Sandbox Code Playgroud)

这种方法可能不像以前那么流行,我个人倾向于传递配置图,尽管这只是我的观点.