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: refactor http as a configurable service #834

Draft
wants to merge 1 commit into
base: refactor/develop
Choose a base branch
from

Conversation

chilingling
Copy link
Member

@chilingling chilingling commented Sep 30, 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

Release Notes

  • New Features

    • Introduced an HTTP service for improved user login and session management.
    • Added global error notification system for API call errors.
  • Improvements

    • Enhanced HTTP service configuration and error handling for better maintainability.
    • Streamlined the export structure for easier access to HTTP functionalities.
  • Bug Fixes

    • Improved handling of session expiration and error responses during API interactions.
  • Chores

    • Removed deprecated HTTP-related files to declutter the codebase.

Copy link
Contributor

coderabbitai bot commented Sep 30, 2024

Walkthrough

The changes involve several modifications across multiple files, primarily enhancing the HTTP service functionality in the application. Key updates include the introduction of a new HTTP management module, adjustments to existing exports, and the removal of outdated configurations. The structure of the exported objects has been refined, and error handling mechanisms have been improved to provide a more robust user experience during API interactions.

Changes

File(s) Change Summary
designer-demo/registry.js Added http import and configuration, updated metas array to include GenerateCodeService, and modified canvas property formatting.
designer-demo/src/http/index.js Introduced a Vue.js application for user login and session handling, including error notification mechanisms, session callbacks, and configuration settings.
packages/design-core/index.js Added new export for the http module from @opentiny/tiny-engine-http, expanding available functionalities.
packages/http/index.js Removed the file that aggregated and exported metadata related to HTTP operations.
packages/http/src/config.js Deleted the configuration file that generated settings based on environment variables, including base URL and headers.
packages/http/src/index.js Restructured HTTP service implementation, simplifying imports, updating response handling, and refining interceptor configurations. Added a new useHttp method.
packages/http/vite.config.js Modified Rollup output configuration by removing the banner option from the output settings.

Possibly related PRs

Poem

🐇 In the garden where code does bloom,
A new HTTP service makes room.
With error handling bright and clear,
Login flows now bring good cheer.
So hop along, let’s celebrate,
For changes here will elevate! 🎉


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 Sep 30, 2024
@chilingling chilingling marked this pull request as draft September 30, 2024 03:18
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: 6

🧹 Outside diff range and nitpick comments (8)
designer-demo/registry.js (3)

47-47: LGTM: Addition of http import and configuration

The addition of http import from '@opentiny/tiny-engine' and httpConfig from './src/http' aligns well with the PR's objective of making the HTTP service configurable. Separating the HTTP configuration into its own file is a good practice for modularity.

Consider grouping related imports together for better readability. You could move the httpConfig import next to the http import from '@opentiny/tiny-engine'.

Also applies to: 50-50


Line range hint 55-55: LGTM: Updates to the exported configuration object

The changes to the exported configuration object are well-aligned with the PR objectives:

  1. Addition of GenerateCodeService to the metas array in the root object.
  2. Addition of the http property with configuration options.

These changes effectively integrate the new HTTP service configuration into the existing structure.

Consider adding a brief comment above the http property to explain its purpose and how it relates to the HTTP service configuration. This would improve the maintainability of the code for future developers.

Also applies to: 106-107


Line range hint 1-108: Summary: Successful implementation of configurable HTTP service

This PR successfully achieves its objective of refactoring the HTTP service into a configurable service. The changes are well-integrated into the existing structure of the registry.js file. Here's a summary of the key changes:

  1. Addition of GenerateCodeService and http imports.
  2. Import of httpConfig from a local file.
  3. Integration of GenerateCodeService into the metas array.
  4. Addition of the http property in the exported configuration object.

These changes enhance the modularity and configurability of the HTTP service without disrupting the overall structure of the configuration file. The implementation appears to be non-breaking, as it adds new functionality without modifying existing behavior.

To further improve this implementation, consider:

  1. Adding documentation comments for the new http configuration to explain its usage and options.
  2. If not already done, create unit tests for the new HTTP service configuration to ensure its correctness and prevent regressions.
  3. Update any relevant documentation or README files to reflect these new configuration options for the HTTP service.
packages/design-core/index.js (1)

41-41: Consider removing the blank line for consistency.

The blank line after the new http export (line 41) seems unnecessary and inconsistent with the file's structure. Other export statements are not separated by blank lines.

For better consistency, consider removing this blank line:

 export { default as http } from '@opentiny/tiny-engine-http'
-
 export * from '@opentiny/tiny-engine-meta-register'
designer-demo/src/http/index.js (4)

11-17: Localize Error Messages for Internationalization

The showError function displays error messages hardcoded in Chinese. To support a wider user base and facilitate future internationalization, consider using a localization framework or moving message strings to a resource file.

You can refactor the code as follows to use a localization function:

 const showError = (url, message) => {
   globalNotify({
     type: 'error',
     title: '接口报错',
-    message: `报错接口: ${url} \n报错信息: ${message ?? ''}`
+    message: i18n.t('errorMessage', { url, message: message ?? '' })
   })
 }

55-56: Remove Commented-Out Code

There's a commented-out line of code which can lead to confusion and clutter the codebase.

Apply this diff to remove the unnecessary line:

         getMetaApi('engine.service.http').request(response.config).then(resolve, reject)
-        // http.request(response.config).then(resolve, reject)

83-85: Review Comment Language Consistency

The code contains comments in Chinese, such as // 仅在本地开发时,启用 withCredentials. For consistency and broader understanding among global team members, consider converting comments to English.

For example:

-// 仅在本地开发时,启用 withCredentials
+// Enable withCredentials only during local development

100-100: Use const Instead of let for Immutable Variables

The environment variable is not reassigned after its initial declaration. Using const makes the intent clear that the variable should not change.

Apply this diff to update the variable declaration:

-let environment = import.meta.env
+const environment = import.meta.env
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 158310b and f1f8b87.

📒 Files selected for processing (7)
  • designer-demo/registry.js (2 hunks)
  • designer-demo/src/http/index.js (1 hunks)
  • packages/design-core/index.js (1 hunks)
  • packages/http/index.js (0 hunks)
  • packages/http/src/config.js (0 hunks)
  • packages/http/src/index.js (2 hunks)
  • packages/http/vite.config.js (1 hunks)
💤 Files with no reviewable changes (2)
  • packages/http/index.js
  • packages/http/src/config.js
🔇 Additional comments (10)
packages/http/vite.config.js (1)

33-33: Approved, but please verify the impact of CSS removal and document the change.

The removal of the banner option from the Rollup output configuration aligns with the PR objective of refactoring the HTTP service. However, please address the following points:

  1. Verify that removing the import "./style.css" banner doesn't negatively impact the styling of the library. If the CSS is now handled differently or is no longer needed, ensure this is reflected in the documentation.

  2. Document the reason for this change in the PR description or in a comment. This will help future maintainers understand the rationale behind the removal of the CSS import.

To ensure no unintended consequences, please run the following script to check for any remaining references to style.css in the package:

This script will help verify that the removal of the CSS import was intentional and comprehensive.

✅ Verification successful

To ensure all references to style.css are accounted for, please run the following updated script:


Verified: Removal of CSS import is safe

The removal of the banner option and import "./style.css" in the Rollup output configuration has been verified. There are no remaining references to style.css in the packages/http package, and the style.css file does not exist. This change aligns with the PR objective of refactoring the HTTP service and does not introduce any unintended side effects.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for references to style.css in the http package

# Search for style.css references
echo "Searching for style.css references:"
rg --type js --type vue "style\.css" packages/http

# Check if style.css file exists
echo "Checking if style.css file exists:"
fd -t f "style.css" packages/http

Length of output: 274


Script:

# Description: Check for references to style.css in the http package, including .vue files

# Search for style.css references in .js and .vue files
echo "Searching for style.css references in .js and .vue files:"
rg "style\.css" packages/http --type-add 'vue:*.vue'

# Check if style.css file exists
echo "Checking if style.css file exists:"
fd -t f "style.css" packages/http

Length of output: 292

designer-demo/registry.js (1)

46-46: LGTM: Addition of GenerateCodeService import

The addition of GenerateCodeService to the imports from '@opentiny/tiny-engine' is consistent with the existing import pattern and aligns with the PR's objective of refactoring the HTTP service.

packages/design-core/index.js (1)

Line range hint 1-46: Overall, the changes successfully implement the PR objectives.

