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
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
137 changes: 137 additions & 0 deletions packages/templates/clients/js/websocket/template/README.md.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
import { File, Text } from '@asyncapi/generator-react-sdk';
import { getClientName } from '@asyncapi/generator-helpers';

export default function({ asyncapi, params }) {
const server = asyncapi.servers().get(params.server);
const info = asyncapi.info();
const clientName = getClientName(info);


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

return (
<File name="README.md">
<Text>
{`# ${info.title()}

## Overview

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

- **Version:** ${info.version()}
- **URL:** ${server.url()}


## Client API Reference

\`\`\`javascript
const ${clientName} = require('./${params.clientFileName.replace('.js', '')}');
const wsClient = new ${clientName}();
\`\`\`

Here the wsClient is an instance of the \`${clientName}\` class.
### Core Methods

#### \`connect()\`
Establishes a WebSocket connection to the server.

#### \`registerMessageHandler(handlerFunction)\`
Registers a callback to handle incoming messages.
- **Parameter:** \`handlerFunction\` - This Function takes a parameter \`message\` which is a string.

#### \`registerErrorHandler(handlerFunction)\`
Registers a callback to handle WebSocket errors.
- **Parameter:** \`handlerFunction\` - This Function takes a parameter \`error\` which is an object

#### \`close()\`
Closes the WebSocket connection.

### Available Operations

${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\`\`\``;
}
}
}

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.

**Example:**
\`\`\`javascript
client.sendEchoMessage({ message: "Hello World" });
\`\`\`
`}

## Testing the client

\`\`\`javascript
const ${clientName} = require('./${params.clientFileName.replace('.js', '')}');
const wsClient = new ${clientName}();


// Example of how custom message handler that operates on incoming messages can look like

function myHandler(message) {
console.log('====================');
console.log('Just proving I got the message in myHandler:', message);
console.log('====================');
}

// Example of custom error handler

function myErrorHandler(error) {
console.error('Errors from Websocket:', error.message);
}

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();
\`\`\`
Comment on lines +105 to +131
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);


`}
</Text>
</File>
);
}