bump_server/lib/bump/messages.ex
raphael 5d50bb30e6 adds rest api connector
- routing setup with path to message_controller
- messages api to database updated to function
  similar to a stack system (push, pop, peek, ..)
- rest calls the same as database calls
- setup default controller showing text message
- parsing database output with Jason to client
- adds curl examples
2021-12-10 15:34:38 +01:00

63 lines
1.4 KiB
Elixir

defmodule Bump.Messages do
alias Bump.Repo
alias Bump.Messages.Message
import Ecto.Query
def pop(sender) do
query = from m in "messages",
where: m.sender == ^sender,
order_by: [desc: m.timestamp],
limit: 1,
select: %{id: m.id, data: m.data, timestamp: m.timestamp}
res = Repo.one(query)
if not is_nil(res) do
Repo.delete_all(from m in "messages", where: m.id == ^res.id)
%{data: res.data, timestamp: res.timestamp}
else
nil
end
end
def peak(sender) do
query = from m in "messages",
where: m.sender == ^sender,
order_by: [desc: m.timestamp],
limit: 1,
select: %{data: m.data, timestamp: m.timestamp}
Repo.one(query)
end
def list(sender, minutes) do
ago = DateTime.utc_now
|> Timex.shift(minutes: -minutes)
|> DateTime.truncate(:second)
query = from m in "messages",
where: m.sender == ^sender and
m.timestamp >= ^ago,
select: %{data: m.data, timestamp: m.timestamp}
Repo.all(query)
end
def clear(sender) do
query = from m in "messages",
where: m.sender == ^sender
Repo.delete_all(query)
end
def push(sender, message) do
time = DateTime.utc_now |> DateTime.truncate(:second)
Repo.insert(%Message{sender: sender, data: message, timestamp: time})
end
end