Created
September 27, 2017 19:26
-
-
Save serialhex/751659194cb0d61345e1aeab2ce3ade0 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
defmodule Foobot.Repo do | |
# use JSON and some awesomesauce to make a database of sorts. | |
# in-memory it will be just a map... | |
# on disk JSON | |
# reads simply read all the data, writes do the write & also write | |
# a copy to disk | |
require Logger | |
@repo :repo_registry | |
def init(filepath) do | |
Registry.start_link(keys: :unique, name: @repo) | |
setup_db(filepath) | |
end | |
############################################################################## | |
# Events and their stuff | |
def events() do | |
[{_pid, data}] = Registry.lookup(@repo, :data) | |
data[:events] | |
end | |
def add_event(event, ts \\ nil) do | |
# Should come in as "YYYY-MM-DD 24:MM:SS" | |
ts = if ts, do: ts, else: Timex.format!(Timex.now, "%F %T", :strftime) | |
IO.puts "WTF1?!?!?!" | |
Registry.update_value(@repo, :data, | |
fn old -> | |
# IO.puts "?!?!?!?!?" | |
# [{_pid, data}] = old | |
# IO.puts "old: #{old} data: #{data}" | |
# put_in(data, [:events], [[ts, event] | data[:events]]) | |
old | |
end) | |
# write_db() | |
# :ok | |
end | |
############################################################################## | |
# Setup & persistence functions | |
defp setup_db(file) do | |
Registry.register(@repo, :db_file, file) | |
Registry.register(@repo, :data, %{}) | |
read_disk_db() | |
end | |
def read_disk_db() do | |
case Registry.lookup(@repo, :db_file) do | |
[{_pid, db_file}] -> | |
case File.read(db_file) do | |
{:ok, data} -> | |
Registry.update_value(@repo, :data, | |
fn _ -> | |
{:ok, data} = JSX.decode(data, [{:labels, :atom}]) | |
data | |
end) | |
{:error, err} -> Logger.error "Error reading file: #{err}" | |
end | |
_ -> Logger.error "No DB File for Repo" | |
end | |
end | |
defp write_db() do | |
case Registry.lookup(@repo, :db_file) do | |
[{_pid, db_file}] -> | |
[{_pid, data}] = Registry.lookup(@repo, :data) | |
{:ok, json} = JSX.encode data | |
{:ok, json} = JSX.prettify json # makin it perdy | |
case File.write(db_file, json) do | |
:ok -> Logger.info "Wrote to DB File" | |
{:error, err} -> Logger.error "Error writing file: #{err}" | |
end | |
_ -> Logger.error "No DB file for Repo" | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment