-
-
Notifications
You must be signed in to change notification settings - Fork 42
/
re_frame.cljs
64 lines (53 loc) · 2.13 KB
/
re_frame.cljs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
(ns martian.re-frame
(:require [cljs.core.async :refer [<!]]
[martian.core :as martian]
[martian.cljs-http :as martian-http]
[re-frame.core :as re-frame])
(:require-macros [cljs.core.async.macros :refer [go]]))
(defn- ->event [handler & args]
(into (if (vector? handler) handler [handler]) args))
(re-frame/reg-fx
::request
(fn [[m operation-id params on-success on-failure]]
(go
(try
(if-let [response-chan (martian/response-for m operation-id params)]
(let [{:keys [error-code] :as response} (<! response-chan)]
(if (= :no-error error-code)
(re-frame/dispatch (->event on-success response operation-id params))
(re-frame/dispatch (->event on-failure response operation-id params))))
(re-frame/dispatch (->event on-failure :unknown-route operation-id params)))
(catch js/Error e
(re-frame/dispatch (->event on-failure e operation-id params)))
(finally
(re-frame/dispatch [::on-complete [operation-id params on-success on-failure]]))))))
(re-frame/reg-event-db
::init
(fn [db [_ martian]]
(assoc db ::martian {:m martian
:pending #{}})))
(defn instance [db & _]
(get-in db [::martian :m]))
(re-frame/reg-event-db
::on-complete
(fn [db [_ req]]
(update-in db [::martian :pending] disj req)))
(defn- do-request [{:keys [db]} [_ operation-id params on-success on-failure]]
(let [request-key [operation-id params on-success on-failure]]
(if (contains? (get-in db [::martian :pending]) request-key)
{:db db}
{:db (update-in db [::martian :pending] conj request-key)
::request [(instance db) operation-id params on-success on-failure]})))
;; deprecated, use ::request instead
(re-frame/reg-event-fx :http/request do-request)
(re-frame/reg-event-fx ::request do-request)
(re-frame/reg-sub
::instance
instance)
(re-frame/reg-sub
::pending-requests
(fn [db]
(get-in db [::martian :pending])))
(defn init [swagger-url & [params]]
(go (let [martian (<! (martian-http/bootstrap-openapi swagger-url params))]
(re-frame/dispatch-sync [::init martian]))))