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: customized http interceptors #863

Conversation

yy-wow
Copy link
Collaborator

@yy-wow yy-wow commented Oct 16, 2024

English | 简体中文

PR

PR Checklist

Please check if your PR fulfills the following requirements:

  • The commit message follows our Commit Message Guidelines
  • Tests for the changes have been added (for bug fixes / features)
  • Docs have been added / updated (for bug fixes / features)
  • Built its own designer, fully self-validated

PR Type

What kind of change does this PR introduce?

  • Bugfix
  • Feature
  • Code style update (formatting, local variables)
  • Refactoring (no functional changes, no api changes)
  • Build related changes
  • CI related changes
  • Documentation content changes
  • Other... Please describe:

Background and solution

What is the current behavior?

支持传入自定义的拦截器

Issue Number: N/A

What is the new behavior?

Does this PR introduce a breaking change?

  • Yes
  • No

Other information

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Introduced initHttp and createHttp methods for enhanced HTTP functionalities.
    • createHttp now supports customizable request interceptors, allowing for greater flexibility in handling HTTP communications.
    • Added a preRequest function to modify HTTP request configurations.
  • Bug Fixes

    • Improved error handling logic in the createHttp function to ensure more robust performance.

Copy link
Contributor

coderabbitai bot commented Oct 16, 2024

Walkthrough

The changes enhance the createHttp function in packages/http/src/index.js to support customizable request and response interceptors through new parameters, requestInterceptors and responseInterceptors. The function signature has been updated to default the options parameter to an empty object. Additionally, new exports initHttp and createHttp are introduced in packages/design-core/index.js, while a new preRequest function is added in designer-demo/src/main.js to modify HTTP request configurations.

Changes

File Path Change Summary
packages/design-core/index.js Added exports: initHttp and createHttp from @opentiny/tiny-engine-http.
designer-demo/src/main.js Added function preRequest(config) and utilized it as a request interceptor in createHttp.
packages/http/src/index.js Enhanced createHttp function to include requestInterceptors and responseInterceptors.
Updated function signatures for createHttp, initHttp, and useHttp (no changes in some).

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant DesignCore
    participant HttpModule

    User->>DesignCore: Call initHttp()
    DesignCore->>HttpModule: Initialize HTTP settings
    User->>DesignCore: Call createHttp(options)
    DesignCore->>HttpModule: Create HTTP instance with options
    HttpModule->>User: Return HTTP instance
Loading

🐰 "In the core of design, new functions bloom,
initHttp and createHttp clear the room.
With interceptors now, requests take flight,
Custom paths we weave, in the day and night.
Hopping through code, we celebrate this cheer,
For every new feature brings us closer, my dear!" 🐇✨


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.

@github-actions github-actions bot added enhancement New feature or request refactor-main refactor/develop branch feature labels Oct 16, 2024
Copy link
Contributor

@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: 3

🧹 Outside diff range and nitpick comments (1)
packages/http/src/index.js (1)

91-101: Consider adding type annotations or documentation for clarity.

Adding comments or using TypeScript type annotations (if applicable) to specify the expected structure of requestInterceptors and responseInterceptors can enhance code readability and maintainability.

Also applies to: 145-156

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 87c6dd1 and e52acb5.

📒 Files selected for processing (2)
  • packages/design-core/index.js (1 hunks)
  • packages/http/src/index.js (2 hunks)
🧰 Additional context used
🔇 Additional comments (2)
packages/design-core/index.js (1)

37-37: LGTM. Consider documentation updates.

The addition of initHttp and createHttp exports from @opentiny/tiny-engine-http looks good. This change provides easier access to HTTP-related functionality from the design core package.

To ensure this change aligns with the project's architecture and doesn't introduce any unintended side effects, please run the following verification:

#!/bin/bash
# Description: Verify the impact of new HTTP exports

# Test 1: Check if the exported functions are used elsewhere in the project
echo "Checking usage of initHttp and createHttp:"
rg --type js "import.*\{.*(?:initHttp|createHttp).*\}.*from.*['\"]@opentiny/tiny-engine-design-core['\"]" -g '!packages/design-core/index.js'

# Test 2: Verify if there are any existing HTTP-related utilities that might overlap
echo "Checking for existing HTTP-related utilities:"
rg --type js "(?:initHttp|createHttp|http\..*|axios\..*)" -g '!packages/design-core/index.js' -g '!packages/http/**'

Consider updating the project's documentation to reflect these new exports and provide usage examples for initHttp and createHttp.

packages/http/src/index.js (1)

147-156: Refactor responseInterceptors loop to handle control flow correctly.

Similar to the issue with requestInterceptors, the return statement inside the forEach callback does not control the loop as intended. This may result in all interceptors being registered, even when some conditions are met to skip them.

Refactor the loop using a for...of loop:

-  responseInterceptors.forEach((item) => {
+  for (const item of responseInterceptors) {
     if (Array.isArray(item)) {
       http.interceptors.response.use(...item)

-      return
+      continue
     }

     http.interceptors.response.use(item)
-  })
+  }

chilingling
chilingling previously approved these changes Oct 16, 2024
@yy-wow yy-wow added the ready_for_review This PR requires more reviews label Oct 16, 2024
Copy link
Contributor

@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: 1

🧹 Outside diff range and nitpick comments (2)
packages/design-core/index.js (2)

36-36: LGTM! Well-structured HTTP utility exports.

The addition of initHttp and createHttp exports follows the established pattern and promotes centralized access to HTTP utilities through the design-core package. This is a clean way to expose the new HTTP interceptor functionality.

This architectural approach:

  • Maintains consistency with other utility exports
  • Provides a single entry point for HTTP-related functionality
  • Enables better maintainability and dependency management

36-36: Consider adding JSDoc comments for the new exports.

To maintain consistency with other exports and improve developer experience, consider adding documentation that explains the purpose and usage of these HTTP utilities.

Example documentation:

+/** 
+ * Initializes HTTP client with global configuration
+ * @param {Object} config - Global HTTP client configuration
+ */
+/** 
+ * Creates an HTTP client instance with custom interceptors
+ * @param {Object} options - Configuration including requestInterceptors and responseInterceptors
+ * @returns {Object} Configured HTTP client instance
+ */
 export { initHttp, createHttp } from '@opentiny/tiny-engine-http'
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between a6effe0 and 3b3c7f7.

📒 Files selected for processing (2)
  • designer-demo/src/main.js (1 hunks)
  • packages/design-core/index.js (1 hunks)
🔇 Additional comments (2)
designer-demo/src/main.js (2)

15-15: LGTM: Import statement is correctly updated.

The addition of createHttp to the import statement is consistent with the new HTTP interceptor functionality.


25-25: Document and verify the HTTP client configuration.

Please address the following concerns:

  1. Document the purpose of force: true option
  2. Consider adding validation for the interceptors array
  3. Verify the global impact of this configuration on all HTTP requests

Let's verify the HTTP client usage across the codebase:

Consider adding a comment explaining the configuration:

+// Configure global HTTP client with organization context interceptor
 createHttp({ force: true,  requestInterceptors: [preRequest] })

Comment on lines +20 to +23
const preRequest = (config) => {
config.headers['x-org-name'] = 123
return config
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Several improvements needed for the preRequest interceptor.

The current implementation has potential issues:

  1. The hardcoded value '123' needs documentation explaining its purpose
  2. Missing error handling for undefined headers
  3. Direct mutation of the config object could cause side effects
  4. The purpose of 'x-org-name' header should be documented

Consider this safer implementation:

+/**
+ * HTTP request interceptor that adds organization context
+ * @param {Object} config - The axios request configuration
+ * @returns {Object} Modified config object
+ */
 const preRequest = (config) => {
-  config.headers['x-org-name'] = 123
+  return {
+    ...config,
+    headers: {
+      ...config.headers,
+      'x-org-name': '123' // TODO: Document the purpose of this value
+    }
+  }
-  return config
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const preRequest = (config) => {
config.headers['x-org-name'] = 123
return config
}
/**
* HTTP request interceptor that adds organization context
* @param {Object} config - The axios request configuration
* @returns {Object} Modified config object
*/
const preRequest = (config) => {
return {
...config,
headers: {
...config.headers,
'x-org-name': '123' // TODO: Document the purpose of this value
}
}
}

@yy-wow yy-wow marked this pull request as draft October 29, 2024 12:08
@yy-wow yy-wow closed this Nov 11, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request ready_for_review This PR requires more reviews refactor-main refactor/develop branch feature
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants