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

chore: refactors readme.md file of js websocket client to reduce cognitive complexity #1480

Open
wants to merge 3 commits into
base: master
Choose a base branch
from

Conversation

KunalNasa
Copy link
Contributor

@KunalNasa KunalNasa commented Apr 7, 2025

Screenshot 2025-04-07 at 7 01 55 PM

This PR refactors the code of readme.md.js file of javascript websocket client by breaking code into functions. This is done to reduce the cognitive complexity of the main function.

Resolves #1471

Summary by CodeRabbit

  • Refactor
    • Streamlined the generation of message examples in the documentation, enhancing readability and consistency by simplifying the logic for extracting example payloads.
    • Introduced a new function to extract example payloads from AsyncAPI operations, improving the overall functionality of the module's public API.

Copy link

changeset-bot bot commented Apr 7, 2025

⚠️ No Changeset found

Latest commit: 34226b6

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

Copy link

coderabbitai bot commented Apr 7, 2025

Walkthrough

The changes refactor the code for generating operation message examples in the README file. The inline logic for extracting message examples has been replaced with a new function, getOperationMessageExamplePayloads, which simplifies the process of retrieving example payloads directly from an AsyncAPI operation object. This refactor reduces complexity by removing unnecessary conditionals and enhances code readability while preserving the functionality of generating operation details.

Changes

File Change Summary
packages/templates/clients/websocket/javascript/template/README.md.js Updated import to include getOperationMessageExamplePayloads and simplified message example generation logic.
packages/helpers/src/index.js Added export for the new function getOperationMessageExamplePayloads to the module's public API.
packages/helpers/src/operations.js Introduced getOperationMessageExamplePayloads function to extract example payloads from an AsyncAPI operation.

Assessment against linked issues

Objective Addressed Explanation
Refactor readme.md.js to reduce cognitive complexity ([#1471])

Possibly related PRs

Suggested labels

ready-to-merge

Suggested reviewers

  • derberg
  • asyncapi-bot-eve
  • magicmatatjahu

Poem

I'm a bunny with a code delight,
Hopping through functions day and night,
Splitting logic with a joyful cheer,
Clean modular steps now all appear.
Carrots and clean code make my heart so light!
🐰💻

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@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)
packages/templates/clients/websocket/javascript/template/README.md.js (2)

104-116: Consider supporting all channels and examples.
Currently, only the first channel and first example are used. If future expansions require capturing additional channels or examples, modify this function to handle them accordingly.


130-140: Validate fallback snippet.
If operations is empty, the fallback snippet documents sendEchoMessage. Double-check that this method is indeed available, or clarify that it’s a placeholder if absent.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9b0172d and d1bb181.

📒 Files selected for processing (1)
  • packages/templates/clients/websocket/javascript/template/README.md.js (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Test generator as dependency with Node 20
  • GitHub Check: Test generator as dependency with Node 18
🔇 Additional comments (2)
packages/templates/clients/websocket/javascript/template/README.md.js (2)

50-50: Ensure generateOperationsSection handles multiple operations gracefully.
While this call looks correct, please verify that the returned markdown is formatted nicely for scenarios where multiple operations exist.


118-128: Looks good!
This function effectively formats operations. No immediate issues found.

@KunalNasa
Copy link
Contributor Author

Hi @derberg, I have written the functions in the same file, as these helper functions are related to this file only and putting them in the helpers package didn't make much sense. However, we can improve the code quality by breaking this file into components similar to the client.js file in the same folder.

Copy link
Member

@derberg derberg left a comment

Choose a reason for hiding this comment

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

actually helpers that help extract stuff from AsyncAPI documents should be placed in https://github.com/asyncapi/generator/tree/master/packages/helpers

and they should have small scope - meaning, they should return simple data. For example one helper should be as simple as giving you a list, actually probably a map of all the operations with examples.

string building, the resulting string, is in the scope of components, like for example https://github.com/asyncapi/generator/blob/master/packages/templates/clients/websocket/javascript/components/Connect.js

@KunalNasa
Copy link
Contributor Author

@derberg thanks for clarifying. Based on the code I have refactored, I am working on making reusable, small scoped helper functions and keeping in mind that they can be used across various templates. I will get back to you when the refactoring of the code is done using these helper functions.

Copy link

sonarqubecloud bot commented Apr 8, 2025

Copy link

@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 (1)
packages/helpers/src/operations.js (1)

19-23: Clean implementation with modern JavaScript features.

The function uses modern JavaScript features like:

  • Optional chaining (examples?.())
  • Array methods (flatMap, map, filter)
  • Short-circuit evaluation with ||

One minor suggestion:

 const examples = messages.flatMap(message => message.examples?.() || []);

 // filter out any undefined/null results, for example if the payload is not defined
 return examples.map(example => example.payload()).filter(Boolean);
-};
+}

The semicolon after the function closing brace is unnecessary in JavaScript and not used elsewhere in the codebase.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d1bb181 and 34226b6.

📒 Files selected for processing (3)
  • packages/helpers/src/index.js (1 hunks)
  • packages/helpers/src/operations.js (1 hunks)
  • packages/templates/clients/websocket/javascript/template/README.md.js (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/templates/clients/websocket/javascript/template/README.md.js
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Test generator as dependency with Node 20
  • GitHub Check: Test generator as dependency with Node 18
  • GitHub Check: Test NodeJS PR - windows-latest
🔇 Additional comments (4)
packages/helpers/src/index.js (1)

1-1: Clean export of the new helper function.

The import and export of the new getOperationMessageExamplePayloads function follows the established pattern in the file. This change properly makes the function available through the helpers package, which is good for code organization and reusability.

Also applies to: 8-9

packages/helpers/src/operations.js (3)

1-8: Well-documented function with clear JSDoc comments.

The JSDoc documentation provides comprehensive information about the function's purpose, parameters, return value, and possible errors. This is excellent for code maintainability and developer experience.


9-18: Good error handling and early returns for edge cases.

The function properly validates input and handles edge cases by:

  1. Checking if the operation parameter exists
  2. Returning early with empty arrays when no channels or messages are found

This approach prevents unnecessary processing and makes the code more robust.


25-27: Clean module exports.

The module exports follow the standard CommonJS pattern, making the function available for import from other files.

@KunalNasa
Copy link
Contributor Author

Hi @derberg,
I moved the logic from line 52 into a separate helper function as suggested and after spending some time I figured out that no more helper functions are required for this code. Let me know if there’s anything wrong or anything I should improve in the new helper. I would be happy to update it.

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.

[Refactor] refactor readme.md.js file code to reduce cognitive complexity
3 participants