Skip to content
Open
Show file tree
Hide file tree
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
17 changes: 9 additions & 8 deletions packages/components/src/components/QueryParamsVariables.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,23 +65,24 @@ const queryParamLogicConfig = {
},
},
javascript: (param) => {
const paramName = param[0];
const rawName = param[0];
const paramName = toCamelCase(rawName);
return {
variableDefinition: {
text: `const ${paramName} = ${paramName} || process.env.${paramName.toUpperCase()};`,
indent: 8,
text: `const _${rawName} = ${paramName} || process.env.${rawName.toUpperCase()};`,
indent: 0,
},
ifCondition: {
text: `if (${paramName}) {`,
indent: 8,
text: `if (_${rawName}) {`,
indent: 0,
},
assignment: {
text: `params["${paramName}"] = ${paramName};`,
indent: 10,
text: `params["${rawName}"] = _${rawName};`,
Comment on lines +68 to +80

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

rg -n -C 5 '\b(toCamelCase|getSafeJsName)\b' \
  packages/components/src/components/QueryParamsVariables.js \
  packages/templates/clients/websocket/javascript/components

rg -n -C 3 'auth-token|foo-bar|queryParams' \
  packages/components/test \
  packages/templates/clients/websocket/javascript/test

Repository: asyncapi/generator

Length of output: 28865


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- QueryParamsVariables.js ---'
cat -n packages/components/src/components/QueryParamsVariables.js

printf '%s\n' '--- getSafeJsName.js ---'
cat -n packages/templates/clients/websocket/javascript/components/getSafeJsName.js

printf '%s\n' '--- InitSignature.js ---'
cat -n packages/templates/clients/websocket/javascript/components/InitSignature.js

printf '%s\n' '--- component tests ---'
cat -n packages/components/test/components/QueryParamsVariables.test.js

printf '%s\n' '--- JavaScript snapshots ---'
rg -n -A18 -B3 'javascript' packages/components/test/components/__snapshots__/QueryParamsVariables.test.js.snap

printf '%s\n' '--- QueryParamsVariables usages ---'
rg -n -C3 '<QueryParamsVariables|QueryParamsVariables' packages --glob '*.{js,jsx,ts,tsx}'

Repository: asyncapi/generator

Length of output: 16195


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- helper usages and exports ---'
rg -n -C3 'getSafeJSName|QueryParamsVariables|QueryParamsArgumentsDocs|InitSignature' \
  packages/components packages/templates/clients/websocket/javascript

printf '%s\n' '--- JavaScript snapshot section ---'
sed -n '1,25p' packages/components/test/components/__snapshots__/QueryParamsVariables.test.js.snap

printf '%s\n' '--- helper source candidates ---'
rg -n -C5 'function toCamelCase|const toCamelCase|export .*toCamelCase' \
  packages

printf '%s\n' '--- package README principles ---'
sed -n '1,220p' packages/README.md

printf '%s\n' '--- deterministic safe-name probe ---'
python3 - <<'PY'
import re

def to_camel_case(name):
    # Probe the cases relevant to this review using the repository's helper
    # implementation if it is available as a readable source file.
    return name

def safe_js_name(name):
    safe = to_camel_case(name)
    safe = re.sub(r'[^a-zA-Z0-9_]', '_', safe)
    if re.match(r'^[0-9]', safe):
        safe = '_' + safe
    if safe in {
        'url', 'throwSendErrors', 'params', 'queryString',
        'class', 'const', 'let', 'var', 'if', 'else', 'return',
        'this', 'true', 'false', 'null', 'undefined',
    }:
        safe = '_' + safe
    return safe

for raw in ['auth-token', 'foo-bar', '1token', 'class', 'params', 'token']:
    print(raw, 'raw identifier:', f'const _{raw}', 'safe helper:', safe_js_name(raw))
PY

Repository: asyncapi/generator

Length of output: 50374


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- toCamelCase implementation ---'
rg -l 'toCamelCase' packages | while read -r file; do
  rg -n -C8 'toCamelCase' "$file"
done | head -n 180

printf '%s\n' '--- focused constructor composition ---'
cat -n packages/templates/clients/websocket/javascript/components/Constructor.js

printf '%s\n' '--- focused safe-name tests ---'
cat -n packages/templates/clients/websocket/javascript/test/components/getSafeJsName.test.js

printf '%s\n' '--- JavaScript syntax probe ---'
node - <<'JS'
const cases = [
  {
    name: 'auth-token',
    argument: 'authToken',
    raw: 'const _auth-token = authToken || process.env.AUTH-TOKEN;',
    corrected: 'const _authToken = authToken || process.env["AUTH-TOKEN"];',
  },
  {
    name: 'url',
    argument: '_url',
    raw: 'const _url = url || process.env.URL;',
    corrected: 'const __url = _url || process.env["URL"];',
  },
  {
    name: 'throw-send-errors',
    argument: '_throwSendErrors',
    raw: 'const _throw-send-errors = throwSendErrors || process.env.THROW-SEND-ERRORS;',
    corrected: 'const __throwSendErrors = _throwSendErrors || process.env["THROW-SEND-ERRORS"];',
  },
];

for (const item of cases) {
  for (const [label, source] of [['raw', item.raw], ['corrected', item.corrected]]) {
    try {
      new Function(`function f(${item.argument}) { ${source} }`);
      console.log(item.name, label, 'PARSES');
    } catch (error) {
      console.log(item.name, label, 'REJECTED:', error.message);
    }
  }
}
JS

Repository: asyncapi/generator

Length of output: 11961


Use safe constructor names in generated query code.

QueryParamsVariables must use the same getSafeJSName mapping as InitSignature. Names such as auth-token, 1st, and url can otherwise produce invalid or duplicate declarations. Use the safe name for all local references, process.env[JSON.stringify(...)] for environment variables, and JSON.stringify(rawName) for query keys. Add regression tests for non-identifier, reserved, and colliding names.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/components/src/components/QueryParamsVariables.js` around lines 68 -
80, Update QueryParamsVariables to reuse InitSignature’s getSafeJSName mapping
for generated local identifiers, applying safe names consistently in
declarations, conditions, and assignments. Generate environment lookups with
process.env[JSON.stringify(rawName)] and query keys with
JSON.stringify(rawName), then add regression coverage for non-identifier,
reserved, and colliding parameter names.

indent: 2,
},
closing: {
text: '}',
indent: 8,
indent: 0,
newLines: 1,
},
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,22 +28,22 @@ exports[`Testing of QueryParamsVariables component renders java quarkus query pa
`;

exports[`Testing of QueryParamsVariables component renders js query params correctly with query parameters 1`] = `
"const heartbeat = heartbeat || process.env.HEARTBEAT;
if (heartbeat) {
params[\\"heartbeat\\"] = heartbeat;
}
const top_of_book = top_of_book || process.env.TOP_OF_BOOK;
if (top_of_book) {
params[\\"top_of_book\\"] = top_of_book;
}
const bids = bids || process.env.BIDS;
if (bids) {
params[\\"bids\\"] = bids;
}
const offers = offers || process.env.OFFERS;
if (offers) {
params[\\"offers\\"] = offers;
}"
"const _heartbeat = heartbeat || process.env.HEARTBEAT;
if (_heartbeat) {
params[\\"heartbeat\\"] = _heartbeat;
}
const _top_of_book = topOfBook || process.env.TOP_OF_BOOK;
if (_top_of_book) {
params[\\"top_of_book\\"] = _top_of_book;
}
const _bids = bids || process.env.BIDS;
if (_bids) {
params[\\"bids\\"] = _bids;
}
const _offers = offers || process.env.OFFERS;
if (_offers) {
params[\\"offers\\"] = _offers;
}"
`;

exports[`Testing of QueryParamsVariables component renders python nothing when queryParams is null 1`] = `""`;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@ import { ModuleExport } from './ModuleExport';
import { CompileOperationSchemas } from './CompileOperationSchemas';
import { RegisterOutgoingProcessor } from './RegisterOutgoingProcessor';

export function ClientClass({ clientName, serverUrl, title, sendOperations }) {
export function ClientClass({ clientName, serverUrl, queryParams, title, sendOperations }) {
return (
<Text>
<Text newLines={2}>
{`class ${clientName} {`}
</Text>
<Constructor serverUrl={serverUrl} sendOperations={sendOperations} />
<Constructor serverUrl={serverUrl} queryParams={queryParams} sendOperations={sendOperations} />
<Connect language="javascript" title={title} />
<RegisterMessageHandler
language="javascript"
Expand Down
Original file line number Diff line number Diff line change
@@ -1,33 +1,52 @@
import { Text } from '@asyncapi/generator-react-sdk';
import { QueryParamsVariables } from '@asyncapi/generator-components';
import { InitSignature } from './InitSignature';
import { QueryParamsArgumentsDocs } from './QueryParamsArgumentsDocs';

export function Constructor({ serverUrl, sendOperations }) {
export function Constructor({ serverUrl, queryParams, sendOperations }) {
const sendOperationsId = sendOperations.map((operation) => operation.id());
const sendOperationsArray = JSON.stringify(sendOperationsId);
const queryParamsArray = queryParams && Array.from(queryParams.entries());

return (
<Text indent={2}>
{
`/*
{`/*
* Constructor to initialize the WebSocket client
* @param {string} url - The WebSocket server URL. Use it if the server URL is different from the default one taken from the AsyncAPI document.
* @param {boolean} [throwSendErrors=true] - Controls how the instance send methods react to a send failure.
`}
<QueryParamsArgumentsDocs queryParams={queryParamsArray} />
{` * @param {boolean} [throwSendErrors=true] - Controls how the instance send methods react to a send failure.
* When true (default) the error is re-thrown after the registered error handlers run, so the caller can
* handle each failure. When false the error is suppressed after the handlers run, which keeps a
* high-throughput producer loop going.
*/
constructor(url, throwSendErrors = true) {
this.url = url || '${serverUrl}';
this.websocket = null;
this.messageHandlers = [];
this.errorHandlers = [];
this.outgoingProcessors = [];
this.compiledSchemas = {};
this.schemasCompiled = false;
this.sendOperationsId = ${sendOperationsArray};
this.throwSendErrors = throwSendErrors; // Re-throw send failures after handlers run
`}
<InitSignature queryParams={queryParamsArray} />
<Text indent={2} newLines={1}>
{`this.url = url || '${serverUrl}';
`}
{queryParamsArray && queryParamsArray.length > 0 && (
<Text>
{`const params = {};
`}
<QueryParamsVariables language="javascript" queryParams={queryParamsArray} />
{`const queryString = querystring.stringify(params);
if (queryString) {
this.url += '?' + queryString;
}
`
}
`}
</Text>
)}
{`this.websocket = null;
this.messageHandlers = [];
this.errorHandlers = [];
this.outgoingProcessors = [];
this.compiledSchemas = {};
this.schemasCompiled = false;
this.sendOperationsId = ${sendOperationsArray};
this.throwSendErrors = throwSendErrors; // Re-throw send failures after handlers run`}
</Text>
{'}'}
</Text>
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { Text } from '@asyncapi/generator-react-sdk';
import { getSafeJSName } from './getSafeJsName';

/**
* Renders the constructor signature for the generated WebSocket client.
* Injects any query parameters into the signature with their default values (if provided in the AsyncAPI document).
*
* @param {Object} props - The component props.
* @param {Array<Array<string>>} [props.queryParams] - Array of query parameters from the AsyncAPI document, where each item is a tuple `[name, defaultValue]`.
* @returns {React.Element} The rendered React SDK Text element containing the constructor signature.
*/
export function InitSignature({ queryParams }) {
if (!queryParams || queryParams.length === 0) {
return (
<Text indent={0}>
{'constructor(url, throwSendErrors = true) {'}
</Text>
);
}

const usedNames = new Set();
const queryParamsArguments = queryParams.map((param) => {
const paramName = getSafeJSName(param[0], usedNames);
const paramDefaultValue = param[1];
let defaultValue = '';
if (paramDefaultValue !== undefined && paramDefaultValue !== null && paramDefaultValue !== '') {
const isBoolean = paramDefaultValue === 'true' || paramDefaultValue === 'false' || typeof paramDefaultValue === 'boolean';
const isNumber = typeof paramDefaultValue === 'number' || (!isNaN(parseFloat(paramDefaultValue)) && isFinite(paramDefaultValue));

if (isBoolean || isNumber) {
defaultValue = ` = ${paramDefaultValue}`;
} else {
defaultValue = ` = "${paramDefaultValue}"`;
}
}
return `${paramName}${defaultValue}`;
}).join(', ');
Comment thread
coderabbitai[bot] marked this conversation as resolved.

return (
<Text indent={0}>
{`constructor(url, ${queryParamsArguments}, throwSendErrors = true) {`}
</Text>
);
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { Text } from '@asyncapi/generator-react-sdk';
import { getSafeJSName } from './getSafeJsName';

/**
* Generates the JSDoc `@param` documentation blocks for each query parameter
* injected into the constructor signature.
*
* @param {Object} props - The component props.
* @param {Array<Array<string>>} [props.queryParams] - Array of query parameters from the AsyncAPI document, where each item is a tuple `[name, defaultValue]`.
* @returns {React.Element[] | null} An array of rendered React SDK Text elements containing the parameter documentation, or null if no query parameters exist.
*/
export function QueryParamsArgumentsDocs({ queryParams }) {
if (!queryParams || queryParams.length === 0) {
return null;
}

const usedNames = new Set();
return queryParams.map((param) => {
const originalParamName = param[0];
const paramName = getSafeJSName(originalParamName, usedNames);
const envVarName = originalParamName.toUpperCase().replace(/[^A-Z0-9_]/g, '_');
const firstLine = `* @param {string} ${paramName} - `;
const secondLine = `If provided (or if ${envVarName} environment variable is set), added as ?${originalParamName}=… to URL`;
return (
<Text indent={2}>
{`${firstLine}${secondLine}\n`}
</Text>
);
});
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { toCamelCase } from '@asyncapi/generator-helpers';

/**
* Converts a given string into a safe JavaScript identifier.
* It camelCases the string, replaces invalid characters, ensures it does not start with a digit,
* and avoids collisions with reserved words (including specific constructor parameters).
*
* @param {string} name - The original string (e.g., a query parameter name).
* @param {Set<string>} [usedNames=new Set()] - A set of already used names to prevent collisions.
* @returns {string} A safe JavaScript identifier.
*/
export function getSafeJSName(name, usedNames = new Set()) {
let safe = toCamelCase(name);
safe = safe.replace(/[^a-zA-Z0-9_]/g, '_');
if ((/^[0-9]/).test(safe)) {
safe = `_${safe}`;
}
const reserved = ['url', 'throwSendErrors', 'params', 'queryString', 'class', 'const', 'let', 'var', 'if', 'else', 'return', 'this', 'true', 'false', 'null', 'undefined'];
if (reserved.includes(safe)) safe = `_${safe}`;

let candidate = safe;
let suffix = 1;
while (usedNames.has(candidate)) {
candidate = `${safe}_${suffix++}`;
}
usedNames.add(candidate);

return candidate;
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Firstly I don't get point of this getSafeJsName becoz we can't just change param name given in the input asyncapi file. Secondly it is not a component it should be in file https://github.com/asyncapi/generator/blob/master/packages/helpers/src/utils.js

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

The main use of getSafeJsName is, if the paramName that the user has sent is, for example, user-id, as it is not valid js variable name it would give a syntax error so to cut that off we are basically using this function

Sure thing, I should have put this in the utils.js.
Also, since we can't change the paramName in the AsyncAPI doc, what if paramName is invalid? What can we actually do here??

Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
const WSClient = require('./test/temp/snapshotTestResult/client_slack/client.js');
// Example usage
const wsClient = new WSClient();

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

rg -n -C 6 'new WSClient|constructor\(|query|ticket|app_id' \
  packages/templates/clients/websocket/javascript \
  packages/templates/clients/websocket/test

Repository: asyncapi/generator

Length of output: 50375


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '--- tracked Slack-related files ---'
git ls-files packages/templates/clients/websocket | grep -Ei 'slack|fixture|snapshot' | head -80

echo '--- focused generated-client references ---'
rg -n -C 5 'class Slack|new WSClient|wss-primary\.slack\.com/link|ticket.*app_id|app_id.*ticket' \
  packages/templates/clients/websocket --glob '!**/*.python.snap' --glob '!**/node_modules/**' | head -240

echo '--- constructor generation ---'
sed -n '1,90p' packages/templates/clients/websocket/javascript/components/InitSignature.js
sed -n '1,90p' packages/templates/clients/websocket/javascript/components/Constructor.js

echo '--- example ---'
cat -n packages/templates/clients/websocket/javascript/example-slack.js

Repository: asyncapi/generator

Length of output: 27822


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '--- Slack fixture ---'
cat -n packages/templates/clients/websocket/test/__fixtures__/asyncapi-slack-client.yml | sed -n '1,90p'

echo '--- generated JavaScript constructor snapshot ---'
sed -n '1106,1165p' packages/templates/clients/websocket/test/integration-test/__snapshots__/integration.test.js.javascript.snap

echo '--- JavaScript Slack documentation and example references ---'
find packages/templates/clients/websocket/javascript -maxdepth 2 -type f -print | sort
rg -n -C 8 'apps\.connections\.open|ticket|app_id|example-slack|client_slack' \
  packages/templates/clients/websocket/javascript \
  packages/templates/clients/websocket/test/__fixtures__/asyncapi-slack-client.yml \
  packages/templates/clients/websocket/test/integration-test/__snapshots__/integration.test.js.javascript.snap

Repository: asyncapi/generator

Length of output: 50376


🏁 Script executed:

#!/bin/bash
set -euo pipefail

python3 - <<'PY'
import re
from pathlib import Path

fixture = Path("packages/templates/clients/websocket/test/__fixtures__/asyncapi-slack-client.yml").read_text()
snapshot = Path(
    "packages/templates/clients/websocket/test/integration-test/"
    "__snapshots__/integration.test.js.javascript.snap"
).read_text()

fixture_section = fixture.split("properties:", 1)[1].split("operations:", 1)[0]
assert re.search(r"^\s+ticket:\s*$", fixture_section, re.MULTILINE)
assert re.search(r"^\s+app_id:\s*$", fixture_section, re.MULTILINE)

constructor = re.search(
    r"constructor\(([^)]*)\) \{(?P<body>.*?)\n  \}",
    snapshot,
    re.DOTALL,
)
assert constructor, "Slack constructor not found"
signature = constructor.group(1)
body = constructor.group("body")

assert signature == "url, ticket, appId, throwSendErrors = true"
assert "ticket = " not in signature
assert "appId = " not in signature
assert "this.url = url || 'wss://wss-primary.slack.com/link';" in body
assert "params[\\\\\"ticket\\\\\"] = _ticket;" in body
assert "params[\\\\\"app_id\\\\\"] = _app_id;" in body

# Model the constructor's zero-argument path without executing repository code.
url = "wss://wss-primary.slack.com/link"
ticket = None
app_id = None
if ticket or None:
    url += "?ticket=" + ticket
if app_id or None:
    url += ("&" if "?" in url else "?") + "app_id=" + app_id

print("constructor signature:", signature)
print("zero-argument URL:", url)
print("zero-argument URL has ticket:", "ticket=" in url)
print("zero-argument URL has app_id:", "app_id=" in url)
assert url == "wss://wss-primary.slack.com/link"
PY

Repository: asyncapi/generator

Length of output: 346


🏁 Script executed:

#!/bin/bash
set -euo pipefail

python3 - <<'PY'
import re
from pathlib import Path

fixture = Path("packages/templates/clients/websocket/test/__fixtures__/asyncapi-slack-client.yml").read_text()
snapshot = Path(
    "packages/templates/clients/websocket/test/integration-test/"
    "__snapshots__/integration.test.js.javascript.snap"
).read_text()

fixture_section = fixture.split("properties:", 1)[1].split("operations:", 1)[0]
assert re.search(r"^\s+ticket:\s*$", fixture_section, re.MULTILINE)
assert re.search(r"^\s+app_id:\s*$", fixture_section, re.MULTILINE)

constructor = re.search(
    r"constructor\(([^)]*)\) \{(?P<body>.*?)\n  \}",
    snapshot,
    re.DOTALL,
)
assert constructor, "Slack constructor not found"
signature = constructor.group(1)
body = constructor.group("body")

assert signature == "url, ticket, appId, throwSendErrors = true"
assert "ticket = " not in signature
assert "appId = " not in signature
assert "this.url = url || 'wss://wss-primary.slack.com/link';" in body
assert "params[\\\\\"ticket\\\\\"] = _ticket;" in body
assert "params[\\\\\"app_id\\\\\"] = _app_id;" in body

url = "wss://wss-primary.slack.com/link"
ticket = None
app_id = None
if ticket or None:
    url += "?ticket=" + ticket
if app_id or None:
    url += ("&" if "?" in url else "?") + "app_id=" + app_id

print("constructor signature:", signature)
print("zero-argument URL:", url)
print("zero-argument URL has ticket:", "ticket=" in url)
print("zero-argument URL has app_id:", "app_id=" in url)
assert url == "wss://wss-primary.slack.com/link"
PY

Repository: asyncapi/generator

Length of output: 346


Pass Slack’s generated connection URL to WSClient.

new WSClient() omits the required ticket and app_id query parameters. Pass the url returned by apps.connections.open to new WSClient(url).

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/templates/clients/websocket/javascript/example-slack.js` at line 3,
Update the WSClient initialization in the example to pass the connection URL
returned by apps.connections.open, using new WSClient(url) so the required
ticket and app_id query parameters are preserved.


// Example of how custom message handler that operates on incoming messages can look like
function myHandler(message) {
console.log('====================');
console.log('\x1b[94mIncoming event from Slack\x1b[0m:', message);
console.log('====================');
}

async function main() {
wsClient.registerMessageHandler(myHandler);

try {
await wsClient.connect();

// Keep the process alive to receive Slack events
// The connection will stay open until you terminate the process
console.log('Listening for Slack events... Press Ctrl+C to exit.');
await new Promise(() => {});
} catch (error) {
console.error('Failed to connect to WebSocket:', error.message);
}
}

main();
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { File } from '@asyncapi/generator-react-sdk';
import { getClientName, getServerUrl, getServer, getInfo, getTitle } from '@asyncapi/generator-helpers';
import { getClientName, getServerUrl, getServer, getInfo, getTitle, getQueryParams } from '@asyncapi/generator-helpers';
import { FileHeaderInfo, DependencyProvider } from '@asyncapi/generator-components';
import { ClientClass } from '../components/ClientClass';

Expand All @@ -11,6 +11,13 @@ export default function ({ asyncapi, params }) {
const serverUrl = getServerUrl(server);
const sendOperations = asyncapi.operations().filterBySend();
const asyncapiFilepath = `${params.asyncapiFileDir}/asyncapi.yaml`;
const queryParams = getQueryParams(asyncapi.channels());

const dependencies = ['const path = require(\'path\');', `const asyncapiFilepath = path.resolve(__dirname, '${asyncapiFilepath}');`];
if (queryParams) {
dependencies.push('const querystring = require(\'querystring\');');
}

return (
<File name={params.clientFileName}>
<FileHeaderInfo
Expand All @@ -20,9 +27,9 @@ export default function ({ asyncapi, params }) {
/>
<DependencyProvider
language="javascript"
additionalDependencies={['const path = require(\'path\');', `const asyncapiFilepath = path.resolve(__dirname, '${asyncapiFilepath}');`]}
additionalDependencies={dependencies}
/>
<ClientClass clientName={clientName} serverUrl={serverUrl} title={title} sendOperations={sendOperations} />
<ClientClass clientName={clientName} serverUrl={serverUrl} queryParams={queryParams} title={title} sendOperations={sendOperations} />
</File>
);
}
Loading
Loading