Skip to content

Conversation

Adi-204
Copy link
Member

@Adi-204 Adi-204 commented Mar 25, 2025

Description
Add new helper function getServer() also written test for it.

image

Related issue(s)
Fixes #1408

Summary by CodeRabbit

  • New Features

    • Introduced a new function for retrieving server configurations with improved error handling.
    • Updated WebSocket client templates for JavaScript and Python to utilize the new server retrieval method, enhancing clarity and efficiency.
  • Tests

    • Added new tests to verify correct server selection and ensure robust handling of missing or invalid server configurations.

Copy link

changeset-bot bot commented Mar 25, 2025

⚠️ No Changeset found

Latest commit: 9d83869

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

Copy link

coderabbitai bot commented Mar 25, 2025

Walkthrough

The pull request introduces a new utility function, getServer, in the helpers module. This function retrieves a server object from a collection of AsyncAPI servers and throws an error if the specified server is not found. Both the source and test files in the helpers package have been updated to export and validate this new function. Additionally, client templates in both JavaScript and Python have been updated to use getServer for obtaining server configuration instead of directly accessing the server data.

Changes

File(s) Change Summary
packages/helpers/src/index.js
packages/helpers/src/servers.js
Added new getServer function; refactored getServerUrl declaration; updated module exports to include both functions with enhanced documentation.
packages/helpers/test/servers.test.js Introduced a new test suite for getServer, covering valid server retrieval and error scenarios for missing/empty server names.
packages/templates/clients/.../template/README.md.js
packages/templates/clients/.../template/client.js.js
packages/templates/clients/.../template/client.py.js
Updated import statements and server access logic to use getServer in both JS and Python client templates, replacing direct server retrieval calls.

Assessment against linked issues

