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

feat: added the template for README.md #1368

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

Conversation

ItshMoh
Copy link

@ItshMoh ItshMoh commented Feb 19, 2025

Description
This pr added the template for README.md file. It is for the issue #1350

Related issue(s)
#1350

Screenshot_2025-02-19_17_49_27

Summary by CodeRabbit

  • Documentation
    • Introduced enhanced guidance for the WebSocket client, featuring a structured overview, clear instructions for connection management and event handling, and practical examples for testing scenarios.
    • Added a new function for generating a README.md file that details core methods, available operations, and error handling for the WebSocket client.

Copy link

changeset-bot bot commented Feb 19, 2025

⚠️ No Changeset found

Latest commit: 3be462b

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 Feb 19, 2025

Walkthrough

A new JavaScript file has been added that exports a function to generate a README for a WebSocket client based on the AsyncAPI specification. The function processes input parameters and API details to construct documentation covering an overview, core methods (such as connection management and message handling), available operations, and testing instructions. This structured README helps users understand and interact with the WebSocket client.

Changes

File Path Change Summary
packages/.../websocket/template/README.md.js Added a new JavaScript file that exports a default function. This function generates a README using AsyncAPI to detail the WebSocket client’s connection methods, message handlers, available operations, and testing examples.

Sequence Diagram(s)

sequenceDiagram
    participant U as User Code
    participant G as README Generator
    participant A as AsyncAPI Spec

    U->>G: Call default function with asyncapi & params
    G->>A: Retrieve server and client details
    A-->>G: Provide AsyncAPI details
    G->>G: Generate README content with overview, methods, & examples
    G-->>U: Return the generated README.md content
Loading

Poem

I’m a rabbit with code so neat,
Crafting docs that cannot be beat.
A WebSocket tale in every line,
Methods and tests all in design.
Hoppin’ through AsyncAPI with cheer,
Leaving clear guides for you, my dear!
🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 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. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @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 (4)
packages/templates/clients/js/websocket/template/README.md.js (4)

8-9: Remove unnecessary empty line.

Consider removing the extra empty line to maintain consistent spacing.

  const clientName = getClientName(info);
-  
  const operations = asyncapi.operations().all();

10-11: Remove unnecessary empty line.

Consider removing the extra empty line to maintain consistent spacing.

  const operations = asyncapi.operations().all();
