Skip to content

Instantly share code, notes, and snippets.

@dimovich
Last active July 21, 2019 09:49
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 dimovich/3f9cd75a21e5073bffc703f2417b136d to your computer and use it in GitHub Desktop.
Save dimovich/3f9cd75a21e5073bffc703f2417b136d to your computer and use it in GitHub Desktop.
Handling Deferred responses for vanilla ring middleware
(require '[ring.middleware.session]
'[manifold.deferred :as d])
(defn wrap-ring-async-handler
"Converts given asynchronous Ring handler to Aleph-compliant handler."
[handler]
(fn [request]
(let [response (d/deferred)]
(handler request #(d/success! response %) #(d/error! response %))
response)))
(defn wrap-deferred-handler
"Chains the Deferred response of handler to respond and raise callbacks."
[handler]
(fn [request respond raise]
(-> (d/chain (handler request)
respond)
(d/catch raise))))
(defn ring-handler [request]
(d/success-deferred {:body "hello"}))
(def handler
(-> ring-handler
wrap-deferred-handler
ring.middleware.session/wrap-session
;; ... other middleware ...
wrap-ring-async-handler))
(handler {:some :request})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment