Skip to content
Merged
Show file tree
Hide file tree
Changes from 6 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
124 changes: 124 additions & 0 deletions packages/components/src/components/Connect.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
import { Text, render } from '@asyncapi/generator-react-sdk';
import { OnOpen } from './OnOpen';
import { OnMessage } from './OnMessage';
import { OnError } from './OnError';
import { OnClose } from './OnClose';

/**
* @typedef {'python' | 'javascript' | 'dart'} SupportedLanguage
* Supported programming languages for WebSocket connection method generation.
*/

/**
* Mapping of supported programming languages to their WebSocket connection method implementations.
*
* @type {Object.<SupportedLanguage, Function>}
*/
const websocketConnectMethod = {
javascript: (onOpenMethod, onMessageMethod, onErrorMethod, onCloseMethod) => {
return {
connectMethod: `// Method to establish a WebSocket connection
connect() {
return new Promise((resolve, reject) => {
this.websocket = new WebSocket(this.url);
${onOpenMethod}
${onMessageMethod}
${onErrorMethod}
${onCloseMethod}
});
}`
};
},
python: (onOpenMethod, onMessageMethod, onErrorMethod, onCloseMethod) => {
const onConnectMethod = `def connect(self):
"""Establish the connection and start the run_forever loop in a background thread."""
ssl_opts = {"ca_certs": certifi.where()}
self.ws_app = websocket.WebSocketApp(
self.url,
on_open=self.on_open,
on_message=self.on_message,
on_error=self.on_error,
on_close=self.on_close
)
# Run the WebSocketApp's run_forever in a separate thread with multithreading enabled.
def run():

retry = 0
max_retries = 5

while not self._stop_event.is_set() and retry < max_retries:
try:
retry += 1
print("Starting WebSocket thread...")
self.ws_app.run_forever(sslopt=ssl_opts)
except Exception as e:
print(f"Exception in WebSocket thread: {e}") # Print full error details

thread = threading.Thread(target=run, daemon=True)
thread.start()`;
return {
connectMethod: `${onOpenMethod}
${onMessageMethod}
${onErrorMethod}
${onCloseMethod}
${onConnectMethod}`
};
},
dart: (onMessageMethod, onErrorMethod, onCloseMethod, title) => {
return {
connectMethod: `/// Method to establish a WebSocket connection
Future<void> connect() async {
if (_channel != null) {
print('Already connected to ${title} server');
return;
}
try {
final wsUrl = Uri.parse(_url);
_channel = WebSocketChannel.connect(wsUrl);
print('Connected to ${title} server');
/// Listen to the incoming message stream
_channel?.stream.listen(
${onMessageMethod}
${onErrorMethod}
${onCloseMethod}
);
} catch (error) {
print('Connection failed: $error');
rethrow;
}
}`
};
}
};

/**
* Component that renders WebSocket connection method for the specified programming language.
*
* @param {Object} props - Component properties.
* @param {SupportedLanguage} props.language - The programming language for which to generate connection code.
* @param {string} props.title - The title of the WebSocket server.
*/
export function Connect({ language, title }) {
const onOpenMethod = render(<OnOpen language={language} title={title} />);
const onMessageMethod = render(<OnMessage language={language} />);
const onErrorMethod = render(<OnError language={language} />);
const onCloseMethod = render(<OnClose language={language} title={title} />);

const generateConnectCode = websocketConnectMethod[language];

let connectMethod;

if (language === 'dart') {
const result = generateConnectCode(onMessageMethod, onErrorMethod, onCloseMethod, title);
connectMethod = result.connectMethod;
} else {
const result = generateConnectCode(onOpenMethod, onMessageMethod, onErrorMethod, onCloseMethod);
connectMethod = result.connectMethod;
}

return (
<Text newLines={2} indent={2}>
{connectMethod}
</Text>
);
}
82 changes: 82 additions & 0 deletions packages/components/src/components/OnClose.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import { Text } from '@asyncapi/generator-react-sdk';

/**
* @typedef {'python' | 'javascript' | 'dart' | 'java' } SupportedLanguage
* Supported programming languages for WebSocket onClose handler generation.
*/

/**
* Mapping of supported programming languages to their WebSocket onClose event handler implementations.
*
* @type {Object.<SupportedLanguage, Function>}
*/
const websocketOnCloseMethod = {
javascript: (title) => {
return {
onCloseMethod: `// On connection close
this.websocket.onclose = () => {
console.log('Disconnected from ${title} server');
};`
};
},
python: (title) => {
return {
onCloseMethod: `def on_close(self, ws, close_status_code, close_msg):
print("Disconnected from ${title}", close_status_code, close_msg)`
};
},
dart: (title) => {
return {
onCloseMethod: `onDone: () {
_channel = null;
print('Disconnected from ${title} server');
},`
};
},
java: {
quarkus: (title) => {
const onCloseMethod = `@OnClose
public void onClose(CloseReason reason, WebSocketClientConnection connection) {
int code = reason.getCode();
Log.info("Websocket disconnected from ${title} with Close code: " + code);
}
}`;
return { onCloseMethod, indent: 2 };
}
}
};