-  
  return (

45-76: Consider refactoring for improved readability and maintainability.

The operations documentation logic could be simplified by extracting helper functions for example generation and operation formatting.

Consider refactoring like this:

+ const getMessageExample = (channel) => {
+   const messages = channel?.messages().all() || [];
+   const firstMessage = messages[0];
+   if (firstMessage?.examples?.()?.length > 0) {
+     const example = firstMessage.examples()[0];
+     return `\n\n**Example:**\n\`\`\`javascript\nclient.${operationId}(${JSON.stringify(example.payload(), null, 2)});\n\`\`\``;
+   }
+   return '';
+ };

+ const formatOperation = (operation) => {
+   const channels = operation.channels().all();
+   const channelAddress = channels.length > 0 ? channels[0].address() : 'default';
+   const messageExamples = channels.length > 0 ? getMessageExample(channels[0]) : '';
+   
+   return `#### \`${operation.id()}(payload)\`
+   ${operation.summary() || `Sends a message to the '${channelAddress}' channel.`}
+   ${operation.description() ? `\n${operation.description()}` : ''}${messageExamples}`;
+ };

${operations.length > 0 ? 
  operations.map(formatOperation).join('\n\n')
  : 
  // ... rest of the code

99-122: Enhance error handling and add more descriptive comments.

The error handling could be more specific, and the example could benefit from additional comments explaining the flow.

 async function main() {
+  // Register message and error handlers before connecting
   wsClient.registerMessageHandler(myHandler);
   wsClient.registerErrorHandler(myErrorHandler);

   try {
+    // Attempt to establish WebSocket connection
     await wsClient.connect();

+    // Configuration for message sending interval
     const interval = 5000; // 5 seconds
     const message = 'Hello, Echo!';

     while (true) {
       try {
         await wsClient.sendEchoMessage(message);
       } catch (error) {
-        console.error('Error while sending message:', error);
+        console.error('Error while sending message:', error.message);
+        // Consider implementing retry logic or breaking the loop on specific errors
+        if (error.code === 'WEBSOCKET_CLOSED') {
+          break;
+        }
       }
       await new Promise(resolve => setTimeout(resolve, interval));
     }
   } catch (error) {
-    console.error('Failed to connect to WebSocket:', error.message);
+    console.error(`WebSocket connection failed: ${error.message}`);
+    process.exit(1); // Exit with error code for proper error handling
   }
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4b31035 and f6fe9a8.

📒 Files selected for processing (1)
  • packages/templates/clients/js/websocket/template/README.md.js (1 hunks)
🔇 Additional comments (2)
packages/templates/clients/js/websocket/template/README.md.js (2)

15-42: Well-structured documentation with comprehensive coverage!

The overview and core methods sections are well-organized, providing clear and comprehensive documentation of the WebSocket client's capabilities.


110-118: Consider adding a termination condition to the infinite loop.

The infinite loop could be problematic in production. Consider adding a termination condition or documenting that this is for testing purposes only.

-    while (true) {
+    // Note: This is for testing purposes only. In production, use appropriate termination conditions
+    const MAX_MESSAGES = 10;
+    let messageCount = 0;
+    while (messageCount < MAX_MESSAGES) {
       try {
         await wsClient.sendEchoMessage(message);
+        messageCount++;
       } catch (error) {
         console.error('Error while sending message:', error);
       }

@ItshMoh ItshMoh changed the title added the template for README.md feat: added the template for README.md Feb 19, 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: 1

🧹 Nitpick comments (3)
packages/templates/clients/js/websocket/template/README.md.js (3)

4-8: Add input validation and improve props destructuring.

Consider adding server validation and making props more explicit:

-export default function({ asyncapi, params }) {
+export default function({ 
+  asyncapi,
+  params: { server: serverName, clientFileName }
+}) {
+  if (!asyncapi.servers().has(serverName)) {
+    throw new Error(`Server "${serverName}" not found in AsyncAPI document`);
+  }
+  const server = asyncapi.servers().get(serverName);
-  const server = asyncapi.servers().get(params.server);
   const info = asyncapi.info();
   const clientName = getClientName(info);

10-11: Remove unnecessary empty line.

The empty line at line 11 can be removed to maintain consistent code style.


51-82: Simplify operations mapping logic and improve example clarity.

The operations mapping logic could be simplified for better maintainability:

+const getMessageExample = (channel) => {
+  const messages = channel?.messages().all() || [];
+  const firstMessage = messages[0];
+  const examples = firstMessage?.examples() || [];
+  const example = examples[0];
+  
+  if (example?.payload()) {
+    return `\n\n**Example:**\n\`\`\`javascript\nclient.${operationId}(${JSON.stringify(example.payload(), null, 2)});\n\`\`\``;
+  }
+  return '';
+};

${operations.length > 0 ? 
  operations.map(operation => {
    const operationId = operation.id();
    const channels = operation.channels().all();
    const channelAddress = channels.length > 0 ? channels[0].address() : 'default';
-    
-    let messageExamples = '';
-    if (channels.length > 0) {
-      const channelMessages = channels[0].messages().all();
-      if (channelMessages && channelMessages.length > 0) {
-        const firstMessage = channelMessages[0];
-        if (firstMessage.examples && firstMessage.examples().length > 0) {
-          const example = firstMessage.examples()[0];
-          messageExamples = `\n\n**Example:**\n\`\`\`javascript\nclient.${operationId}(${JSON.stringify(example.payload(), null, 2)});\n\`\`\``;
-        }
-      }
-    }
+    const messageExamples = channels.length > 0 ? getMessageExample(channels[0]) : '';
    
    return `#### \`${operationId}(payload)\`
${operation.summary() || `Sends a message to the '${channelAddress}' channel.`}
${operation.description() ? `\n${operation.description()}` : ''}${messageExamples}`;
  }).join('\n\n')
  : 
  `#### \`sendEchoMessage(payload)\`
-Sends a message to the server that will be echoed back.
+Sends a test message to the server that will be echoed back. This is a default operation provided for testing when no operations are defined in the AsyncAPI specification.

**Example:**
\`\`\`javascript
-client.sendEchoMessage({ message: "Hello World" });
+client.sendEchoMessage({
+  message: "Hello World",
+  timestamp: new Date().toISOString()
+});
\`\`\`
`}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f6fe9a8 and f7b7002.

📒 Files selected for processing (1)
  • packages/templates/clients/js/websocket/template/README.md.js (1 hunks)

Comment on lines +105 to +131
async function main() {
wsClient.registerMessageHandler(myHandler);
wsClient.registerErrorHandler(myErrorHandler);

try {
await wsClient.connect();

// Loop to send messages every 5 seconds
const interval = 5000; // 5 seconds
const message = 'Hello, Echo!';

while (true) {
try {
await wsClient.sendEchoMessage(message);
} catch (error) {
console.error('Error while sending message:', error);
}
// Wait for the interval before sending the next message
await new Promise(resolve => setTimeout(resolve, interval));
}
} catch (error) {
console.error('Failed to connect to WebSocket:', error.message);
}
}

main();
\`\`\`
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve the testing example with proper cleanup and documentation.

The testing example could be enhanced with proper cleanup and better documentation:

 async function main() {
   wsClient.registerMessageHandler(myHandler);
   wsClient.registerErrorHandler(myErrorHandler);
+  let isRunning = true;
+
+  // Handle cleanup on process termination
+  process.on('SIGINT', async () => {
+    console.log('\nGracefully shutting down...');
+    isRunning = false;
+    await wsClient.close();
+    process.exit(0);
+  });

   try {
     await wsClient.connect();

     // Loop to send messages every 5 seconds
     const interval = 5000; // 5 seconds
     const message = 'Hello, Echo!';

-    while (true) {
+    // Send messages for a limited time (e.g., 1 minute) or until interrupted
+    while (isRunning) {
       try {
         await wsClient.sendEchoMessage(message);
       } catch (error) {
         console.error('Error while sending message:', error);
+        break;  // Exit loop on error
       }
       // Wait for the interval before sending the next message
       await new Promise(resolve => setTimeout(resolve, interval));
     }
   } catch (error) {
     console.error('Failed to connect to WebSocket:', error.message);
+  } finally {
+    await wsClient.close();
   }
 }

-main();
+// Add documentation about running and stopping the client
+console.log('Starting WebSocket client...');
+console.log('Press Ctrl+C to stop');
+main().catch(console.error);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
async function main() {
wsClient.registerMessageHandler(myHandler);
wsClient.registerErrorHandler(myErrorHandler);
try {
await wsClient.connect();
// Loop to send messages every 5 seconds
const interval = 5000; // 5 seconds
const message = 'Hello, Echo!';
while (true) {
try {
await wsClient.sendEchoMessage(message);
} catch (error) {
console.error('Error while sending message:', error);
}
// Wait for the interval before sending the next message
await new Promise(resolve => setTimeout(resolve, interval));
}
} catch (error) {
console.error('Failed to connect to WebSocket:', error.message);
}
}
main();
\`\`\`
async function main() {
wsClient.registerMessageHandler(myHandler);
wsClient.registerErrorHandler(myErrorHandler);
let isRunning = true;
// Handle cleanup on process termination
process.on('SIGINT', async () => {
console.log('\nGracefully shutting down...');
isRunning = false;
await wsClient.close();
process.exit(0);
});
try {
await wsClient.connect();
// Loop to send messages every 5 seconds
const interval = 5000; // 5 seconds
const message = 'Hello, Echo!';
// Send messages for a limited time (e.g., 1 minute) or until interrupted
while (isRunning) {
try {
await wsClient.sendEchoMessage(message);
} catch (error) {
console.error('Error while sending message:', error);
break; // Exit loop on error
}
// Wait for the interval before sending the next message
await new Promise(resolve => setTimeout(resolve, interval));
}
} catch (error) {
console.error('Failed to connect to WebSocket:', error.message);
} finally {
await wsClient.close();
}
}
// Add documentation about running and stopping the client
console.log('Starting WebSocket client...');
console.log('Press Ctrl+C to stop');
main().catch(console.error);

@ItshMoh
Copy link
Author

ItshMoh commented Feb 19, 2025

@derberg updated the readme template as you have said.

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

4-8: Add JSDoc documentation for better type information and usage guidance.

Consider adding JSDoc to document the function parameters and return type:

+/**
+ * Generates a README.md file for the WebSocket client
+ * @param {Object} options - The options object
+ * @param {AsyncAPIDocument} options.asyncapi - The AsyncAPI document
+ * @param {Object} options.params - Generator parameters
+ * @param {string} options.params.server - The server name
+ * @param {string} options.params.clientFileName - The client file name
+ * @returns {File} The generated README.md file
+ */
 export default function({ asyncapi, params }) {

10-11: Add validation for operations extraction.

Consider adding validation to handle cases where operations might be undefined or invalid:

-  const operations = asyncapi.operations().all();
+  const operations = asyncapi.operations()?.all() ?? [];

15-23: Enhance the overview section with additional metadata.

Consider adding more metadata from the AsyncAPI document to make the overview more comprehensive:

 # ${info.title()} 

 ## Overview

 ${info.description() || `A WebSocket client for ${info.title()}.`}

 - **Version:** ${info.version()}
 - **URL:** ${server.url()}
+${info.license() ? `- **License:** [${info.license().name()}](${info.license().url() || ''})` : ''}
+${info.contact() ? `- **Contact:** ${info.contact().name() || ''} ${info.contact().email() ? `<${info.contact().email()}>` : ''}` : ''}
+${server.description() ? `\n### Server Description\n\n${server.description()}` : ''}

35-48: Enhance method documentation with return types and error handling.

The core methods documentation could be more detailed:

 #### \`connect()\`
 Establishes a WebSocket connection to the server.
+- **Returns:** Promise<void>
+- **Throws:** WebSocketError if connection fails
 
 #### \`registerMessageHandler(handlerFunction)\`
 Registers a callback to handle incoming messages.
 - **Parameter:** \`handlerFunction\` - This Function takes a parameter \`message\` which is a string. 
+- **Returns:** void
 
 #### \`registerErrorHandler(handlerFunction)\`
 Registers a callback to handle WebSocket errors.
 - **Parameter:** \`handlerFunction\` - This Function takes a parameter \`error\` which is an object
+- **Returns:** void
 
 #### \`close()\`
 Closes the WebSocket connection.
+- **Returns:** Promise<void>
+- **Throws:** WebSocketError if closing fails

51-82: Simplify operations documentation generation.

The nested conditionals could be simplified using optional chaining and nullish coalescing:

-    if (channels.length > 0) {
-      const channelMessages = channels[0].messages().all();
-      if (channelMessages && channelMessages.length > 0) {
-        const firstMessage = channelMessages[0];
-        if (firstMessage.examples && firstMessage.examples().length > 0) {
-          const example = firstMessage.examples()[0];
-          messageExamples = `\n\n**Example:**\n\`\`\`javascript\nclient.${operationId}(${JSON.stringify(example.payload(), null, 2)});\n\`\`\``;
-        }
-      }
-    }
+    const example = channels[0]?.messages()?.all()?.[0]?.examples()?.[0];
+    messageExamples = example 
+      ? `\n\n**Example:**\n\`\`\`javascript\nclient.${operationId}(${JSON.stringify(example.payload(), null, 2)});\n\`\`\``
+      : '';
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f7b7002 and 3be462b.

📒 Files selected for processing (1)
  • packages/templates/clients/js/websocket/template/README.md.js (1 hunks)
🔇 Additional comments (1)
packages/templates/clients/js/websocket/template/README.md.js (1)

105-131: Improve the testing example with proper cleanup and documentation.

The testing example needs improvements in cleanup and error handling.

This issue was previously identified. Please refer to the earlier review comment for the suggested improvements.

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.

1 participant