Last active
August 29, 2015 14:02
-
-
Save coxchen/b6e7ca706a0f37a53031 to your computer and use it in GitHub Desktop.
Adopt Graph (Plumbing) for complex task definition in RestBot
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(use 'plumbing.core) | |
(require '[plumbing.graph :as graph]) | |
(use '[restbot core utils]) | |
(defn- make-task-graph | |
[specs serverSym authSym] | |
(reduce merge | |
(for [[specKey specParam specBody] (partition 3 specs)] | |
{specKey (cons 'fnk | |
(list (conj specParam serverSym authSym) | |
(list 'do! (list specBody | |
:server-url (list :url serverSym)) | |
:cookies (if-not (nil? authSym) (list :cookies authSym)))))}))) | |
(defmacro def-graph | |
[graphName & specs] | |
(let [server# (gensym 'server) | |
auth# (gensym 'auth) | |
no-op# (fn []) | |
tasks (make-task-graph specs server# auth#) | |
taskGraph (-> tasks | |
(assoc (keyword auth#) `(fnk [] (~no-op#))) | |
(with-meta {:auth-step (keyword auth#) | |
:server-key (keyword server#)}))] | |
`(do | |
(def ~graphName | |
~taskGraph)))) | |
(defn- extract-auth-step | |
[server] | |
(condp = (get-in server [:auth :type]) | |
:cookies (get-in server [:auth :req]) | |
nil)) | |
(defn exec! | |
[server taskGraph] | |
(let [serverUrl (server :url) | |
authStepKey ((meta taskGraph) :auth-step) | |
serverKey ((meta taskGraph) :server-key) | |
execGraph (if-let [auth-step (extract-auth-step server)] | |
(assoc taskGraph authStepKey (fnk [] (do! (auth-step :server-url serverUrl)))) | |
taskGraph)] | |
(into {} ((graph/compile execGraph) {serverKey server})))) | |
;;;;;;;;;; | |
(def-server github "https://api.github.com") | |
(def-api starred :GET "/users/{user}/starred") | |
(def-graph test-gh | |
:starred [] (starred)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment