Skip to content

chore: Add OpenAPI Support to chat.getMessage API#36819

Open
ahmed-n-abdeltwab wants to merge 12 commits intoRocketChat:developfrom
ahmed-n-abdeltwab:feat/openapi-chat-getMessage
Open

chore: Add OpenAPI Support to chat.getMessage API#36819
ahmed-n-abdeltwab wants to merge 12 commits intoRocketChat:developfrom
ahmed-n-abdeltwab:feat/openapi-chat-getMessage

Conversation

@ahmed-n-abdeltwab
Copy link
Contributor

@ahmed-n-abdeltwab ahmed-n-abdeltwab commented Aug 28, 2025

Description:
This PR integrates OpenAPI support into the Rocket.Chat API, migrate of Rocket.Chat API endpoints to the new OpenAPI pattern. The update includes improved API documentation, enhanced type safety, and response validation using AJV.

Key Changes:

  • Implemented the new pattern and added AJV-based JSON schema validation for API.
  • Uses the ExtractRoutesFromAPI utility from the TypeScript definitions to dynamically derive the routes from the endpoint specifications.
  • Enabled Swagger UI integration for this API.
  • Route Methods Chaining for the endpoints.
  • This does not introduce any breaking changes to the endpoint logic.

Issue Reference:
Relates to #34983, part of the ongoing OpenAPI integration effort.

Testing:

  • Verified that the API response schemas are correctly documented in Swagger UI.
  • All tests passed without any breaking changes

Endpoints:

Looking forward to your feedback! 🚀

Summary by CodeRabbit

  • New Features

    • Added OpenAPI support for the chat.getMessage endpoint to improve API docs and client tooling.
  • Refactor

    • Centralized and modernized chat.getMessage routing and validation without changing observable behavior.
  • Chores

    • Removed the previously generated public typing for chat.getMessage, reducing the published API surface.
  • Bug Fix

    • Normalize message attachments so attachment metadata consistently uses an array format.

@dionisio-bot
Copy link
Contributor

dionisio-bot bot commented Aug 28, 2025

Looks like this PR is ready to merge! 🎉
If you have any trouble, please check the PR guidelines

@changeset-bot
Copy link

changeset-bot bot commented Aug 28, 2025

🦋 Changeset detected

Latest commit: 765cd11

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 41 packages
Name Type
@rocket.chat/meteor Patch
@rocket.chat/rest-typings Patch
@rocket.chat/api-client Patch
@rocket.chat/core-services Patch
@rocket.chat/ddp-client Patch
@rocket.chat/http-router Patch
@rocket.chat/models Patch
@rocket.chat/ui-contexts Patch
@rocket.chat/web-ui-registration Patch
@rocket.chat/account-service Patch
@rocket.chat/authorization-service Patch
@rocket.chat/ddp-streamer Patch
@rocket.chat/federation-matrix Patch
@rocket.chat/omnichannel-services Patch
@rocket.chat/presence Patch
rocketchat-services Patch
@rocket.chat/omnichannel-transcript Patch
@rocket.chat/presence-service Patch
@rocket.chat/queue-worker Patch
@rocket.chat/abac Patch
@rocket.chat/network-broker Patch
@rocket.chat/omni-core-ee Patch
@rocket.chat/livechat Patch
@rocket.chat/mock-providers Patch
@rocket.chat/cron Patch
@rocket.chat/instance-status Patch
@rocket.chat/omni-core Patch
@rocket.chat/server-fetch Patch
@rocket.chat/ui-client Patch
@rocket.chat/media-calls Patch
@rocket.chat/uikit-playground Patch
@rocket.chat/fuselage-ui-kit Patch
@rocket.chat/gazzodown Patch
@rocket.chat/ui-avatar Patch
@rocket.chat/ui-video-conf Patch
@rocket.chat/ui-voip Patch
@rocket.chat/core-typings Patch
@rocket.chat/apps Patch
@rocket.chat/model-typings Patch
@rocket.chat/license Patch
@rocket.chat/pdf-worker Patch

Not sure what this means? Click here to learn what changesets are.

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

@codecov
Copy link

codecov bot commented Aug 28, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 70.63%. Comparing base (d907668) to head (765cd11).
⚠️ Report is 3 commits behind head on develop.

Additional details and impacted files

Impacted file tree graph

