From 3b1657e18a147a2cd461aac4539736e138e4220a Mon Sep 17 00:00:00 2001 From: raphael Date: Fri, 10 Dec 2021 12:46:34 +0100 Subject: [PATCH] adds api calls for getting, setting, removing - using Ecto queries, the api can now get newest message or get the last message - delete all messages of a sender id - add a message (auto adding a time stamp) --- README.md | 7 +++++++ lib/bump/messages.ex | 24 +++++++++++++++++++++--- lib/bump/messages/message.ex | 3 +-- 3 files changed, 29 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 9245216..c544317 100644 --- a/README.md +++ b/README.md @@ -22,3 +22,10 @@ Ready to run in production? Please [check our deployment guides](https://hexdocs * Docs: https://hexdocs.pm/phoenix * Forum: https://elixirforum.com/c/phoenix-forum * Source: https://github.com/phoenixframework/phoenix + +## TODOs + +[x] finish api calls in lib/bump/messages.ex +[] + + diff --git a/lib/bump/messages.ex b/lib/bump/messages.ex index db5fd0c..fc6a820 100644 --- a/lib/bump/messages.ex +++ b/lib/bump/messages.ex @@ -1,8 +1,15 @@ defmodule Bump.Messages do alias Bump.Repo + alias Bump.Messages.Message import Ecto.Query - def get_newest_message(_sender) do + def get_newest_message(sender) do + query = from m in "messages", + where: m.sender == ^sender, + order_by: [desc: m.timestamp], + limit: 1, + select: m.data + Repo.one(query) end def get_all_messages_since(sender, minutes) do @@ -18,10 +25,21 @@ defmodule Bump.Messages do Repo.all(query) end - def remove_sender(_sender) do + def remove_sender(sender) do + query = from m in "messages", + where: m.sender == ^sender, + select: m.id + Repo.delete_all(query) end - def add_message(_sender, _message) do + def add_message(sender, message) do + time = + DateTime.utc_now + |> DateTime.truncate(:second) + + Repo.insert(%Message{sender: sender, data: message, timestamp: time}) + end + end diff --git a/lib/bump/messages/message.ex b/lib/bump/messages/message.ex index 3c7f78d..e3e0412 100644 --- a/lib/bump/messages/message.ex +++ b/lib/bump/messages/message.ex @@ -5,8 +5,7 @@ defmodule Bump.Messages.Message do schema "messages" do field :sender, :string field :data, :string, default: "" - field :timestamp, :utc_datetime, default: DateTime.utc_now |> DateTime.truncate(:second) - + field :timestamp, :utc_datetime timestamps() end