const resolveCloseConfig = (language, framework = '') => {
const config = websocketOnCloseMethod[language];
if (typeof config === 'function') {
return config;
}
if (framework && typeof config[framework] === 'function') {
return config[framework];
}
};

/**
* Component that renders WebSocket onClose event handler for the specified programming language.
*
* @param {Object} props - Component properties.
* @param {SupportedLanguage} props.language - The programming language for which to generate onClose handler code.
* @param {string} props.title - The title of the WebSocket server.
*/
export function OnClose({ language, framework = '', title }) {
let onCloseMethod = '';
let indent = 0;

if (websocketOnCloseMethod[language]) {
const generateOnCloseCode = resolveCloseConfig(language, framework);
const closeResult = generateOnCloseCode(title);
onCloseMethod = closeResult.onCloseMethod;
indent = closeResult.indent ?? 0;
}

return (
<Text indent={indent}>
{onCloseMethod}
</Text>
);
}
71 changes: 71 additions & 0 deletions packages/components/src/components/OnError.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import { Text } from '@asyncapi/generator-react-sdk';

/**
* @typedef {'python' | 'javascript' | 'dart'} SupportedLanguage
* Supported programming languages for WebSocket onError handler generation.
*/

/**
* Mapping of supported programming languages to their WebSocket onError event handler implementations.
*
* @type {Object.<SupportedLanguage, Function>}
*/
const websocketOnErrorMethod = {
javascript: () => {
return {
onErrorMethod: `// On error first call custom error handlers, then default error behavior
this.websocket.onerror = (error) => {
if (this.errorHandlers.length > 0) {
// Call custom error handlers
this.errorHandlers.forEach(handler => handler(error));
} else {
// Default error behavior
console.error('WebSocket Error:', error);
}
reject(error);
};`
};
},
python: () => {
return {
onErrorMethod: `def on_error(self, ws, error):
print("WebSocket Error:", error)
self.handle_error(error)`
};
},
dart: () => {
return {
onErrorMethod: `onError: (error) {
if (_errorHandlers.isNotEmpty) {
for (var handler in _errorHandlers) {
handler(error);
}
} else {
print('WebSocket Error: $error');
}
},`
};
}
};

/**
* Component that renders WebSocket onError event handler for the specified programming language.
*
* @param {Object} props - Component properties.
* @param {SupportedLanguage} props.language - The programming language for which to generate onError handler code.
*/
export function OnError({ language }) {
let onErrorMethod = '';

if (websocketOnErrorMethod[language]) {
const generateErrorCode = websocketOnErrorMethod[language];
const errorResult = generateErrorCode();
onErrorMethod = errorResult.onErrorMethod;
}

return (
<Text>
{onErrorMethod}
</Text>
);
}
73 changes: 73 additions & 0 deletions packages/components/src/components/OnMessage.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import { Text } from '@asyncapi/generator-react-sdk';

/**
* @typedef {'python' | 'javascript' | 'dart'} SupportedLanguage
* Supported programming languages for WebSocket onMessage handler generation.
*/

/**
* Mapping of supported programming languages to their WebSocket onMessage event handler implementations.
*
* @type {Object.<SupportedLanguage, Function>}
*/
const websocketOnMessageMethod = {
javascript: () => {
return {
onMessageMethod: `// On receiving a message
this.websocket.onmessage = (event) => {
if (this.messageHandlers.length > 0) {
// Call custom message handlers
this.messageHandlers.forEach(handler => {
if (typeof handler === 'function') {
this.handleMessage(event.data, handler);
}
});
} else {
// Default message logging
console.log('Message received:', event.data);
}
};`
};
},
python: () => {
return {
onMessageMethod: `def on_message(self, ws, message):
self.handle_message(message)`
};
},
dart: () => {
return {
onMessageMethod: `(message) {
if (_messageHandlers.isNotEmpty) {
for (var handler in _messageHandlers) {
_handleMessage(message, handler);
}
} else {
print('Message received: $message');
}
},`
};
}
};

/**
* Component that renders WebSocket onMessage event handler for the specified programming language.
*
* @param {Object} props - Component properties.
* @param {SupportedLanguage} props.language - The programming language for which to generate onMessage handler code.
*/
export function OnMessage({ language }) {
let onMessageMethod = '';

if (websocketOnMessageMethod[language]) {
const generateOnMessageCode = websocketOnMessageMethod[language];
const messageResult = generateOnMessageCode();
onMessageMethod = messageResult.onMessageMethod;
}

return (
<Text>
{onMessageMethod}
</Text>
);
}
Loading
Loading