Objective Addressed Explanation
Ensure template requires server configuration (#1408) The changes do not implement a check for the presence of a server or throw an error if no server is present.

Possibly related PRs

  • feat: add the template for README.md #1368: The changes in the main PR, which involve adding the getServer function to the exports in index.js, are directly related to the modifications in the retrieved PR, as both involve the introduction and usage of the getServer function in the context of server retrieval.

Suggested labels

ready-to-merge

Suggested reviewers

  • derberg
  • asyncapi-bot-eve
  • jonaslagoni

Poem

I'm a clever rabbit with code in my paws,
Hopping through changes without a pause.
I’ve added a function to fetch the server just right,
Throwing errors if it hides out of sight.
Celebrate with a hop—this PR shines bright! 🐰✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b71577d and 9d83869.

📒 Files selected for processing (1)
  • packages/helpers/src/servers.js (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/helpers/src/servers.js
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Test generator as dependency with Node 20
  • GitHub Check: Test generator as dependency with Node 18
  • GitHub Check: Test NodeJS PR - windows-latest

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

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)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@asyncapi-bot
Copy link
Contributor

Hello, @coderabbitai[bot]! 👋🏼

    I'm 🧞🧞🧞 Genie 🧞🧞🧞 from the magic lamp. Looks like somebody needs a hand!

    At the moment the following comments are supported in pull requests:

    - `/please-take-a-look` or `/ptal` - This comment will add a comment to the PR asking for attention from the reviewrs who have not reviewed the PR yet.
    - `/ready-to-merge` or `/rtm` - This comment will trigger automerge of PR in case all required checks are green, approvals in place and do-not-merge label is not added
    - `/do-not-merge` or `/dnm` - This comment will block automerging even if all conditions are met and ready-to-merge label is added
    - `/autoupdate` or `/au` - This comment will add `autoupdate` label to the PR and keeps your PR up-to-date to the target branch's future changes. Unless there is a merge conflict or it is a draft PR. (Currently only works for upstream branches.)
    - `/update` or `/u` - This comment will update the PR with the latest changes from the target branch. Unless there is a merge conflict or it is a draft PR. NOTE: this only updates the PR once, so if you need to update again, you need to call the command again.

Copy link

coderabbitai bot commented Mar 25, 2025

@asyncapi-bot Thank you for the information about the available commands in pull requests. These are helpful for managing PR workflow!

I see this PR is about adding a new helper function getServer() along with tests. If you'd like me to review these changes, just let me know, and I'll be happy to help.

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (2)
packages/helpers/src/index.js (1)

4-8: Consider maintaining alphabetical ordering in exports.

The new getServer export is added at the end, but the export ordering could be more maintainable if kept alphabetical. Consider reordering to:

 module.exports = {
   getClientName,
+  getServer,
   getServerUrl,
-  getClientName,
-  getServer
 };

This is a minor nitpick and doesn't affect functionality.

packages/helpers/test/servers.test.js (1)

75-77: Consider testing null and undefined server names.

The test suite covers empty string server names, but consider also testing with null and undefined values to ensure complete error handling coverage.

it('should throw error when server name is not provided', () => {
  const serverName = '';

  expect(() => {
    getServer(servers, serverName);
  }).toThrow(`Server ${serverName} not found in AsyncAPI document.`);
});

+it('should throw error when server name is null', () => {
+  const serverName = null;
+
+  expect(() => {
+    getServer(servers, serverName);
+  }).toThrow(`Server ${serverName} not found in AsyncAPI document.`);
+});
+
+it('should throw error when server name is undefined', () => {
+  expect(() => {
+    getServer(servers, undefined);
+  }).toThrow(`Server undefined not found in AsyncAPI document.`);
+});
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0aa211d and 121c64a.

📒 Files selected for processing (6)
  • packages/helpers/src/index.js (1 hunks)
  • packages/helpers/src/servers.js (1 hunks)
  • packages/helpers/test/servers.test.js (2 hunks)
  • packages/templates/clients/js/websocket/template/README.md.js (1 hunks)
  • packages/templates/clients/js/websocket/template/client.js.js (1 hunks)
  • packages/templates/clients/python/websocket/template/client.py.js (1 hunks)
🧰 Additional context used
🪛 GitHub Check: Test NodeJS PR - ubuntu-latest
packages/helpers/src/servers.js

[failure] 44-44:
Missing semicolon


[failure] 39-39:
Missing semicolon

🪛 GitHub Actions: PR testing - if Node project
packages/helpers/src/servers.js

[error] 39-39: ESLint: Missing semicolon (semi)

⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Test generator as dependency with Node 20
  • GitHub Check: Test generator as dependency with Node 18
🔇 Additional comments (12)
packages/helpers/src/index.js (1)

1-1: Good addition of the new helper function.

The import now includes getServer alongside the existing getServerUrl, which maintains the module's pattern of importing related functions together.

packages/templates/clients/js/websocket/template/README.md.js (2)

2-2: Good use of named imports.

The import statement now includes getServer alongside getClientName, maintaining a clean and explicit import style.


5-5: Improved error handling with new helper function.

Replacing the direct server access with the new getServer helper function enhances error handling for cases where the specified server doesn't exist. This is a good improvement that makes the code more robust.

packages/templates/clients/js/websocket/template/client.js.js (2)

2-2: Good addition of the new helper to imports.

The import statement has been updated appropriately to include the new getServer function alongside the existing helpers.


8-8: Improved server retrieval with consistent error handling.

Replacing direct server access with the getServer helper function ensures consistent error handling across the codebase. This is a good practice that improves code reliability.

packages/helpers/test/servers.test.js (3)

3-3: Good inclusion of the new helper in test imports.

The import statement has been updated to include getServer alongside the existing getServerUrl function, which is consistent with the implementation file.


44-79: Well-structured test suite with good coverage.

The test suite for the new getServer function is comprehensive and follows best practices:

  1. Tests the happy path (server exists)
  2. Tests error handling (server doesn't exist)
  3. Tests edge cases (empty server name)

Each test has clear assertions and good naming that describes the expected behavior. The setup is properly organized with the beforeAll hook to avoid code duplication.


44-79:

✅ Verification successful

Verify server implementation with a validation script.

Let's verify that the implementation of getServer in the servers.js file properly checks for server existence and throws the expected error.


🏁 Script executed:

#!/bin/bash
# Check the implementation of getServer in servers.js

echo "Checking for getServer implementation in servers.js"
if [ -f "packages/helpers/src/servers.js" ]; then
  cat packages/helpers/src/servers.js
else
  echo "servers.js not found at expected location"
  find packages/helpers/src -type f -name "*.js" | xargs grep -l "getServer"
fi

Length of output: 1748


Verified GetServer Implementation – No Changes Required

The implementation of getServer in packages/helpers/src/servers.js correctly checks for server existence in the provided servers map and throws the expected error when the server is not found. The reviewed test cases in packages/helpers/test/servers.test.js appropriately confirm this behavior.

No modifications are needed.

packages/templates/clients/python/websocket/template/client.py.js (2)

2-2: Import updated to include the new helper function.

The import statement has been correctly updated to include the new getServer helper function alongside the existing helpers.


8-8: Improved server retrieval with error handling.

Replacing the direct server access with the getServer helper function enhances the code by adding proper error handling when a specified server is not found. This change makes the code more robust and consistent with other templates.

packages/helpers/src/servers.js (2)

8-22: Export style modified for consistency.

The getServerUrl function has been refactored from a direct module export to a constant declaration, which aligns with the new consolidated export pattern at the end of the file. The function's logic remains unchanged.


46-46: Informative TODO comment for future development.

The TODO comment provides valuable context about the organization of helper functions and indicates the direction for future improvements.

* @returns {object} The AsyncAPI server object corresponding to the given server name.
*/
const getServer = (servers, serverName) => {
if (serverName && servers.has(serverName)) {
Copy link
Member

Choose a reason for hiding this comment

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

servers can also be undefined

Copy link
Member Author

Choose a reason for hiding this comment

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

@derberg I will add that any more suggested changes?

Copy link
Member

Choose a reason for hiding this comment

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

no, only this

probably servers = parsedAsyncAPIDocument.servers(); should not be part of beforeAll

Copy link

@coderabbitai coderabbitai bot left a 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 (2)
packages/helpers/src/servers.js (2)

24-39: Well-implemented new helper function with proper error handling.

The new getServer function is well-documented with JSDoc comments and implements appropriate error handling when a server isn't found. This abstraction improves code quality across templates by centralizing server retrieval logic.

However, you might want to enhance the error handling for edge cases:

const getServer = (servers, serverName) => {
-  if (serverName && servers.has(serverName)) {
+  if (!serverName) {
+    throw new Error('Server name must be provided.');
+  }
+  if (servers.has(serverName)) {
    return servers.get(serverName);
  }
-  throw new Error(`Server ${serverName} not found in AsyncAPI document.`);
+  throw new Error(`Server "${serverName}" not found in AsyncAPI document. Available servers: ${Array.from(servers.keys()).join(', ')}`);
};

This would provide more context in error messages and handle empty server names more explicitly.


46-46: Consider turning TODO into a more formal JSDoc module description.

This TODO comment provides valuable context about the file's purpose, but it might be better as a formal JSDoc module description at the top of the file.

+/**
+ * Helpers for working with AsyncAPI server objects.
+ * 
+ * This file contains utilities for extracting and manipulating data from 
+ * server objects in AsyncAPI documents, including URL construction and server retrieval.
+ * Future helpers may include variable extraction, security handling, etc.
+ * @module servers
+ */

/**
 * Get server URL from AsyncAPI server object.
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 121c64a and bc5b7fa.

📒 Files selected for processing (1)
  • packages/helpers/src/servers.js (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Test generator as dependency with Node 18
  • GitHub Check: Test generator as dependency with Node 20
  • GitHub Check: Test NodeJS PR - windows-latest
🔇 Additional comments (2)
packages/helpers/src/servers.js (2)

8-8: Code style improvement with consistent function declaration.

The function declaration has been updated to use the constant pattern instead of direct export, which aligns better with the module exports pattern used at the end of the file. This improves code organization and maintainability.


41-44: Improved export pattern for better maintainability.

Consolidating exports into a single object is a better practice than individual exports, making it easier to see all available functions at a glance.

@Adi-204
Copy link
Member Author

Adi-204 commented Mar 25, 2025

@derberg should I throw different type of errors as suggested by coderabbit or is it ok to throw only 1 type of error. According to me coderabbit suggestion is nice.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (2)
packages/helpers/test/servers.test.js (1)

47-51: Consider initializing servers in the beforeAll hook

Since you're accessing servers in each test case, consider initializing it once in the beforeAll hook to avoid repetition.

 beforeAll(async () => {
   const parseResult = await fromFile(parser, asyncapi_v3_path).parse();
   parsedAsyncAPIDocument = parseResult.document;
+  servers = parsedAsyncAPIDocument.servers();
 });
packages/helpers/src/servers.js (1)

35-37: Consider checking for undefined/null servers

Based on a previous comment from derberg, servers can be undefined. Your check handles this case correctly, but consider making the error message more specific about the expected Map type.

-  if (!servers) {
-    throw new Error('No server found in AsyncAPI document.');
+  if (!servers) {
+    throw new Error('Server map is undefined or null. A valid Map of AsyncAPI servers must be provided.');
🧰 Tools
🪛 GitHub Check: Test NodeJS PR - ubuntu-latest

[failure] 35-35:
Missing space before opening brace


[failure] 35-35:
Expected space(s) after "if"

🪛 GitHub Actions: PR testing - if Node project

[error] 35-35: ESLint: Expected space(s) after 'if' (keyword-spacing)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between bc5b7fa and ca8f5a9.

📒 Files selected for processing (2)
  • packages/helpers/src/servers.js (1 hunks)
  • packages/helpers/test/servers.test.js (2 hunks)
🧰 Additional context used
🪛 GitHub Check: Test NodeJS PR - ubuntu-latest
packages/helpers/test/servers.test.js

[failure] 46-46:
'servers' is defined but never used

packages/helpers/src/servers.js

[failure] 38-38:
Missing space before opening brace


[failure] 38-38:
Expected space(s) after "if"


[failure] 35-35:
Missing space before opening brace


[failure] 35-35:
Expected space(s) after "if"

🪛 GitHub Actions: PR testing - if Node project
packages/helpers/src/servers.js

[error] 35-35: ESLint: Expected space(s) after 'if' (keyword-spacing)

⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Test generator as dependency with Node 20
  • GitHub Check: Test generator as dependency with Node 18
🔇 Additional comments (4)
packages/helpers/test/servers.test.js (2)

44-84: Well-structured test suite for the new getServer helper

The test cases thoroughly cover the main scenarios: successful retrieval of an existing server, error handling for non-existent servers, and validation of empty server names. This provides good test coverage for the new functionality.

🧰 Tools
🪛 GitHub Check: Test NodeJS PR - ubuntu-latest

[failure] 46-46:
'servers' is defined but never used


65-73: Good error message testing

The test effectively validates that the error message includes both the server name and a list of available servers, which will be helpful for debugging.

packages/helpers/src/servers.js (2)

41-43: Helpful error message with available servers

Listing the available servers in the error message is a nice touch that will help developers quickly identify and fix issues.


47-50: Improved module export pattern

The consolidated export approach is better than individual exports, making it easier to see all available functions at a glance.

Copy link

@coderabbitai coderabbitai bot left a 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 (1)
packages/helpers/src/servers.js (1)

52-52: Consider enhancing the TODO comment.

The TODO comment provides good context but seems to be describing the current state rather than future work. Consider rephrasing it to more clearly indicate what specific enhancements are planned.

-//TODO: this separate file for helpers for servers represents approach to keep all helpers in separate files related to extractions of data from specific high level AsyncAPI objects. Here we will have more helpers for example related to variables extraction from servers, security, etc.
+//TODO: Add more helper functions for extracting data from server objects, such as variables, security requirements, etc. This follows our approach of organizing helpers by AsyncAPI object type.
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ca8f5a9 and 20208ca.

📒 Files selected for processing (2)
  • packages/helpers/src/servers.js (1 hunks)
  • packages/helpers/test/servers.test.js (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/helpers/test/servers.test.js
🧰 Additional context used
🧬 Code Definitions (1)
packages/helpers/src/servers.js (3)
packages/templates/clients/js/websocket/template/client.js.js (2)
  • server (8-8)
  • serverName (12-12)
packages/templates/clients/python/websocket/template/client.py.js (1)
  • server (8-8)
packages/templates/clients/js/websocket/template/README.md.js (1)
  • server (5-5)
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: Test generator as dependency with Node 20
  • GitHub Check: Test generator as dependency with Node 18
  • GitHub Check: Test NodeJS PR - macos-13
  • GitHub Check: Test NodeJS PR - windows-latest
🔇 Additional comments (4)
packages/helpers/src/servers.js (4)

8-22: Well-structured function definition!

Converting getServerUrl from a direct export to a local constant is a good practice. This change aligns with the new consolidated export pattern at the end of the file.


24-45: Well-implemented new helper function with comprehensive error handling.

The new getServer function is well-documented with detailed JSDoc comments and properly handles three critical error cases:

  1. Missing servers collection
  2. Missing server name
  3. Server not found in the collection

The error message for the third case is particularly helpful as it includes the list of available servers, which will aid debugging when an incorrect server name is provided.


47-50: Improved export pattern for better maintainability.

Consolidating exports into a single object is a better practice than individual exports, making it easier to see all available functions at a glance.


34-45:

✅ Verification successful

Verify integration with template clients.

The implementation looks solid. Based on the provided code snippets, this function is being used in multiple template clients, which is a good sign of its utility.


🏁 Script executed:

#!/bin/bash
# Check how the getServer function is used across the codebase
rg -A 2 -B 2 "getServer\(.*servers\(\)" --glob "*.js"

Length of output: 1547


Integration Verified: Template Clients Confirmed

The implementation of getServer is solid and its integration has been verified. The function is consistently used across multiple template clients, including:

  • packages/templates/clients/js/websocket/template/client.js.js
  • packages/templates/clients/python/websocket/template/client.py.js
  • packages/templates/clients/js/websocket/template/README.md.js

No changes are required based on the current usage.

@Adi-204
Copy link
Member Author

Adi-204 commented Mar 25, 2025

@derberg any more suggestion from your side? thanks : )

*/
const getServer = (servers, serverName) => {
if (!servers) {
throw new Error('No server found in AsyncAPI document.');
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
throw new Error('No server found in AsyncAPI document.');
throw new Error('Provided AsyncAPI document doesn\'t contain Servers object.');

Copy link

@coderabbitai coderabbitai bot left a 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 (2)
packages/helpers/src/servers.js (2)

24-45: Well-implemented new helper function with proper error handling

The new getServer function provides excellent error handling for different scenarios:

  1. When servers collection is missing
  2. When server name is not provided
  3. When the specified server doesn't exist in the collection

I particularly like the detailed error message for the missing server case that includes available servers, which will help developers debug issues.

Consider using custom error classes instead of generic Error for better error type distinction. This would allow consumers to catch specific error types:

+ class ServersNotFoundError extends Error {
+   constructor(message) {
+     super(message);
+     this.name = 'ServersNotFoundError';
+   }
+ }
+ 
+ class ServerNameNotProvidedError extends Error {
+   constructor(message) {
+     super(message);
+     this.name = 'ServerNameNotProvidedError';
+   }
+ }
+ 
+ class ServerNotFoundError extends Error {
+   constructor(message) {
+     super(message);
+     this.name = 'ServerNotFoundError';
+   }
+ }
+
 const getServer = (servers, serverName) => {
   if (!servers) {
-    throw new Error('Provided AsyncAPI document doesn\'t contain Servers object.');
+    throw new ServersNotFoundError('Provided AsyncAPI document doesn\'t contain Servers object.');
   }
   if (!serverName) {
-    throw new Error('Server name must be provided.');
+    throw new ServerNameNotProvidedError('Server name must be provided.');
   }
   if (!servers.has(serverName)) {
-    throw new Error(`Server "${serverName}" not found in AsyncAPI document. Available servers: ${Array.from(servers.keys()).join(', ')}`);
+    throw new ServerNotFoundError(`Server "${serverName}" not found in AsyncAPI document. Available servers: ${Array.from(servers.keys()).join(', ')}`);
   }
   return servers.get(serverName);
 };

52-52: Consider converting TODO comment to a formal ticket

While the comment provides good context about the file's purpose and future plans, it would be better to track it in an issue tracking system rather than leaving it as a TODO in the code. This ensures the task won't be forgotten and can be properly prioritized.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 20208ca and b71577d.

📒 Files selected for processing (1)
  • packages/helpers/src/servers.js (1 hunks)
🧰 Additional context used
🧬 Code Definitions (1)
packages/helpers/src/servers.js (3)
packages/templates/clients/js/websocket/template/client.js.js (2)
  • server (8-8)
  • serverName (12-12)
packages/templates/clients/python/websocket/template/client.py.js (1)
  • server (8-8)
packages/templates/clients/js/websocket/template/README.md.js (1)
  • server (5-5)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Test generator as dependency with Node 18
  • GitHub Check: Test generator as dependency with Node 20
  • GitHub Check: Test NodeJS PR - windows-latest
🔇 Additional comments (2)
packages/helpers/src/servers.js (2)

8-22: LGTM - Good function implementation

The function has been properly transformed into a named constant. The implementation is clean and well-documented with appropriate JSDoc comments.


47-50: Improved export pattern for better maintainability

Consolidating exports into a single object is a good practice, making it easier to see all available functions at a glance and maintain the interface. This change aligns with modern JavaScript patterns.

@Adi-204
Copy link
Member Author

Adi-204 commented Mar 25, 2025

@derberg changes done 👍

Copy link

@derberg
Copy link
Member

derberg commented Mar 26, 2025

/rtm

@asyncapi-bot asyncapi-bot merged commit 289e70d into asyncapi:master Mar 26, 2025
15 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Draft]: Ensure Template Requires Server Configuration

3 participants