@@             Coverage Diff             @@
##           develop   #36819      +/-   ##
===========================================
+ Coverage    70.61%   70.63%   +0.01%     
===========================================
  Files         3189     3189              
  Lines       112717   112715       -2     
  Branches     20401    20425      +24     
===========================================
+ Hits         79597    79611      +14     
+ Misses       31074    31061      -13     
+ Partials      2046     2043       -3     
Flag Coverage Δ
unit 71.17% <ø> (+0.02%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@ahmed-n-abdeltwab ahmed-n-abdeltwab marked this pull request as ready for review September 8, 2025 12:21
@ahmed-n-abdeltwab ahmed-n-abdeltwab requested review from a team as code owners September 8, 2025 12:21
@ahmed-n-abdeltwab
Copy link
Contributor Author

@cardoso , @ggazzo 👍

@Kaustubh1204
Copy link

Kaustubh1204 commented Jan 22, 2026

Hi @ahmed-n-abdeltwab

Thanks for the detailed OpenAPI migration for chat.getMessage. I reviewed the changes and everything looks solid — the endpoint, AJV validations, and the schema improvements are clear and well-structured.
I noticed the branch has a merge conflict with develop and some lint warnings regarding non-null assertions. If needed, I can help with resolving the merge conflict or testing the endpoint on CE/EE environments to unblock this PR.
Let me know how I can assist to move this forward.

@ahmed-n-abdeltwab
Copy link
Contributor Author

Hi @Kaustubh1204 ,

Thanks for the review! I definitely haven't given up on this one, just been a bit tied up.

If you're still down to help with the merge conflicts and testing on CE/EE, that would be awesome and much appreciated! It would definitely help get this over the finish line.

Also, just for context, I've been using this PR as a guide for the migration track and project docs: RocketChat/Rocket.Chat-Open-API#150 It shows the other APIs I'm working on and how everything is structured.

Let me know if you want to jump in, and thanks again for reaching out!

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jan 25, 2026

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Walkthrough

Relocates and redefines the chat.getMessage GET endpoint into the Meteor app with AJV query validation and OpenAPI-style response schema, removes the corresponding typings and endpoint declaration from rest-typings, and normalizes message attachment md to arrays during message updates.

Changes

Cohort / File(s) Summary
Changeset metadata
.changeset/unlucky-sloths-cough.md
Adds a patch changeset for @rocket.chat/meteor and @rocket.chat/rest-typings, noting OpenAPI support for chat.getMessage.
API route & validation
apps/meteor/app/api/server/v1/chat.ts
Moves/reintroduces chat.getMessage GET endpoint into main chat endpoints; adds ChatGetMessage type, ChatGetMessageSchema, isChatGetMessageProps AJV validator, and a structured response; handler validates msgId, fetches and normalizes the message, and returns result or error.
Removed public typings & endpoint
packages/rest-typings/src/v1/chat.ts
Removes ChatGetMessage type, ChatGetMessageSchema, exported isChatGetMessageProps, and the '/v1/chat.getMessage' entry from ChatEndpoints, shrinking the public typings surface.
Message normalization in updater
apps/meteor/app/lib/server/functions/updateMessage.ts
Adds import of Root from @rocket.chat/message-parser and normalizes editedMessage.attachments so each attachment's md is an array of Root before the DB update.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant Server
  participant Validator as AJV\ Validator
  participant DB as Database
  participant Normalizer

  Client->>Server: GET /api/v1/chat.getMessage?msgId=...
  Server->>Validator: validate query (ChatGetMessageSchema)
  alt valid
    Server->>DB: fetch message by msgId and user
    DB-->>Server: message or null
    alt message found
      Server->>Normalizer: normalize message (attachments.md -> array)
      Normalizer-->>Server: normalized message
      Server-->>Client: 200 { message, success: true }
    else not found
      Server-->>Client: 404 { success: false, error }
    end
  else invalid
    Server-->>Client: 400 { success: false, error }
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 I hopped through code and schema light,
Moved a route beneath the moonlit byte,
AJV trimmed each query tight,
Attachments lined up, neat and bright,
Now messages bound home — what a sight!

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Title check ✅ Passed The PR title 'chore: Add OpenAPI Support to chat.getMessage API' accurately describes the main change of integrating OpenAPI support into the chat.getMessage endpoint through schema validation and modern route definition.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

Copy link
Contributor

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

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

No issues found across 3 files

@ahmed-n-abdeltwab ahmed-n-abdeltwab force-pushed the feat/openapi-chat-getMessage branch from 7e1aff5 to 83634f3 Compare January 25, 2026 17:09
@ahmed-n-abdeltwab ahmed-n-abdeltwab marked this pull request as draft January 25, 2026 18:12
Comment on lines +77 to +84
// Ensure attachments have proper md arrays before saving
if (editedMessage.attachments) {
editedMessage.attachments = editedMessage.attachments.map((attachment: MessageAttachment) => ({
...attachment,
md: Array.isArray(attachment.md) ? attachment.md : [],
}));
}

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Normalize attachments properties to arrays in updateMessage. Previously, the database would ignore attachments because they didn’t follow the MongoDB schema, leading to data loss.

Fortunately, chat.getMessage was used in a test that encountered this attachment issue; because chat.getMessage is strictly typed, the test failed and alerted us. I suspect this change might fix multiple tests. Any test utilizing message attachments should now be resolved.

@ahmed-n-abdeltwab
Copy link
Contributor Author

ahmed-n-abdeltwab commented Jan 26, 2026

It's impressive how effectively this new pattern detected the bug early. Even though I spent all day yesterday tracing and debugging, I think my next step should be to revisit the old PRs. I should update the straightforward ones and fix the buggy ones before expanding the API further. This is a perfect live demonstration of how much more powerful this pattern is.

I think this pattern has transitioning from 'generating Swagger docs and maintaining a single source of truth API' to 'increasing API toughness and resiliency' or it might be from the start was like that. and Im only now seeing the full extent of its power.

@ahmed-n-abdeltwab ahmed-n-abdeltwab marked this pull request as ready for review January 26, 2026 13:14
Copy link
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: 2

🤖 Fix all issues with AI agents
In `@apps/meteor/app/lib/server/functions/updateMessage.ts`:
- Line 77: Remove the inline implementation comment "// Ensure attachments have
proper md arrays before saving" from
apps/meteor/app/lib/server/functions/updateMessage.ts; locate it inside the
updateMessage function (or the exported update message handler) and delete the
comment, and if the rationale must be preserved move the note to external docs,
a unit test name, or the function's JSDoc rather than leaving an inline comment
in the TS implementation.
- Around line 78-83: The current update in updateMessage.ts assumes
editedMessage.attachments is an array and that attachment.md is an array; change
the logic to first coerce editedMessage.attachments into an array when it's a
single object (e.g., if typeof !== 'undefined' and !Array.isArray) before
mapping, and when mapping each MessageAttachment preserve md by converting
non-array md values into an array (wrap single values) rather than replacing
them with [] — keep existing arrays untouched and ensure the result is always an
array of attachments with md as an array.

Copy link
Contributor

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

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

No issues found across 4 files

Copy link
Contributor

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

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

No issues found across 4 files

@ggazzo ggazzo added this to the 8.2.0 milestone Jan 26, 2026
@ggazzo ggazzo modified the milestones: 8.2.0, 8.3.0 Feb 24, 2026
@ggazzo ggazzo added the stat: QA assured Means it has been tested and approved by a company insider label Feb 24, 2026
@dionisio-bot dionisio-bot bot added the stat: ready to merge PR tested and approved waiting for merge label Feb 24, 2026
Copy link
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: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@apps/meteor/app/api/server/v1/chat.ts`:
- Around line 368-370: Remove the redundant runtime guard that checks
this.queryParams.msgId in the chat.getMessage action because the http-router
middleware already validates the query using the isChatGetMessageProps validator
(enforcing minLength:1); delete the if-block that returns API.v1.failure and
directly use this.queryParams.msgId (like chat.pinMessage does with
this.bodyParams.messageId) so the handler assumes a validated, non-empty msgId.

ℹ️ Review info

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4849442 and 0b34741.

📒 Files selected for processing (2)
  • apps/meteor/app/api/server/v1/chat.ts
  • apps/meteor/app/lib/server/functions/updateMessage.ts
📜 Review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: 📦 Build Packages
  • GitHub Check: CodeQL-Build
🧰 Additional context used
📓 Path-based instructions (1)
**/*.{ts,tsx,js}

📄 CodeRabbit inference engine (.cursor/rules/playwright.mdc)

**/*.{ts,tsx,js}: Write concise, technical TypeScript/JavaScript with accurate typing in Playwright tests
Avoid code comments in the implementation

Files:

  • apps/meteor/app/api/server/v1/chat.ts
  • apps/meteor/app/lib/server/functions/updateMessage.ts
🧠 Learnings (9)
📓 Common learnings
Learnt from: ggazzo
Repo: RocketChat/Rocket.Chat PR: 35995
File: apps/meteor/app/api/server/v1/rooms.ts:1107-1112
Timestamp: 2026-02-23T17:53:06.802Z
Learning: In Rocket.Chat PR reviews, maintain strict scope boundaries—when a PR is focused on a specific endpoint (e.g., rooms.favorite), avoid reviewing or suggesting changes to other endpoints that were incidentally refactored (e.g., rooms.invite) unless explicitly requested by maintainers.
📚 Learning: 2026-01-17T01:51:47.764Z
Learnt from: tassoevan
Repo: RocketChat/Rocket.Chat PR: 38219
File: packages/core-typings/src/cloud/Announcement.ts:5-6
Timestamp: 2026-01-17T01:51:47.764Z
Learning: In packages/core-typings/src/cloud/Announcement.ts, the AnnouncementSchema.createdBy field intentionally overrides IBannerSchema.createdBy (object with _id and optional username) with a string enum ['cloud', 'system'] to match existing runtime behavior. This is documented as technical debt with a FIXME comment at apps/meteor/app/cloud/server/functions/syncWorkspace/handleCommsSync.ts:53 and should not be flagged as an error until the runtime behavior is corrected.

Applied to files:

  • apps/meteor/app/api/server/v1/chat.ts
  • apps/meteor/app/lib/server/functions/updateMessage.ts
📚 Learning: 2026-02-23T17:53:06.802Z
Learnt from: ggazzo
Repo: RocketChat/Rocket.Chat PR: 35995
File: apps/meteor/app/api/server/v1/rooms.ts:1107-1112
Timestamp: 2026-02-23T17:53:06.802Z
Learning: During PR reviews that touch endpoint files under apps/meteor/app/api/server/v1, enforce strict scope: if a PR targets a specific endpoint (e.g., rooms.favorite), do not propose changes to unrelated endpoints (e.g., rooms.invite) unless maintainers explicitly request them. Focus feedback on the touched endpoint's behavior, API surface, and related tests; avoid broad cross-endpoint changes in the same PR unless requested.

Applied to files:

  • apps/meteor/app/api/server/v1/chat.ts
📚 Learning: 2025-11-19T18:20:07.720Z
Learnt from: gabriellsh
Repo: RocketChat/Rocket.Chat PR: 37419
File: packages/i18n/src/locales/en.i18n.json:918-921
Timestamp: 2025-11-19T18:20:07.720Z
Learning: Repo: RocketChat/Rocket.Chat — i18n/formatting
Learning: This repository uses a custom message formatting parser in UI blocks/messages; do not assume standard Markdown rules. For keys like Call_ended_bold, Call_not_answered_bold, Call_failed_bold, and Call_transferred_bold in packages/i18n/src/locales/en.i18n.json, retain the existing single-asterisk emphasis unless maintainers request otherwise.

Applied to files:

  • apps/meteor/app/lib/server/functions/updateMessage.ts
📚 Learning: 2025-11-24T17:08:17.065Z
Learnt from: CR
Repo: RocketChat/Rocket.Chat PR: 0
File: .cursor/rules/playwright.mdc:0-0
Timestamp: 2025-11-24T17:08:17.065Z
Learning: Applies to **/*.{ts,tsx,js} : Avoid code comments in the implementation

Applied to files:

  • apps/meteor/app/lib/server/functions/updateMessage.ts
📚 Learning: 2025-11-10T19:06:20.146Z
Learnt from: MartinSchoeler
Repo: RocketChat/Rocket.Chat PR: 37408
File: apps/meteor/client/views/admin/ABAC/useRoomAttributeOptions.tsx:53-69
Timestamp: 2025-11-10T19:06:20.146Z
Learning: In the Rocket.Chat repository, do not provide suggestions or recommendations about code sections marked with TODO comments. The maintainers have already identified these as future work and external reviewers lack the full context about implementation plans and timing.

Applied to files:

  • apps/meteor/app/lib/server/functions/updateMessage.ts
📚 Learning: 2025-10-06T20:32:23.658Z
Learnt from: d-gubert
Repo: RocketChat/Rocket.Chat PR: 37152
File: packages/apps-engine/tests/test-data/utilities.ts:557-573
Timestamp: 2025-10-06T20:32:23.658Z
Learning: In packages/apps-engine/tests/test-data/utilities.ts, the field name `isSubscripbedViaBundle` in the `IMarketplaceSubscriptionInfo` type should not be flagged as a typo, as it may match the upstream API's field name.

Applied to files:

  • apps/meteor/app/lib/server/functions/updateMessage.ts
📚 Learning: 2025-11-19T18:20:37.116Z
Learnt from: gabriellsh
Repo: RocketChat/Rocket.Chat PR: 37419
File: apps/meteor/server/services/media-call/service.ts:141-141
Timestamp: 2025-11-19T18:20:37.116Z
Learning: In apps/meteor/server/services/media-call/service.ts, the sendHistoryMessage method should use call.caller.id or call.createdBy?.id as the message author, not call.transferredBy?.id. Even for transferred calls, the message should appear in the DM between the two users who are calling each other, not sent by the person who transferred the call.

Applied to files:

  • apps/meteor/app/lib/server/functions/updateMessage.ts
📚 Learning: 2026-02-23T17:53:06.802Z
Learnt from: ggazzo
Repo: RocketChat/Rocket.Chat PR: 35995
File: apps/meteor/app/api/server/v1/rooms.ts:1107-1112
Timestamp: 2026-02-23T17:53:06.802Z
Learning: In Rocket.Chat PR reviews, maintain strict scope boundaries—when a PR is focused on a specific endpoint (e.g., rooms.favorite), avoid reviewing or suggesting changes to other endpoints that were incidentally refactored (e.g., rooms.invite) unless explicitly requested by maintainers.

Applied to files:

  • apps/meteor/app/lib/server/functions/updateMessage.ts
🧬 Code graph analysis (1)
apps/meteor/app/lib/server/functions/updateMessage.ts (1)
packages/message-parser/src/definitions.ts (1)
  • Root (245-245)
🔇 Additional comments (2)
apps/meteor/app/lib/server/functions/updateMessage.ts (1)

80-99: LGTM — previous concerns fully addressed.

Both fixes (the non-array attachments guard and the single-value md wrapping) are correctly implemented. The three-branch normalization is clean and complete.

apps/meteor/app/api/server/v1/chat.ts (1)

344-384: LGTM — endpoint migration and response schema are well-structured.

The OpenAPI pattern is correctly applied: AJV schema + validator compile + chained .get() with $ref: '#/components/schemas/IMessage' in the 200 response matches the chat.pinMessage pattern and addresses the $ref feedback from the previous review.

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
@dionisio-bot dionisio-bot bot enabled auto-merge February 24, 2026 02:43
auto-merge was automatically disabled February 24, 2026 08:57

Head branch was pushed to by a user without write access

@dionisio-bot dionisio-bot bot enabled auto-merge February 24, 2026 08:57
@ahmed-n-abdeltwab ahmed-n-abdeltwab changed the title feat: Add OpenAPI Support to chat.getMessage API chore: Add OpenAPI Support to chat.getMessage API Feb 24, 2026
Comment on lines +80 to +100
if (editedMessage.attachments != null) {
const attachments = Array.isArray(editedMessage.attachments) ? editedMessage.attachments : [editedMessage.attachments];

editedMessage.attachments = attachments.map((attachment) => {
let normalizedMd: Root;

if (Array.isArray(attachment.md)) {
normalizedMd = attachment.md;
} else if (attachment.md != null) {
normalizedMd = [attachment.md];
} else {
normalizedMd = [];
}

return {
...attachment,
md: normalizedMd,
};
});
}

Copy link
Member

Choose a reason for hiding this comment

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

is this required?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

The short answer is yes. The reason this fixed the problem is that the editedMessage attachments were missing. This caused the test to fail because the JSON schema was able to detect the missing data

Copy link
Contributor Author

Choose a reason for hiding this comment

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

It happens a lot with other APIs too. I'm going to try my best to avoid making any changes, especially to the frontend or the database

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

stat: QA assured Means it has been tested and approved by a company insider stat: ready to merge PR tested and approved waiting for merge

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants