Skip to content

Instantly share code, notes, and snippets.

@jaen

jaen/async.clj Secret

Created February 3, 2016 23:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jaen/6d9fdc0819ce662ba24b to your computer and use it in GitHub Desktop.
Save jaen/6d9fdc0819ce662ba24b to your computer and use it in GitHub Desktop.
(defrecord Async [dispatch-method ajax-post-fn handshake-fn send!]
component/Lifecycle
(start [component]
(log/info "Starting async with: " )
(let [dispatch-method (make-dispatch-method)
handlers (->> (vals component)
(filter #(satisfies? protocols/AsyncHandlerProvider %))
(mapcat protocols/-get-async-handlers))
{:keys [send! handshake-fn ajax-post-fn]} (start-async! dispatch-method)]
;(log/debug "HALF KEK: " (vals component))
;(log/debug "KEK: " (vec (filter #(satisfies? logic/AsyncHandlerProvider %) (vals component))))
(doseq [[dispatch-value handler] handlers]
(log/debug "Registering event handler for" dispatch-value)
(.addMethod ^MultiFn dispatch-method dispatch-value handler))
(.addMethod ^MultiFn dispatch-method :default
(fn [event] (log/debug "Unhandled event type: " (dissoc event :ev-msg))))
(assoc component :dispatch-method dispatch-method
:handshake-fn handshake-fn
:ajax-post-fn ajax-post-fn
:send! send!)))
(stop [component]
(when dispatch-method
(log/info "Stopping async.")
(dissoc component :dispatch-method :handshake-fn :ajax-post-fn :send!)))
protocols/WebServiceProvider
(-get-routes [_]
[["sente" {:get :async/handshake-fn
:post :async/ajax-post-fn}]])
(-get-handlers [this]
{:async/handshake-fn handshake-fn
:async/ajax-post-fn ajax-post-fn}))
(defn make [& [options]]
(map->Async {}))
(defrecord WebServer [environment options server application]
component/Lifecycle
(start [component]
(log/info "Starting webserver with: " options)
(let [[routes handlers] (->> (vals component)
(filter #(satisfies? protocols/WebServiceProvider %))
(map (juxt protocols/-get-routes protocols/-get-handlers))
(reduce (fn [[nums keys] [new-nums new-keys]]
[(concatv nums new-nums) (merge keys new-keys)])
[[] {}]))
_ (log/debug "ROUTES: " ["/" routes])
handler (build-ring-handler ["/" routes] handlers)
wrapped-handler (if (= environment :development)
(wrap-development handler)
handler)
server (immutant/run wrapped-handler options)]
(assoc component :server server)))
(stop [component]
(when server
(log/info "Stopping webserver.")
(immutant/stop server)
component)))
(component/system-map
:async (-> (async/make)
(component/using [:synchronisation]))
:web (-> (webserver/make immutant-params)
(component/using [:async])))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment