Skip to content

Instantly share code, notes, and snippets.

@coxchen
Last active August 29, 2015 14:03
Show Gist options
  • Save coxchen/611e5ec176d53b01e18e to your computer and use it in GitHub Desktop.
Save coxchen/611e5ec176d53b01e18e to your computer and use it in GitHub Desktop.
refactor API definition
(defprotocol ApiBuilder
(-req [this apiOpts]))
(defn- replace-with-param
[basestr param]
(clojure.string/replace basestr
(re-pattern (str "\\{" (name (first param)) "\\}"))
(str (second param))))
(defn apply-api-params
[apiUrl paramMap]
(reduce replace-with-param (into [apiUrl] paramMap)))
(defn update-url
[url params]
(if params
(apply-api-params url params)
url))
(defrecord Api [name method url headers body stream? resp validations]
ApiBuilder
(-req [this apiOpts]
(let [{:keys [params]} apiOpts
url (update-url (:url this) params)]
(map->Api (-> this
(merge {:url url})
(merge (hash-map apiOpts)))))))
(defn req [this & apiOpts] (-req this apiOpts))
(defmacro def-api2
[apiName apiMethod apiUrl & apiMore]
(let [;;{:keys [headers body validations stream?]} apiMore
apiKeyword (keyword apiName)]
`(do
(def ~apiName (map->Api (merge ~(apply hash-map apiMore)
{:name (str '~apiName) :method ~apiMethod :url ~apiUrl})))
;; (defn ~apiName [& apiOpts#]
;; (fn [& apiRuntime#]
;; (build-req ~apiName ~apiMethod ~apiUrl ~headers ~body ~validations ~stream? apiOpts# apiRuntime#)))
(swap! apis assoc ~apiKeyword {:name (str '~apiName)
:method ~apiMethod
:url ~apiUrl}))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment