grub-fork/src-clj/grub/db.clj

60 lines
1.8 KiB
Clojure
Raw Normal View History

(ns grub.db
(:require [grub.async :refer [go-loop]]
[monger.core :as m]
[monger.collection :as mc]
[monger.operators :as mo]
[clojure.core.async :as async :refer [<! >! >!! chan go close! timeout]]))
(def grub-collection "grubs")
2013-08-17 10:05:05 +00:00
(def incoming-events (atom nil))
(defmulti handle-event :event :default :unknown-event)
(defmethod handle-event :create [event]
(let [grub (-> event
(select-keys [:_id :grub])
(assoc :completed false))]
2013-08-17 10:05:05 +00:00
(when (and (:_id grub) (:grub grub)) (mc/insert grub-collection grub))))
(defmethod handle-event :complete [event]
(mc/update grub-collection
{:_id (:_id event)}
{mo/$set {:completed true}}))
(defmethod handle-event :uncomplete [event]
(mc/update grub-collection
{:_id (:_id event)}
{mo/$set {:completed false}}))
(defmethod handle-event :delete [event]
(mc/remove grub-collection {:_id (:_id event)}))
(defmethod handle-event :unknown-event [event]
(println "Cannot handle unknown event:" event))
2013-08-17 10:05:05 +00:00
(defn handle-incoming-events! []
(reset! incoming-events (chan))
(go-loop (let [event (<! @incoming-events)]
(handle-event event))))
(defn get-current-grubs-as-events []
(let [grubs (mc/find-maps grub-collection)
sorted-grubs (sort-by :_id (vec grubs))
out (chan)]
(go (doseq [grub sorted-grubs]
(let [grub-event (-> grub
(select-keys [:_id :grub :completed])
2013-08-06 20:38:53 +00:00
(assoc :event :add))]
(>! out grub-event))))
out))
2013-08-17 10:05:05 +00:00
(def default-db "grub")
2013-08-17 10:05:05 +00:00
(defn connect-and-handle-events
([] (connect-and-handle-events default-db))
([db-name]
(handle-incoming-events!)
(m/connect!)
(m/set-db! (m/get-db db-name))))