The addition of the http module export effectively refactors the HTTP service as a configurable component, aligning with the PR's main objective. The change is minimal yet impactful, maintaining the file's existing structure and export pattern. This modification enhances the modularity of the codebase, allowing for on-demand import of HTTP-related functionalities.

A few points to consider:

  1. Ensure that the @opentiny/tiny-engine-http module is properly documented, especially regarding its configuration options.
  2. Update any relevant documentation to reflect this new configurable HTTP service.
  3. Consider adding tests specific to this new export to ensure it behaves as expected when imported and used.
packages/http/src/index.js (4)

28-36: LGTM: preResponse function handles response correctly

The preResponse function properly checks for errors in the response data and returns the expected data property when no errors are present. This implementation is clear and concise.


38-46: LGTM: errorResponse function provides appropriate error handling

The errorResponse function effectively captures errors, displays an error message to the user using showError, and appropriately rejects the promise with the correct error information.


74-80: Flexibility in axios configuration

The init function allows config to be either an object or a function that returns an object. This provides flexibility in configuring axios instances based on dynamic conditions.


90-90: LGTM: Attaching request interceptors

The request interceptors are correctly attached using http.interceptors.request.use(...interceptors.request). This ensures any custom request interceptors provided in the options are properly utilized.

designer-demo/src/http/index.js (3)

116-126: Ensure Correct Order of Response Interceptors

In the httpConfig, the response interceptors are specified as [interceptors.response[0], errorResponse]. Verify that this order is intentional and that errorResponse correctly handles errors after any prior interceptors.

No script needed, but please confirm that interceptors.response[0] should precede errorResponse and that they are compatible.


104-114: Verify Modification of config.baseURL in preRequest

The preRequest function conditionally sets config.baseURL to an empty string. Ensure this does not unintentionally affect API endpoints, especially in production environments.

Run the following script to list all API calls and check their base URLs:

#!/bin/bash
# Description: List all configurations of baseURL in API requests.

rg --type javascript 'config\.baseURL' -A 2

62-72: Verify Behavior When Session Expires

In the errorResponse function, when the response status is LOGIN_EXPIRED_CODE, the logic depends on the environment. Verify that in all environments, the user is appropriately prompted to re-authenticate.

Run the following script to ensure that the session rebuild process works correctly across different environments:

✅ Verification successful

To address the issues encountered, please run the following scripts to properly verify how session expiration is handled across different environments:


To resolve the regex errors and accurately verify how session expiration is handled across different environments, please run the following scripts with corrected regex patterns:


Session Expiration Handling Verified Successfully

The errorResponse function correctly prompts users to re-authenticate in all environments:

  • VSCode Plugin Environment: Detects window.vscodeBridge and resolves the session prompt.
  • Browser Environment: Detects the x-login-url header and invokes openLogin() to prompt re-authentication.
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check how session expiration is handled in different environments.

# Test for vscodeBridge existence
rg --type javascript 'window\.vscodeBridge' -A 3

# Look for handling of 'x-login-url' header
rg --type javascript "response\?\.\headers\['x-login-url'\]" -A 3

Length of output: 435


Script:

#!/bin/bash
# Description: Check how session expiration is handled in different environments using specific file extensions and corrected regex patterns.

# Search for vscodeBridge usage in JavaScript files
rg 'window\.vscodeBridge' -A 3 --glob '*.js' --glob '*.jsx'

# Search for handling of 'x-login-url' header in JavaScript files
rg "response\?\.\headers\['x-login-url'\]" -A 3 --glob '*.js' --glob '*.jsx'

Length of output: 1671


Script:

#!/bin/bash
# Description: Check how session expiration is handled in different environments with corrected regex patterns.

# Search for vscodeBridge usage in JavaScript files
rg 'window\.vscodeBridge' -A 3 --glob '*.js' --glob '*.jsx'

# Search for handling of 'x-login-url' header in JavaScript files with corrected regex
rg 'response\?.headers\['"'"'x-login-url'"'"'\]' -A 3 --glob '*.js' --glob '*.jsx'

Length of output: 1760

Comment on lines +40 to +41
export { default as http } from '@opentiny/tiny-engine-http'

Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

