-
-
Notifications
You must be signed in to change notification settings - Fork 257
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
base: master
Are you sure you want to change the base?
Conversation
|
WalkthroughA 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
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
Poem
✨ Finishing Touches
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? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this 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
📒 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); }
There was a problem hiding this 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() +}); \`\`\` `}
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(); | ||
\`\`\` |
There was a problem hiding this comment.
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.
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); |
@derberg updated the readme template as you have said. |
|
There was a problem hiding this 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
📒 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.
Description
This pr added the template for README.md file. It is for the issue #1350
Related issue(s)
#1350
Summary by CodeRabbit