Last active
April 28, 2017 16:17
-
-
Save roman01la/d4e5acc08fb5b455438fe84255933ab0 to your computer and use it in GitHub Desktop.
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
(defmulti control (fn [action] action)) | |
(defmethod control :init [_ _ _] | |
{:state {:count 0}}) ;; <= initial state effect | |
(defmethod control :inc [_ _ state] | |
{:state (update state :count inc)}) ;; <= increment state effect | |
(defmethod control :load [_ [id] _] | |
{:http {:uri (str "/api/count/" id) | |
:on-success :load-ready | |
:on-fail :load-fail}}) ;; <= HTTP effect | |
(defmethod control :load-fail [_ [error] state] | |
{:state (assoc state :error error)}) ;; <= load error state effect | |
(defmethod control :load-ready [_ [response] state] | |
{:state (assoc state :count response)}) ;; <= load success state effect | |
(defmethod control :persist [_ _ state] | |
{:local-storage {:method :set | |
:key :my-app/counter | |
:data (-> state clj->js js/JSON.stringify)}}) ;; <= persist localStorage effect | |
(defmethod control :read-persist [_ _ _] | |
{:local-storage {:method :get | |
:key :my-app/counter | |
:on-read :read-persist-ready}}) ;; <= read persist localStorage effect | |
(defmethod control :read-persist-ready [_ [data] state] | |
{:state (->> data js/JSON.parse js->clj)}) ;; <= read persist localStorage success effect | |
;; =========================== | |
(def r | |
(scrum/reconciler | |
{:state (atom {}) | |
:controllers {:counter counter/control}} | |
:effects {:http effects/http | |
:local-storage effects/local-storage})) | |
(scrum/broadcast-sync! :init) | |
(scrum/dispatch! :counter :load 5) | |
;; =========================== | |
(defn http [reconciler controller {:keys [uri on-success on-fail]}] | |
(-> (httpurr/get uri) | |
(p/then #(scrum/dispatch! reconciler controller on-success %)) | |
(p/catch #(scrum/dispatch! reconciler controller on-fail %)))) | |
(defn local-storage [reconciler controller {:keys [method key data on-read]}] | |
(case method | |
:set (js/localStorage.setItem (str key) data) | |
:get (->> (js/localStorage.getItem (str key)) (scrum/dispatch! reconciler controller on-read)) | |
nil)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Line 18 why not simply return response ? In this proposal, the
control
controller isn't responsible directly for the state at the key:counter
? What is the value of thestate
parameter in the controller methods ?