-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathfirebase.cljs
More file actions
43 lines (37 loc) · 1.24 KB
/
firebase.cljs
File metadata and controls
43 lines (37 loc) · 1.24 KB
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
(ns bg.firebase
(:require [cljsjs.firebase]
[re-frame.core :as rf]
[clojure.string :as string]
[cljs.reader :as reader]))
(defn init []
(js/firebase.initializeApp
#js {:apiKey "<API_KEY>"
:authDomain "<PROJECT_ID>.firebaseapp.com"
:databaseURL "https://<DATABASE_NAME>.firebaseio.com"
:projectId "<PROJECT_ID>FROM THE FIREBASE UI"
:storageBucket "<BUCKET>.appspot.com"
:messagingSenderId "<SENDER_ID>"}))
(defn db-ref [path]
(.ref (js/firebase.database) (string/join "/" path)))
(defn save! [ref data]
(.set ref (pr-str data)))
(defn subscribe [path]
(.on path "value"
(fn [snapshot]
(when-let [d (.val snapshot)]
(rf/dispatch [:sync (reader/read-string d)])))))
(rf/reg-fx
:firebase/subscribe
(fn [{:keys [game-id default]}]
(let [ref (db-ref [game-id])]
(.once ref "value"
(fn received [snapshot]
(subscribe ref)
(if-let [data (.val snapshot)]
(rf/dispatch [:sync (reader/read-string data)])
(do (save! ref default)
(rf/dispatch [:sync default]))))))))
(rf/reg-fx
:firebase/set
(fn [{:keys [game-id data]}]
(save! (db-ref [game-id]) data)))