Skip to content

Commit ede00d9

Browse files
chore: replace hardcode sendEchoMessage method in js websocket client (#1557)
Co-authored-by: Adi-204 <adiboghawala@gmail.com> Co-authored-by: Chan <bot+chan@asyncapi.io>
1 parent ec628cd commit ede00d9

File tree

9 files changed

+223
-57
lines changed

9 files changed

+223
-57
lines changed

packages/helpers/test/__fixtures__/asyncapi-websocket-query.yml

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ channels:
8181

8282
operations:
8383
noMessage:
84-
action: receive
84+
action: send
8585
channel:
8686
$ref: '#/channels/marketDataV1'
8787
summary: Operation with no messages
@@ -112,7 +112,7 @@ operations:
112112
- $ref: '#/channels/marketDataV1/messages/multipleExamples'
113113

114114
mixedMessageExamples:
115-
action: receive
115+
action: send
116116
channel:
117117
$ref: '#/channels/marketDataV1'
118118
summary: Mixed message example coverage
@@ -130,4 +130,4 @@ components:
130130
enum:
131131
- btcusd
132132
- ethbtc
133-
- ethusd
133+
- ethusd

packages/templates/clients/websocket/javascript/components/ClientClass.js

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,11 @@ import { Connect } from './Connect';
44
import { RegisterMessageHandler } from './RegisterMessageHandler';
55
import { RegisterErrorHandler } from './RegisterErrorHandler';
66
import { HandleMessage } from './HandleMessage';
7-
import { SendEchoMessage } from './SendEchoMessage';
7+
import { SendOperation } from './SendOperation';
88
import { CloseConnection } from './CloseConnection';
99
import { ModuleExport } from './ModuleExport';
1010

11-
export function ClientClass({ clientName, serverUrl, title }) {
11+
export function ClientClass({ clientName, serverUrl, title, sendOperations}) {
1212
return (
1313
<Text>
1414
<Text newLines={2}>
@@ -19,7 +19,7 @@ export function ClientClass({ clientName, serverUrl, title }) {
1919
<RegisterMessageHandler />
2020
<RegisterErrorHandler />
2121
<HandleMessage />
22-
<SendEchoMessage />
22+
<SendOperation sendOperations={sendOperations} clientName={clientName} />
2323
<CloseConnection />
2424
<Text>
2525
{'}'}

packages/templates/clients/websocket/javascript/components/SendEchoMessage.js

Lines changed: 0 additions & 22 deletions
This file was deleted.
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
import { Text } from '@asyncapi/generator-react-sdk';
2+
3+
export function SendOperation({ sendOperations, clientName }) {
4+
if (!sendOperations || sendOperations.length === 0) {
5+
return null;
6+
}
7+
8+
return (
9+
<>
10+
{sendOperations.map((operation) => (
11+
<Text newLines={2} indent={2}>
12+
{`
13+
/**
14+
* Sends a ${operation.id()} message over the WebSocket connection.
15+
*
16+
* @param {Object} message - The message payload to send. Should match the schema defined in the AsyncAPI document.
17+
* @param {WebSocket} [socket] - The WebSocket connection to use. If not provided, the client's own connection will be used.
18+
* @throws {TypeError} If message cannot be stringified to JSON
19+
* @throws {Error} If WebSocket connection is not in OPEN state
20+
*/
21+
static ${operation.id()}(message, socket) {
22+
try {
23+
socket.send(JSON.stringify(message));
24+
} catch (error) {
25+
console.error('Error sending ${operation.id()} message:', error);
26+
}
27+
}
28+
/**
29+
* Instance method version of ${operation.id()} that uses the client's own WebSocket connection.
30+
* @param {Object} message - The message payload to send
31+
* @throws {Error} If WebSocket connection is not established
32+
*/
33+
${operation.id()}(message){
34+
if(!this.websocket){
35+
throw new Error('WebSocket connection not established. Call connect() first.');
36+
}
37+
${clientName}.${operation.id()}(message, this.websocket);
38+
}
39+
`}
40+
</Text>
41+
))}
42+
</>
43+
);
44+
}

packages/templates/clients/websocket/javascript/example.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ async function main() {
2727

2828
while (true) {
2929
try {
30-
await WSClient.sendEchoMessage(message, wsClient.websocket);
30+
await wsClient.sendEchoMessage(message);
3131
} catch (error) {
3232
console.error('Error while sending message:', error);
3333
}

packages/templates/clients/websocket/javascript/template/client.js.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,14 +10,15 @@ export default function ({ asyncapi, params }) {
1010
const title = info.title();
1111
const clientName = getClientName(info, params.appendClientSuffix, params.customClientName);
1212
const serverUrl = getServerUrl(server);
13+
const sendOperations = asyncapi.operations().filterBySend();
1314
return (
1415
<File name={params.clientFileName}>
1516
<FileHeaderInfo
1617
info={info}
1718
server={server}
1819
/>
1920
<Requires />
20-
<ClientClass clientName={clientName} serverUrl={serverUrl} title={title} />
21+
<ClientClass clientName={clientName} serverUrl={serverUrl} title={title} sendOperations={sendOperations} />
2122
</File>
2223
);
2324
}

packages/templates/clients/websocket/javascript/test/__snapshots__/integration.test.js.snap

Lines changed: 72 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -93,17 +93,32 @@ class HoppscotchEchoWebSocketClient {
9393
}
9494
9595
/**
96-
* By default sends a message over a provided WebSocket connection.
97-
* Useful when you already have an established WebSocket connection
98-
* and want to send a message without creating a class instance.
99-
*
100-
* @param {Object} message - The message to send. It will be stringified to JSON.
101-
* @param {WebSocket} socket - An existing WebSocket connection to use for sending the message.
102-
*/
96+
* Sends a sendEchoMessage message over the WebSocket connection.
97+
*
98+
* @param {Object} message - The message payload to send. Should match the schema defined in the AsyncAPI document.
99+
* @param {WebSocket} [socket] - The WebSocket connection to use. If not provided, the client's own connection will be used.
100+
* @throws {TypeError} If message cannot be stringified to JSON
101+
* @throws {Error} If WebSocket connection is not in OPEN state
102+
*/
103103
static sendEchoMessage(message, socket) {
104-
const websocket = socket || this.websocket;
105-
websocket.send(JSON.stringify(message));
104+
try {
105+
socket.send(JSON.stringify(message));
106+
} catch (error) {
107+
console.error('Error sending sendEchoMessage message:', error);
108+
}
109+
}
110+
/**
111+
* Instance method version of sendEchoMessage that uses the client's own WebSocket connection.
112+
* @param {Object} message - The message payload to send
113+
* @throws {Error} If WebSocket connection is not established
114+
*/
115+
sendEchoMessage(message){
116+
if(!this.websocket){
117+
throw new Error('WebSocket connection not established. Call connect() first.');
118+
}
119+
HoppscotchEchoWebSocketClient.sendEchoMessage(message, this.websocket);
106120
}
121+
107122
108123
// Method to close the WebSocket connection
109124
close() {
@@ -211,17 +226,32 @@ class HoppscotchClient {
211226
}
212227
213228
/**
214-
* By default sends a message over a provided WebSocket connection.
215-
* Useful when you already have an established WebSocket connection
216-
* and want to send a message without creating a class instance.
217-
*
218-
* @param {Object} message - The message to send. It will be stringified to JSON.
219-
* @param {WebSocket} socket - An existing WebSocket connection to use for sending the message.
220-
*/
229+
* Sends a sendEchoMessage message over the WebSocket connection.
230+
*
231+
* @param {Object} message - The message payload to send. Should match the schema defined in the AsyncAPI document.
232+
* @param {WebSocket} [socket] - The WebSocket connection to use. If not provided, the client's own connection will be used.
233+
* @throws {TypeError} If message cannot be stringified to JSON
234+
* @throws {Error} If WebSocket connection is not in OPEN state
235+
*/
221236
static sendEchoMessage(message, socket) {
222-
const websocket = socket || this.websocket;
223-
websocket.send(JSON.stringify(message));
237+
try {
238+
socket.send(JSON.stringify(message));
239+
} catch (error) {
240+
console.error('Error sending sendEchoMessage message:', error);
241+
}
224242
}
243+
/**
244+
* Instance method version of sendEchoMessage that uses the client's own WebSocket connection.
245+
* @param {Object} message - The message payload to send
246+
* @throws {Error} If WebSocket connection is not established
247+
*/
248+
sendEchoMessage(message){
249+
if(!this.websocket){
250+
throw new Error('WebSocket connection not established. Call connect() first.');
251+
}
252+
HoppscotchClient.sendEchoMessage(message, this.websocket);
253+
}
254+
225255
226256
// Method to close the WebSocket connection
227257
close() {
@@ -330,17 +360,32 @@ class PostmanEchoWebSocketClientClient {
330360
}
331361
332362
/**
333-
* By default sends a message over a provided WebSocket connection.
334-
* Useful when you already have an established WebSocket connection
335-
* and want to send a message without creating a class instance.
336-
*
337-
* @param {Object} message - The message to send. It will be stringified to JSON.
338-
* @param {WebSocket} socket - An existing WebSocket connection to use for sending the message.
339-
*/
363+
* Sends a sendEchoMessage message over the WebSocket connection.
364+
*
365+
* @param {Object} message - The message payload to send. Should match the schema defined in the AsyncAPI document.
366+
* @param {WebSocket} [socket] - The WebSocket connection to use. If not provided, the client's own connection will be used.
367+
* @throws {TypeError} If message cannot be stringified to JSON
368+
* @throws {Error} If WebSocket connection is not in OPEN state
369+
*/
340370
static sendEchoMessage(message, socket) {
341-
const websocket = socket || this.websocket;
342-
websocket.send(JSON.stringify(message));
371+
try {
372+
socket.send(JSON.stringify(message));
373+
} catch (error) {
374+
console.error('Error sending sendEchoMessage message:', error);
375+
}
376+
}
377+
/**
378+
* Instance method version of sendEchoMessage that uses the client's own WebSocket connection.
379+
* @param {Object} message - The message payload to send
380+
* @throws {Error} If WebSocket connection is not established
381+
*/
382+
sendEchoMessage(message){
383+
if(!this.websocket){
384+
throw new Error('WebSocket connection not established. Call connect() first.');
385+
}
386+
PostmanEchoWebSocketClientClient.sendEchoMessage(message, this.websocket);
343387
}
388+
344389
345390
// Method to close the WebSocket connection
346391
close() {
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import path from 'path';
2+
import { render } from '@asyncapi/generator-react-sdk';
3+
import { Parser, fromFile } from '@asyncapi/parser';
4+
import { SendOperation } from '../../components/SendOperation';
5+
6+
const parser = new Parser();
7+
const asyncapi_websocket_query = path.resolve(__dirname, '../../../../../../helpers/test/__fixtures__/asyncapi-websocket-query.yml');
8+
9+
describe('Testing of SendOperation function', () => {
10+
let parsedAsyncAPIDocument;
11+
12+
beforeAll(async () => {
13+
const parseResult = await fromFile(parser, asyncapi_websocket_query).parse();
14+
parsedAsyncAPIDocument = parseResult.document;
15+
});
16+
17+
test('render websockets with send operations and client name', () => {
18+
const result = render(
19+
<SendOperation
20+
clientName='GeminiMarketDataWebsocketAPI'
21+
sendOperations={parsedAsyncAPIDocument.operations().filterBySend()}
22+
/>
23+
);
24+
const actual = result.trim();
25+
expect(actual).toMatchSnapshot();
26+
});
27+
28+
test('render websockets without send operations', () => {
29+
const result = render(
30+
<SendOperation
31+
clientName='GeminiMarketDataWebsocketAPI'
32+
sendOperations={null}
33+
/>
34+
);
35+
const actual = result.trim();
36+
expect(actual).toMatchSnapshot();
37+
});
38+
});
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
// Jest Snapshot v1, https://goo.gl/fbAQLP
2+
3+
exports[`Testing of SendOperation function render websockets with send operations and client name 1`] = `
4+
"/**
5+
* Sends a noMessage message over the WebSocket connection.
6+
*
7+
* @param {Object} message - The message payload to send. Should match the schema defined in the AsyncAPI document.
8+
* @param {WebSocket} [socket] - The WebSocket connection to use. If not provided, the client's own connection will be used.
9+
* @throws {TypeError} If message cannot be stringified to JSON
10+
* @throws {Error} If WebSocket connection is not in OPEN state
11+
*/
12+
static noMessage(message, socket) {
13+
try {
14+
socket.send(JSON.stringify(message));
15+
} catch (error) {
16+
console.error('Error sending noMessage message:', error);
17+
}
18+
}
19+
/**
20+
* Instance method version of noMessage that uses the client's own WebSocket connection.
21+
* @param {Object} message - The message payload to send
22+
* @throws {Error} If WebSocket connection is not established
23+
*/
24+
noMessage(message){
25+
if(!this.websocket){
26+
throw new Error('WebSocket connection not established. Call connect() first.');
27+
}
28+
GeminiMarketDataWebsocketAPI.noMessage(message, this.websocket);
29+
}
30+
31+
32+
/**
33+
* Sends a mixedMessageExamples message over the WebSocket connection.
34+
*
35+
* @param {Object} message - The message payload to send. Should match the schema defined in the AsyncAPI document.
36+
* @param {WebSocket} [socket] - The WebSocket connection to use. If not provided, the client's own connection will be used.
37+
* @throws {TypeError} If message cannot be stringified to JSON
38+
* @throws {Error} If WebSocket connection is not in OPEN state
39+
*/
40+
static mixedMessageExamples(message, socket) {
41+
try {
42+
socket.send(JSON.stringify(message));
43+
} catch (error) {
44+
console.error('Error sending mixedMessageExamples message:', error);
45+
}
46+
}
47+
/**
48+
* Instance method version of mixedMessageExamples that uses the client's own WebSocket connection.
49+
* @param {Object} message - The message payload to send
50+
* @throws {Error} If WebSocket connection is not established
51+
*/
52+
mixedMessageExamples(message){
53+
if(!this.websocket){
54+
throw new Error('WebSocket connection not established. Call connect() first.');
55+
}
56+
GeminiMarketDataWebsocketAPI.mixedMessageExamples(message, this.websocket);
57+
}"
58+
`;
59+
60+
exports[`Testing of SendOperation function render websockets without send operations 1`] = `""`;

0 commit comments

Comments
 (0)