Skip to content

Instantly share code, notes, and snippets.

@sido378
Last active February 26, 2017 20:40
Show Gist options
  • Save sido378/0676b4ae6e264a73cc18737aa9496c69 to your computer and use it in GitHub Desktop.
Save sido378/0676b4ae6e264a73cc18737aa9496c69 to your computer and use it in GitHub Desktop.
(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)))
@sido378
Copy link
Author

sido378 commented Feb 26, 2017

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")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment