Skip to content

fix: sort pinned messages#36768

Open
redeagle17 wants to merge 7 commits into
RocketChat:developfrom
redeagle17:fix/sort_pinned_messages
Open

fix: sort pinned messages#36768
redeagle17 wants to merge 7 commits into
RocketChat:developfrom
redeagle17:fix/sort_pinned_messages

Conversation

@redeagle17
Copy link
Copy Markdown

@redeagle17 redeagle17 commented Aug 21, 2025

Proposed changes (including videos or screenshots)

The below changes are made:

  • Added functionality to sort pinned messages in the GET /api/v1/chat.getPinnedMessages endpoint.
  • Implemented the sort parameter to sort messages.
  • Added automated tests to ensure that messages are correctly sorted based on the sort parameter.

This change allows the /api/v1/chat.getPinnedMessages query to sort pinned messages according to the sort parameter value.

Issue(s)

This PR resolves the following issue:

Steps to test or reproduce

Further comments

Summary by CodeRabbit

  • New Features

    • Added sorting support to chat.getPinnedMessages, allowing clients to sort pinned messages (e.g., by timestamp descending) via a sort parameter.
  • Tests

    • Added end-to-end test to verify pinned message sorting by timestamp in descending order.

@redeagle17 redeagle17 requested a review from a team as a code owner August 21, 2025 13:52
@changeset-bot
Copy link
Copy Markdown

changeset-bot Bot commented Aug 21, 2025

⚠️ No Changeset found

Latest commit: a22cdaa

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@dionisio-bot
Copy link
Copy Markdown
Contributor

dionisio-bot Bot commented Aug 21, 2025

Looks like this PR is not ready to merge, because of the following issues:

  • This PR is missing the 'stat: QA assured' label
  • This PR is missing the required milestone or project

Please fix the issues and try again

If you have any trouble, please check the PR guidelines

@CLAassistant
Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

@redeagle17 redeagle17 changed the title Fix/sort pinned messages fix: pinned sort messages Aug 21, 2025
@redeagle17 redeagle17 changed the title fix: pinned sort messages fix: sort pinned messages Aug 21, 2025
Comment thread package.json Outdated
"@types/node": "~22.16.1",
"ts-node": "^10.9.2",
"turbo": "~2.5.5",
"turbo": "^2.5.6",
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I dont think this is related with the fix

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

reverted this

@redeagle17 redeagle17 requested a review from ggazzo August 23, 2025 19:06
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Sep 15, 2025

Walkthrough

Adds sort parsing to chat.getPinnedMessages by extracting a sort object from the JSON query and forwarding it to Messages.findPaginatedPinnedByRoom. Introduces an end-to-end test verifying descending timestamp sorting when a sort parameter is supplied.

Changes

Cohort / File(s) Summary
API: Pinned messages sorting
apps/meteor/app/api/server/v1/chat.ts
Parse sort from JSON query after offset/count and pass it in options to Messages.findPaginatedPinnedByRoom.
E2E: Sorting verification
apps/meteor/tests/end-to-end/api/chat.ts
New test ensures chat.getPinnedMessages sorts by ts descending when provided sort: JSON.stringify({ ts: -1 }).

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant C as Client
  participant API as chat.getPinnedMessages
  participant PQ as parseJsonQuery
  participant DB as Messages.findPaginatedPinnedByRoom

  C->>API: GET pinned messages (roomId, query with sort)
  API->>PQ: parse offset, count, sort
  PQ-->>API: { offset, count, sort }
  API->>DB: findPaginatedPinnedByRoom(roomId, { offset, count, sort })
  DB-->>API: { messages, total }
  API-->>C: 200 OK { success: true, messages, count, offset, total }
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related issues

Poem

A rabbit taps keys with delighted flair,
Sorting pins by time through digital air.
Timestamps tumble, high to low they glide,
Tests keep watch with a coder’s pride.
Burrow to server, the messages align—
Hop, sort, return: results are fine. 🐇✨

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title "fix: sort pinned messages" is concise, uses a conventional commit prefix, and accurately summarizes the primary change (adding sorting support for pinned messages in the chat.getPinnedMessages endpoint), so it clearly communicates the PR's main purpose.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Tip

👮 Agentic pre-merge checks are now available in preview!

