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(core): if provided options.request use instead #3944

Merged
merged 2 commits into from
Nov 2, 2024

Conversation

robstax
Copy link
Contributor

@robstax robstax commented Oct 30, 2024

COMPLETES https://jira-eng-gpk2.cisco.com/jira/browse/SPARK-574364

This pull request addresses

particular use case here, where we'd like to use postMessage instead of XHR to interact with a parent page instead of with a HTTP service in certain iframe scenarios
need ability for developers to provide their own request function instead of whatever is coded into SDK

by making the following changes

packages/@webex/http-core/src/request/index.js checks if there is a provided request and if so calls that instead

Change Type

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to change)
  • Documentation update
  • Tooling change
  • Internal code refactor

The following scenarios were tested

manually tested with and without custom request

I certified that

  • I have read and followed contributing guidelines

  • I discussed changes with code owners prior to submitting this pull request

  • I have not skipped any automated checks

  • All existing and new tests passed

  • I have updated the documentation accordingly


Make sure to have followed the contributing guidelines before submitting.

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Introduced flexibility in handling requests by allowing users to provide a custom request function.
  • Bug Fixes

    • Improved the accuracy of request handling and response interception.
  • Tests

    • Added a new test suite for the request function, enhancing coverage for both default and custom request scenarios.
    • Removed unused import from the test suite without affecting existing test logic.

@robstax robstax requested review from a team as code owners October 30, 2024 21:20
Copy link

coderabbitai bot commented Oct 30, 2024

Walkthrough

The changes in this pull request involve modifications to the request function in the @webex/http-core package, allowing for a custom request function to be optionally provided via the options object. If a custom function is specified, it is invoked; otherwise, the default _request function is used. Additionally, a new test suite has been introduced to validate the behavior of the request function, ensuring both default and custom request handling are properly tested. An unused import in the test files has also been removed.

Changes

File Change Summary
packages/@webex/http-core/src/request/index.js Modified request function to allow optional custom request function via options.request.
packages/@webex/http-core/test/unit/spec/index.js Removed unused import statement for utils.
packages/@webex/http-core/test/unit/spec/request/index.js Added a new test suite for the request function, validating both default and custom request handling.

Poem

In the meadow, requests take flight,
With options dancing, oh what a sight!
Custom paths now lead the way,
While tests ensure they’ll never stray.
Hops and skips, let’s celebrate,
Flexibility is truly great! 🐰✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 48ecb76 and 60c4018.

📒 Files selected for processing (3)
  • packages/@webex/http-core/src/request/index.js (1 hunks)
  • packages/@webex/http-core/test/unit/spec/index.js (0 hunks)
  • packages/@webex/http-core/test/unit/spec/request/index.js (1 hunks)
💤 Files with no reviewable changes (1)
  • packages/@webex/http-core/test/unit/spec/index.js
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/@webex/http-core/src/request/index.js
  • packages/@webex/http-core/test/unit/spec/request/index.js

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 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 resolve resolve all the CodeRabbit review comments.
  • @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.

@robstax robstax added the validated If the pull request is validated for automation. label Oct 30, 2024
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

🧹 Outside diff range and nitpick comments (2)
packages/@webex/http-core/src/request/index.js (1)

26-33: Update JSDoc to document the new options.request parameter.

The function's JSDoc should be updated to document the new capability of providing a custom request handler.

Add the following to the JSDoc:

 /**
  * @param {Object} options
+ * @param {Function} [options.request] - Optional custom request handler function
  * @returns {Promise}
  */
packages/@webex/http-core/test/unit/spec/request/index.js (1)

21-40: Consider enhancing test coverage and readability.

While the test effectively validates the core functionality, consider these improvements:

  1. Add assertions for the interceptor chain's behavior
  2. Use more descriptive test names that follow the given-when-then pattern
  3. Extract test data into named constants for better maintainability

Example improvement:

-  it('should modify options and call _request if no custom request function is provided', async () => {
+  it('given default configuration, when making a request, then should use internal request handler', async () => {
+    // Test setup
+    const TEST_URL = 'http://example.com';
+    const EXPECTED_RESPONSE = 'response';
     const options = {
-      url: 'http://example.com',
+      url: TEST_URL,
       headers: {},
       interceptors: [],
     };

-    requestStub.resolves('response');
+    requestStub.resolves(EXPECTED_RESPONSE);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between a807933 and 48ecb76.

📒 Files selected for processing (3)
  • packages/@webex/http-core/src/request/index.js (1 hunks)
  • packages/@webex/http-core/test/unit/spec/index.js (0 hunks)
  • packages/@webex/http-core/test/unit/spec/request/index.js (1 hunks)
💤 Files with no reviewable changes (1)
  • packages/@webex/http-core/test/unit/spec/index.js
🔇 Additional comments (5)
packages/@webex/http-core/src/request/index.js (2)

26-36: Implementation looks clean and maintains compatibility.

The changes:

  1. Preserve the existing Promise chain structure
  2. Maintain backward compatibility
  3. Correctly handle response interceptors
  4. Keep the event emitter functionality intact

28-30: Verify custom request handler compatibility.

The custom request handler must maintain compatibility with the SDK's interceptor chain and event emitter pattern. Consider adding validation or documentation to ensure custom implementations follow the expected interface.

Let's verify the usage pattern:

✅ Verification successful

The test file and implementation details will help us understand the expected interface and behavior of custom request handlers, particularly their interaction with interceptors and event emitters.


Based on the code analysis, I can now provide a final response:

Custom request handlers must implement interceptor chain and event emitter pattern

The custom request handler must:

  • Accept options object and spread args as parameters
  • Process the request after Request interceptors but before Response interceptors
  • Maintain compatibility with options.download and options.upload EventEmitters
  • Return a Promise that resolves with the response

Example usage shown in tests demonstrates proper integration with both patterns.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for existing request handler implementations to understand the interface
rg -l 'request\s*:\s*function' --type js

# Look for any documentation or examples of request handlers
fd -e md -e js -x grep -l 'request.*function'

Length of output: 925


Script:

#!/bin/bash
# Let's examine the test file to understand the expected interface and behavior
cat packages/@webex/http-core/test/unit/spec/request/index.js

# Also check the main implementation for any interface documentation
cat packages/@webex/http-core/src/request/index.js

# Look for any interceptor chain implementations
rg -A 5 "interceptor" packages/@webex/http-core/

Length of output: 19104

packages/@webex/http-core/test/unit/spec/request/index.js (3)

1-6: LGTM! Well-organized imports.

The imports are clean, purposeful, and include all necessary testing utilities and module dependencies.


8-19: LGTM! Robust test setup with proper cleanup.

The test suite follows best practices with proper initialization of test doubles and cleanup after each test.


1-58: Verify alignment with implementation details.

The tests look comprehensive, but let's verify that all implementation details from the main module are covered.

✅ Verification successful

Let me gather more information about the implementation details to ensure thorough verification.


Let me check the TypeScript utils file and the request implementation to complete the verification.


Tests adequately cover the implementation

The test file correctly verifies all the key aspects of the request implementation:

  • URL to URI conversion
  • Headers initialization
  • EventEmitter instances for download and upload
  • Interceptor calls (both for Request and Response phases)
  • Custom request function handling

The implementation in index.js and utils.ts aligns perfectly with the test scenarios, and no additional test cases are required as:

  1. The basic request flow is tested
  2. The interceptor functionality is verified
  3. The custom request override is covered
  4. The options transformation is validated
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if all exported functions from the request module are tested
# and if there are any additional configuration options that should be tested.

# Test: Look for exports and configuration options in the implementation
rg -t js "export|interface|type" packages/@webex/http-core/src/request/

Length of output: 1348


Script:

#!/bin/bash
# Check the actual implementation of the request function and its options
rg -A 10 "export default function request" packages/@webex/http-core/src/request/index.js

# Check for any interceptor-related code that might need testing
rg -A 5 "intercept" packages/@webex/http-core/src/request/utils.js

# Look for any type definitions or interfaces that might indicate required options
fd -e ts -e d.ts . packages/@webex/http-core/src/request/

Length of output: 601


Script:

#!/bin/bash
# Check the utils.ts file for interceptor implementation
cat packages/@webex/http-core/src/request/utils.ts

# Check the complete implementation of request.js
cat packages/@webex/http-core/src/request/index.js

# Check if there are any other test files for request
fd -e spec.js -e test.js . packages/@webex/http-core/test/

Length of output: 3283

Comment on lines +42 to +57
it('should use custom request function if provided', async () => {
const customRequest = sinon.stub().resolves('custom response');
const options = {
url: 'http://example.com',
headers: {},
interceptors: [],
request: customRequest,
};

const result = await request(options);

assert.strictEqual(result, 'custom response');
assert.isTrue(customRequest.calledOnceWith(options));
assert.isTrue(interceptStub.calledTwice);
assert.isFalse(requestStub.called);
});
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider adding edge case tests for custom request handling.

While the happy path is well tested, consider adding the following test cases:

  1. When custom request function throws an error
  2. When custom request function is not a function
  3. When custom request function returns invalid response

Example additional test:

it('should handle errors from custom request function gracefully', async () => {
  const customError = new Error('Custom request failed');
  const customRequest = sinon.stub().rejects(customError);
  const options = {
    url: 'http://example.com',
    headers: {},
    interceptors: [],
    request: customRequest
  };

  try {
    await request(options);
    assert.fail('Should have thrown an error');
  } catch (error) {
    assert.strictEqual(error, customError);
    assert.isTrue(customRequest.calledOnce);
    assert.isTrue(interceptStub.calledTwice);
    assert.isFalse(requestStub.called);
  }
});

Copy link

This pull request is automatically being deployed by Amplify Hosting (learn more).

Access this pull request here: https://pr-3944.d3m3l2kee0btzx.amplifyapp.com

@robstax robstax changed the title if provided options.request use instead feat(core): if provided options.request use instead Oct 31, 2024
@webex webex deleted a comment from coderabbitai bot Oct 31, 2024
@arun3528 arun3528 merged commit 1715035 into webex:next Nov 2, 2024
11 of 12 checks passed
@coderabbitai coderabbitai bot mentioned this pull request Nov 4, 2024
11 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
validated If the pull request is validated for automation.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants