Created
January 9, 2018 03:51
-
-
Save isaksky/1914aad2b41fe888343a80e28e4d5eb8 to your computer and use it in GitHub Desktop.
reframe - Request Effect
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
(def req-counter (atom 0)) | |
;; Not battle tested - adapted from an existing codebase | |
(rf/reg-fx | |
:request-giving-id | |
(fn [[request-id {:keys [on-complete resp-body-formatter request-args] | |
:or {on-complete identity | |
resp-body-formatter identity} | |
:as args}]] | |
(let [initial-req-counter @req-counter] | |
(swap! | |
re-frame.db/app-db | |
(fn [db] | |
(let [current-request (get-in db [:request-id->request request-id])] | |
;; Optional: Cancel existing xhr. Not needed/wanted for autocomplete | |
;; see below | |
(when-let [xhr (:xhr current-request)] (.abort xhr)) | |
;; Clobber existing state. Alternatively, keep it around if it is still | |
;; useful even when 'dirty', for autocomplete controls, for example | |
(assoc-in db [:request-id->request request-id] {:state :pending})))) | |
(let [xhr (request! | |
:path (:path request-args) | |
:request-body (:request-body request-args) | |
:method (:method request-args) | |
:on-http-success | |
(fn [txt] | |
;; Prevent slow old request from clobbering | |
;; request issued with fresher state | |
(when (= @req-counter initial-req-counter) | |
(let [req {:response (resp-body-formatter txt) | |
:request-state :complete}] | |
(swap! re-frame.db/app-db | |
(fn [db] | |
(assoc-in db [:request-id->request request-id] req))) | |
(on-complete req)) | |
(swap! req-counter inc))) | |
:on-http-error | |
(fn [error] | |
(when (= @req-counter initial-req-counter) | |
(let [req {:error error | |
:request-state :errored}] | |
(swap! re-frame.db/app-db | |
(fn [db] (assoc-in db [:request-id->request request-id] req))) | |
(on-complete req)) | |
(swap! req-counter inc))))] | |
(swap! re-frame.db/app-db | |
#(assoc-in % [:request-id->request request-id :xhr] xhr)))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment