Skip to content

Commit

Permalink
Add method to get messages from a conversation
Browse files Browse the repository at this point in the history
  • Loading branch information
renatolond committed Nov 20, 2024
1 parent 4c769bd commit 7e7a3eb
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
14 changes: 14 additions & 0 deletions app/persistence/repository/messages.rb
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,20 @@ def find_conversations(profile_id:)
.to_a
end

# Returns the last 20 messages from a conversation
# @param conversation_id (see .insert_message)
# @param max_id [Integer, nil] Used for pagination, will only look for messages with id smaller than the given one
# @return [Array<Hash>]
def find_messages(conversation_id:, max_id: nil)
# TODO: (renatolond, 2024-11-20) I think this needs an index to support this query, look into it
m = messages.where(conversation_id:)
.order(Sequel[:id].desc)
.limit(20)

m = m.where { id < max_id } if max_id
m.to_a
end

private

# @return [Sequel::Postgres::Dataset]
Expand Down
27 changes: 27 additions & 0 deletions test/app/persistence/repository/messages_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -94,4 +94,31 @@
assert_equal 2, conversations.size
end
end

describe ".find_messages" do
before do
create(:message, conversation: @conversation, sender: "profile1", content: "Message 1")
create(:message, conversation: @conversation, sender: "profile2", content: "Message 2")
@message3 = create(:message, conversation: @conversation, sender: "profile1", content: "Message 3")
create(:message, conversation: @conversation, sender: "profile1", content: "Message 4")
create(:message, conversation: @conversation, sender: "profile2", content: "Message 5")
end

it "find all messages for a conversation" do
messages = Persistence::Repository::Messages.find_messages(conversation_id: @conversation.id)
expected_messages = ["Message 5", "Message 4", "Message 3", "Message 2", "Message 1"]

assert_equal 5, messages.size
assert_equal(expected_messages, messages.map { |v| v[:content] })
end

it "paginate messages for a conversation" do
messages = Persistence::Repository::Messages.find_messages(conversation_id: @conversation.id, max_id: @message3.id)

expected_messages = ["Message 2", "Message 1"]

assert_equal 2, messages.size
assert_equal(expected_messages, messages.map { |v| v[:content] })
end
end
end

0 comments on commit 7e7a3eb

Please sign in to comment.