Missing @opentiny/tiny-engine-http in package.json Dependencies.

The @opentiny/tiny-engine-http module is being exported and imported across multiple files but is not listed in the package.json dependencies. This can lead to installation and runtime issues.

  • Add @opentiny/tiny-engine-http to dependencies in package.json.
🔗 Analysis chain

New HTTP module export aligns with PR objectives.

The addition of the http module export from @opentiny/tiny-engine-http is consistent with the PR's objective to refactor HTTP as a configurable service. This change allows users to import HTTP-related functionalities on demand, which is in line with the modular structure of the file.

To ensure this change doesn't introduce any conflicts or issues, let's verify the module's existence and its usage across the codebase:

This script will help us confirm that the module is properly included in the project dependencies and identify any existing usage or potential conflicts.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Verify the existence of the @opentiny/tiny-engine-http module
echo "Checking for @opentiny/tiny-engine-http in package.json:"
jq '.dependencies["@opentiny/tiny-engine-http"] // .devDependencies["@opentiny/tiny-engine-http"]' package.json

# Check for any existing imports of the http module
echo "Checking for existing imports of the http module:"
rg --type js --type ts 'import.*from.*@opentiny/tiny-engine-http'

# Look for any potential conflicts or duplicate exports
echo "Checking for potential conflicts or duplicate exports:"
rg --type js --type ts 'export.*http.*from'

Length of output: 3414

Comment on lines +94 to +95
http.interceptors.request.use(...interceptors.response)
}
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

Incorrectly attaching response interceptors to request interceptors

At line 94, response interceptors are being added to the request interceptors chain using http.interceptors.request.use(...interceptors.response). This will result in the response interceptors not being called appropriately and could cause unexpected behaviors in request handling.

Apply this diff to fix the issue:

-          http.interceptors.request.use(...interceptors.response)
+          http.interceptors.response.use(...interceptors.response)
📝 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
http.interceptors.request.use(...interceptors.response)
}
http.interceptors.response.use(...interceptors.response)
}

globalNotify({
type: 'error',
title: '接口报错',
message: `报错接口: ${url} \n报错信息: ${message ?? ''}`
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

Ensure Error Messages Are Properly Sanitized

When displaying error messages that include dynamic data such as url and message, ensure that they are properly sanitized to prevent potential Cross-Site Scripting (XSS) attacks.

Consider sanitizing the inputs or using a library that handles this automatically.

Comment on lines +52 to +58
if (!procession.promiseLogin) {
procession.promiseLogin = loginVM.openLogin(procession, '/api/rebuildSession')
procession.promiseLogin.then(() => {
getMetaApi('engine.service.http').request(response.config).then(resolve, reject)
// http.request(response.config).then(resolve, reject)
})
}
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

Avoid Potential Race Conditions in openLogin Function

The openLogin function checks if procession.promiseLogin is falsy before initializing it. However, there might be a race condition if multiple calls happen simultaneously.

Consider using a locking mechanism or initializing procession.promiseLogin atomically to prevent multiple logins from being initiated.

Comment on lines +48 to +49
const { response } = error

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

Handle Undefined response Gracefully

In the errorResponse function, you destructure response from error, but response might be undefined. This could lead to runtime errors when accessing response.status or response.headers.

Apply this diff to add a check for response:

 export const errorResponse = (error) => {
   // 用户信息失效时,弹窗提示登录
-  const { response } = error
+  const { response } = error || {}
📝 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 { response } = error
export const errorResponse = (error) => {
// 用户信息失效时,弹窗提示登录
const { response } = error || {}

const dev = env.MODE?.includes('dev')

// 获取租户 id
const getTenant = () => new URLSearchParams(location.search).get('tenant')
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

Ensure location Object Is Available

The getTenant function uses location.search, which may not be available in non-browser environments like Node.js or server-side rendering.

Consider adding a check to ensure location is defined:

 const getTenant = () => {
+  if (typeof location === 'undefined') return null
   return new URLSearchParams(location.search).get('tenant')
 }
📝 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 getTenant = () => new URLSearchParams(location.search).get('tenant')
const getTenant = () => {
if (typeof location === 'undefined') return null
return new URLSearchParams(location.search).get('tenant')
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request refactor-main refactor/develop branch feature
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant