Last active
February 26, 2017 20:40
-
-
Save sido378/0676b4ae6e264a73cc18737aa9496c69 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
(ns facebook-example.database | |
(:gen-class) | |
(:require [clojure.java.io :as io] | |
[clojure.data.json :as json])) | |
(defn load-db [] | |
(if-let [data (slurp (io/file (io/resource "database.json")))] | |
(try (json/read-str data :key-fn keyword) | |
(catch Exception e {})))) | |
(defn write-db [data] | |
(with-open [out-file (io/writer "./resources/database.json" :encoding "UTF-8")] | |
(.write out-file (json/write-str data))) | |
data) | |
(defn read [key] | |
((keyword key) (load-db)) | |
(defn save [key value] | |
(as-> (load-db) data | |
(assoc data (keyword key) value) | |
(write-db data))) | |
(defn save-in [keys value] | |
(as-> (load-db) data | |
(assoc-in data (map keyword keys) value) | |
(write-db data))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Setup:
create an empty file "database.json" in your resources directory
add [facebook-example.database :as db] to your :require statement at the beginning of your bot.clj
Usage:
(db/read sender-id)
(db/save sender-id {"state" "new User"})
(db/save-in [sender-id "state"] "old user")