bump_server/lib/bump/database.ex

91 lines
2.2 KiB
Elixir
Raw Normal View History

defmodule Bump.Database do
alias Bump.Repo
alias Bump.Messages.Message
alias Bump.Senders.Sender
import Ecto.Query
def pop(sender) do
query = from m in "messages",
where: m.sender == ^sender,
order_by: [desc: m.timestamp],
limit: 1,
2022-01-17 15:33:59 +01:00
select: %{id: m.id, title: m.title, 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)
2022-01-17 15:33:59 +01:00
%{title: res.title, data: res.data, timestamp: res.timestamp}
else
%{}
end
end
def peek(sender) do
query = from m in "messages",
where: m.sender == ^sender,
order_by: [desc: m.timestamp],
limit: 1,
2022-01-17 15:33:59 +01:00
select: %{title: m.title, 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,
2022-01-17 15:33:59 +01:00
select: %{title: m.title, 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, title, data) do
time = DateTime.utc_now |> DateTime.truncate(:second)
Repo.insert(%Message{sender: sender, title: title, data: data, timestamp: time})
end
def addSender(sender, %{"firebase" => firebase}) do
query = from s in "senders",
where: s.sender == ^sender and
s.firebase_token == ^firebase,
select: %{id: s.id}
if(Repo.all(query) == []) do
IO.puts("Adding sender: #{sender}")
Repo.insert(%Sender{sender: sender, firebase_token: firebase})
end
end
def deleteSender(sender) do
query = from s in "senders",
where: s.sender == ^sender
Repo.delete_all(query)
end
def tokens(sender) do
query = from s in "senders",
where: s.sender == ^sender,
select: %{firebase_token: s.firebase_token}
Repo.all(query)
end
end