Pro plan users can now enable pre-merge checks in their settings to enforce checklists before merging PRs.

  • Built-in checks – Quickly apply ready-made checks to enforce title conventions, require pull request descriptions that follow templates, validate linked issues for compliance, and more.
  • Custom agentic checks – Define your own rules using CodeRabbit’s advanced agentic capabilities to enforce organization-specific policies and workflows. For example, you can instruct CodeRabbit’s agent to verify that API documentation is updated whenever API schema files are modified in a PR. Note: Upto 5 custom checks are currently allowed during the preview period. Pricing for this feature will be announced in a few weeks.

Please see the documentation for more information.

Example:

reviews:
  pre_merge_checks:
    custom_checks:
      - name: "Undocumented Breaking Changes"
        mode: "warning"
        instructions: |
          Pass/fail criteria: All breaking changes to public APIs, CLI flags, environment variables, configuration keys, database schemas, or HTTP/GraphQL endpoints must be documented in the "Breaking Change" section of the PR description and in CHANGELOG.md. Exclude purely internal or private changes (e.g., code not exported from package entry points or explicitly marked as internal).

Please share your feedback with us on this Discord post.


Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (2)
apps/meteor/tests/end-to-end/api/chat.ts (1)

2961-2981: Test can pass vacuously with a single pinned message; ensure 2+ pins and fix title typo

Create at least two pinned messages before asserting order, and drop the stray brace in the test title.

-it('should return a list of pinned messages sorted by timestamp descending when sort is provided as {"ts":-1}}', (done) => {
-  void request
-    .get(api('chat.getPinnedMessages'))
-    .set(credentials)
-    .query({
-      roomId,
-      sort: JSON.stringify({ ts: -1 }),
-    })
-    .expect('Content-Type', 'application/json')
-    .expect(200)
-    .expect((res) => {
-      expect(res.body).to.have.property('success', true);
-      expect(res.body).to.have.property('messages').and.to.be.an('array');
-
-      const { messages } = res.body;
-      for (let i = 0; i < messages.length - 1; i++) {
-        expect(new Date(messages[i].ts).getTime()).to.be.greaterThan(new Date(messages[i + 1].ts).getTime());
-      }
-    })
-    .end(done);
-});
+it('should return a list of pinned messages sorted by timestamp descending when sort is provided as {"ts":-1}', async () => {
+  // Ensure at least 2 pinned messages with different timestamps
+  const msgA = (await sendSimpleMessage({ roomId })).body.message._id;
+  await pinMessage({ msgId: msgA });
+  await new Promise((r) => setTimeout(r, 10));
+  const msgB = (await sendSimpleMessage({ roomId })).body.message._id;
+  await pinMessage({ msgId: msgB });
+
+  const res = await request
+    .get(api('chat.getPinnedMessages'))
+    .set(credentials)
+    .query({ roomId, sort: JSON.stringify({ ts: -1 }) })
+    .expect('Content-Type', 'application/json')
+    .expect(200);
+
+  expect(res.body).to.have.property('success', true);
+  expect(res.body).to.have.property('messages').and.to.be.an('array');
+  const { messages } = res.body;
+  expect(messages.length).to.be.greaterThan(1);
+  for (let i = 0; i < messages.length - 1; i++) {
+    expect(new Date(messages[i].ts).getTime()).to.be.greaterThan(new Date(messages[i + 1].ts).getTime());
+  }
+});
apps/meteor/app/api/server/v1/chat.ts (1)

579-583: Only include sort when provided — preserve defaults and match file style

BaseRaw.findPaginated forwards options to col.find (packages/models/src/models/BaseRaw.ts); avoid passing an explicit sort: undefined — use the conditional spread pattern.

- const { cursor, totalCount } = Messages.findPaginatedPinnedByRoom(roomId, {
-   skip: offset,
-   limit: count,
-   sort: sort,
- });
+ const { cursor, totalCount } = Messages.findPaginatedPinnedByRoom(roomId, {
+   skip: offset,
+   limit: count,
+   ...(sort && { sort }),
+ });
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c5ee569 and a22cdaa.

📒 Files selected for processing (2)
  • apps/meteor/app/api/server/v1/chat.ts (2 hunks)
  • apps/meteor/tests/end-to-end/api/chat.ts (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
apps/meteor/tests/end-to-end/api/chat.ts (1)
apps/meteor/tests/data/api-data.ts (3)
  • request (10-10)
  • api (46-48)
  • credentials (39-42)
🔇 Additional comments (1)
apps/meteor/app/api/server/v1/chat.ts (1)

573-573: Sort parsing added — LGTM

Parsing sort via parseJsonQuery aligns this route with others. No concerns.

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

Successfully merging this pull request may close these issues.

3 participants