I have been in the process of learning a new database. Boy are these interesting.
I have been able to save data using a multimethod!
(defmulti save (fn [game db-type] db-type))
(defmethod save :edn [game db-type]
(->> game
(swap! log-edn assoc (:game-id game))
pr-str
(spit "log.edn")))
(defmethod save :json [game db-type]
(->> game
(swap! log-edn assoc (:game-id game))
json/write-str
(spit "log.json")))
This is quite useful and pretty amazing.
Now the interesting part has been retrieving the data. From what I have collected it is not so easy to retrieve the exact data that was placed in JSON. This makes things complicated.
Initially I assumed it would be data in is the data out.
(defmulti fetch-the-games (fn [db-type] db-type))
(defmethod fetch-the-games :edn [_db-type]
(let [log-edn (slurp "log.edn")]
(if (empty? log-edn) {} (edn/read-string log-edn))))
(defmethod fetch-the-games :json [_db-type]
(let [log-json (slurp "log.json")]
(if (empty? log-json) {} (json/read-str log-json :key-fn keyword))))
So I created this multimethod to retrieve the data. Let me show you what this brings back.
(json/write-str {:a 1 :b 2})
;;=> "{\"a\":1,\"b\":2}"
(json/read-str "{\"a\":1,\"b\":2}")
;;=> {"a" 1, "b" 2}
(json/read-str "{\"a\":1,\"b\":2}"
:key-fn keyword)
;;=> {:a 1, :b 2}
Upon seeing this I believed I found the way to get my precious data completely. However if you save something like {:a :example :b :example2}
and use the :key-fn
keyword, you will receive back `{:a “example” :b “example2”}.
Alas I am still at this point. Hopefully soon I will be able to overcome this obstacle and continue playing Tic Tac Toe.
Best,
Merl