Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Current message pagination approach is not well-suited to a realtime chat application #324

Open
ndavidson7 opened this issue Apr 26, 2024 · 0 comments

Comments

@ndavidson7
Copy link

Currently, retrieving messages from a conversation uses offset-based pagination:

/**
* Get messages in conversation for the specific participant.
*
* @param Model $participant
* @param $paginationParams
* @param $deleted
*
* @return LengthAwarePaginator|HasMany|Builder
*/
private function getConversationMessages(Model $participant, $paginationParams, $deleted)
{
$messages = $this->messages()
->join($this->tablePrefix.'message_notifications', $this->tablePrefix.'message_notifications.message_id', '=', $this->tablePrefix.'messages.id')
->where($this->tablePrefix.'message_notifications.messageable_type', $participant->getMorphClass())
->where($this->tablePrefix.'message_notifications.messageable_id', $participant->getKey());
$messages = $deleted ? $messages->whereNotNull($this->tablePrefix.'message_notifications.deleted_at') : $messages->whereNull($this->tablePrefix.'message_notifications.deleted_at');
$messages = $messages->orderBy($this->tablePrefix.'messages.id', $paginationParams['sorting'])
->paginate(
$paginationParams['perPage'],
[
$this->tablePrefix.'message_notifications.updated_at as read_at',
$this->tablePrefix.'message_notifications.deleted_at as deleted_at',
$this->tablePrefix.'message_notifications.messageable_id',
$this->tablePrefix.'message_notifications.id as notification_id',
$this->tablePrefix.'message_notifications.is_seen',
$this->tablePrefix.'message_notifications.is_sender',
$this->tablePrefix.'messages.*',
],
$paginationParams['pageName'],
$paginationParams['page']
);
return $messages;
}

However, this is not the appropriate method for a realtime chat application. If a message is sent between the time that a user loads the first and second pages of messages, the offset will point to one of the previously retrieved messages. This is exactly the problem that cursor-based pagination aims to solve, not to mention better performance.

I believe the solution is as simple as changing

->paginate(

to ->cursorPaginate( and removing redundant pagination parameters.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant