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

perf: request support to set how to return response #5436

Merged
merged 4 commits into from
Jan 19, 2025

Conversation

mynetfan
Copy link
Collaborator

@mynetfan mynetfan commented Jan 19, 2025

Description

为 RequestClient 添加额外的选项。可以在实例化时、调用具体的请求方法时传入这些额外的选项来改变request的一些表现。
目前第一个新增的选项为responseReturn,用于设置返回的数据类型,取值和说明如下:

  • raw: 原始的AxiosResponse,包括headers、status等。
  • body: 返回响应数据的BODY部分。
  • data: 解构响应的BODY数据,只返回其中的data节点数据(默认方式)。

close #5432

Type of change

Please delete options that are not relevant.

  • 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 not work as expected)
  • This change requires a documentation update
  • Please, don't make changes to pnpm-lock.yaml unless you introduce a new test example.

Checklist

ℹ️ Check all checkboxes - this will indicate that you have done everything in accordance with the rules in CONTRIBUTING.

  • If you introduce new functionality, document it. You can run documentation with pnpm run docs:dev command.
  • Run the tests with pnpm test.
  • Changes in changelog are generated from PR name. Please, make sure that it explains your changes in an understandable manner. Please, prefix changeset messages with feat:, fix:, perf:, docs:, or chore:.
  • My code follows the style guidelines of this project
  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes
  • Any dependent changes have been merged and published in downstream modules

Summary by CodeRabbit

  • New Features

    • Enhanced request client configuration with optional parameters.
    • Added more flexible response handling options.
  • Improvements

    • Streamlined request client creation process.
    • Updated method signatures across multiple request-related files.
    • Improved type definitions for request configurations.
    • Expanded test coverage for different response types from the request client.
  • Changes

    • Removed specific response interceptor for data structure handling.
    • Modified error handling approach for API requests.

@mynetfan mynetfan requested review from anncwb, vince292007 and a team as code owners January 19, 2025 09:00
Copy link

changeset-bot bot commented Jan 19, 2025

⚠️ No Changeset found

Latest commit: 1d8293f

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
Contributor

coderabbitai bot commented Jan 19, 2025

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 eslint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

packages/effects/request/src/request-client/request-client.test.ts

Oops! Something went wrong! :(

ESLint: 9.17.0

Error [ERR_MODULE_NOT_FOUND]: Cannot find module '/node_modules/@vben/eslint-config/dist/index.mjs' imported from /eslint.config.mjs
at finalizeResolution (node:internal/modules/esm/resolve:257:11)
at moduleResolve (node:internal/modules/esm/resolve:914:10)
at defaultResolve (node:internal/modules/esm/resolve:1038:11)
at ModuleLoader.defaultResolve (node:internal/modules/esm/loader:557:12)
at ModuleLoader.resolve (node:internal/modules/esm/loader:525:25)
at ModuleLoader.getModuleJob (node:internal/modules/esm/loader:246:38)
at ModuleJob._link (node:internal/modules/esm/module_job:126:49)

Walkthrough

The pull request introduces modifications to the request handling mechanism across multiple files in the Vben Admin project. The primary changes involve updating the createRequestClient function to accept optional RequestClientOptions, removing a specific response interceptor that handled data structure validation, and enhancing the request client's configuration flexibility. These modifications aim to provide more customizable request handling while simplifying the response processing logic.

Changes

File Change Summary
apps/web-*/src/api/request.ts Updated createRequestClient function signature to accept optional RequestClientOptions, removed response data structure interceptor
packages/effects/request/src/request-client/request-client.ts Updated method signatures to use RequestClientConfig, added new response interceptor for configurable response processing
packages/effects/request/src/request-client/types.ts Introduced new types ExtendOptions, RequestClientConfig, modified existing type signatures to support new configuration options

Assessment against linked issues

Objective Addressed Explanation
Add isTransformResponse parameter [#5432] The changes do not explicitly introduce an isTransformResponse parameter; they implement responseReturn instead, which may not fulfill the original request.

Possibly related PRs

Suggested labels

chore

Suggested reviewers

  • anncwb
  • vince292007

Poem

🐰 Requests dance with grace anew,
Interceptors shed their old debut
Options spread like rabbit's ears
Flexibility conquers coding fears
A request client, nimble and bright! 🚀

Finishing Touches

  • 📝 Generate Docstrings (Beta)

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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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.

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: 2

🧹 Nitpick comments (5)
packages/effects/request/src/request-client/types.ts (1)

8-15: Translate comments to English for better international collaboration.

The comments explaining the responseReturn options should be in English. Here's the suggested translation:

-  /** 响应数据的返回方式。
-   * raw: 原始的AxiosResponse,包括headers、status等。
-   * body: 返回响应数据的BODY部分。
-   * data: 解构响应的BODY数据,只返回其中的data节点数据(默认方式)。
-   */
+  /** Response data return format.
+   * raw: Original AxiosResponse, including headers, status, etc.
+   * body: Returns the BODY part of the response.
+   * data: Destructures the BODY data, returns only the data node (default).
+   */
apps/web-antd/src/api/request.ts (1)

23-25: Consider documenting the new options usage.

The function now accepts options but lacks documentation about the available configuration, especially the new responseReturn option.

+/**
+ * Creates a configured request client
+ * @param baseURL - The base URL for API requests
+ * @param options - Optional client configuration
+ * @param options.responseReturn - Response format ('raw' | 'body' | 'data')
+ * @returns Configured RequestClient instance
+ */
 function createRequestClient(baseURL: string, options?: RequestClientOptions) {
playground/src/api/request.ts (1)

Line range hint 97-99: Consider configuring exported client instances.

The exported requestClient and baseRequestClient instances don't specify the responseReturn option. Consider setting a default response format to maintain consistent behavior across the application.

-export const requestClient = createRequestClient(apiURL);
+export const requestClient = createRequestClient(apiURL, { responseReturn: 'data' });

-export const baseRequestClient = new RequestClient({ baseURL: apiURL });
+export const baseRequestClient = new RequestClient({ 
+  baseURL: apiURL,
+  responseReturn: 'data'
+});
packages/effects/request/src/request-client/request-client.ts (1)

56-72: Consider adding type validation and documentation for response types.

To improve the robustness of the new feature:

  1. Add TypeScript type validation for responseReturn values
  2. Add JSDoc documentation explaining the response type options

Consider adding these type definitions:

type ResponseReturnType = 'raw' | 'body' | 'data';

interface RequestClientConfig extends AxiosRequestConfig {
  responseReturn?: ResponseReturnType;
}

And update the constructor documentation:

/**
 * Creates an instance of RequestClient
 * @param options - Configuration options
 * @param options.responseReturn - Controls response format:
 *   - 'raw': Returns complete AxiosResponse
 *   - 'body': Returns response body
 *   - 'data': Returns data node from body (default)
 */
constructor(options: RequestClientOptions = {}) {
apps/web-naive/src/api/request.ts (1)

22-25: Consider documenting the new options and their impact.

While the implementation is solid, consider:

  1. Adding JSDoc comments to document the new options parameter and its effects
  2. Updating relevant API documentation to explain the responseReturn option
  3. Providing migration guides for consumers who relied on the removed data structure validation
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3f0f4d5 and 05a7108.

📒 Files selected for processing (6)
  • apps/web-antd/src/api/request.ts (2 hunks)
  • apps/web-ele/src/api/request.ts (2 hunks)
  • apps/web-naive/src/api/request.ts (2 hunks)
  • packages/effects/request/src/request-client/request-client.ts (5 hunks)
  • packages/effects/request/src/request-client/types.ts (2 hunks)
  • playground/src/api/request.ts (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (7)
  • GitHub Check: Lint (windows-latest)
  • GitHub Check: Lint (ubuntu-latest)
  • GitHub Check: Check (windows-latest)
  • GitHub Check: post-update (windows-latest)
  • GitHub Check: Check (ubuntu-latest)
  • GitHub Check: post-update (ubuntu-latest)
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (10)
packages/effects/request/src/request-client/types.ts (3)

16-20: LGTM! Well-structured type definitions.

The types are properly defined with correct extension of Axios types and good use of generics.


28-28: LGTM! Good type composition.

The type correctly extends CreateAxiosDefaults with ExtendOptions, providing a clean way to configure the request client.


32-35: LGTM! Robust type definitions for interceptors.

The interceptor types are well-defined with proper handling of ExtendOptions and async operations.

Also applies to: 41-42

apps/web-antd/src/api/request.ts (1)

23-25: Verify the impact of removing the response interceptor.

The removal of the response data structure validation interceptor changes how responses are processed. Ensure that all API consumers are updated to handle the raw response format correctly.

Let's check for direct response data access patterns that might break:

apps/web-ele/src/api/request.ts (2)

4-4: LGTM! Import statement updated correctly.

The import statement has been updated to include RequestClientOptions which is needed for the new configuration options.


23-26: LGTM! Function signature updated correctly.

The changes correctly implement the new options parameter:

  1. Function signature updated to accept optional RequestClientOptions
  2. Options are properly forwarded to RequestClient using spread operator
packages/effects/request/src/request-client/request-client.ts (2)

1-7: LGTM! Import statements updated correctly.

The imports have been properly updated to include the necessary types for the new response handling functionality.


85-88: LGTM! Method signatures updated consistently.

All HTTP method signatures have been properly updated to use RequestClientConfig instead of AxiosRequestConfig, maintaining consistency across the API.

Also applies to: 95-95, 105-105, 116-116, 124-127

apps/web-naive/src/api/request.ts (2)

4-4: LGTM! Type import added for new options parameter.

The import of RequestClientOptions type is correctly added to support the enhanced function signature.


24-25: Verify the impact of removing data structure validation.

The options spreading is implemented correctly, with baseURL properly preserved. However, the removal of the data structure validation interceptor (as noted in the AI summary) requires verification:

  1. Ensure all API consumers are prepared to handle varied response structures
  2. Confirm this aligns with the new responseReturn option behavior

Let's analyze the impact:

✅ Verification successful

✓ Data structure validation removal verified as safe

The codebase analysis shows no rigid response structure assumptions in consuming applications, making the removal of the validation interceptor safe and aligned with the flexible responseReturn option design.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for direct RequestClient usage to identify affected consumers
ast-grep --pattern 'new RequestClient($$$)'

# Search for response data structure assumptions
rg -g '*.{ts,tsx,vue}' -A 3 'response\.(data|body)'

Length of output: 3767

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: 0

🧹 Nitpick comments (1)
packages/effects/request/src/request-client/request-client.ts (1)

125-128: Enhance error handling in request method.

Consider adding more context to errors for better debugging.

 public async request<T>(
   url: string,
   config: RequestClientConfig,
 ): Promise<T> {
   try {
     const response: AxiosResponse<T> = await this.instance({
       url,
       ...config,
     });
     return response as T;
   } catch (error: any) {
-    throw error.response ? error.response.data : error;
+    const errorData = error.response?.data;
+    throw {
+      ...errorData,
+      url,
+      method: config.method,
+      message: errorData?.message || error.message,
+      status: error.response?.status
+    };
   }
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 05a7108 and f1b8287.

📒 Files selected for processing (6)
  • apps/web-antd/src/api/request.ts (3 hunks)
  • apps/web-ele/src/api/request.ts (3 hunks)
  • apps/web-naive/src/api/request.ts (3 hunks)
  • packages/effects/request/src/request-client/request-client.ts (6 hunks)
  • packages/effects/request/src/request-client/types.ts (2 hunks)
  • playground/src/api/request.ts (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • apps/web-antd/src/api/request.ts
  • apps/web-ele/src/api/request.ts
  • packages/effects/request/src/request-client/types.ts
⏰ Context from checks skipped due to timeout of 90000ms (9)
  • GitHub Check: Test (windows-latest)
  • GitHub Check: Test (ubuntu-latest)
  • GitHub Check: Lint (windows-latest)
  • GitHub Check: Lint (ubuntu-latest)
  • GitHub Check: post-update (windows-latest)
  • GitHub Check: post-update (ubuntu-latest)
  • GitHub Check: Check (windows-latest)
  • GitHub Check: Check (ubuntu-latest)
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (6)
packages/effects/request/src/request-client/request-client.ts (4)

1-7: LGTM! Import statements updated to support custom request configuration.

The changes properly introduce the new types needed for configurable response returns.


36-43: LGTM! Default configuration properly initialized.

The default responseReturn: 'raw' ensures backward compatibility while enabling customization through options.


86-89: LGTM! Method signatures properly updated.

The HTTP method implementations consistently use the new RequestClientConfig type.

Also applies to: 96-96, 106-106, 117-117


57-73: ⚠️ Potential issue

Improve response interceptor implementation.

The current implementation has several potential issues:

  1. Missing type checking for responseData structure
  2. Unsafe destructuring of code and data
  3. Circular reference in error object

Consider this safer implementation:

 this.addResponseInterceptor<HttpResponse>({
   fulfilled: (response) => {
     const { config, data: responseData, status } = response;

     if (config.responseReturn === 'raw') {
       return response;
     }

-    const { code, data } = responseData;
+    // Safe handling of responseData
+    if (typeof responseData !== 'object' || responseData === null) {
+      return config.responseReturn === 'body' ? responseData : responseData;
+    }
+
+    const code = 'code' in responseData ? responseData.code : undefined;
+    const data = 'data' in responseData ? responseData.data : responseData;

     if (status >= 200 && status < 400 && code === 0) {
       return config.responseReturn === 'body' ? responseData : data;
     }
-    throw Object.assign({}, response, { response });
+    // Avoid circular reference
+    throw {
+      status,
+      data: responseData,
+      message: responseData?.message || 'Request failed'
+    };
   },
 });

Likely invalid or redundant comment.

apps/web-naive/src/api/request.ts (1)

22-24: LGTM! Request client properly configured.

The implementation correctly:

  1. Updates createRequestClient to support options
  2. Sets responseReturn to 'data' as default

Also applies to: 98-100

playground/src/api/request.ts (1)

23-25: LGTM! Implementation consistent with web-naive.

The changes mirror those in web-naive/src/api/request.ts, maintaining consistency across the codebase.

Also applies to: 99-101

@mynetfan mynetfan changed the title pref: request support to set how to return response perf: request support to set how to return response Jan 19, 2025
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: 0

🧹 Nitpick comments (1)
packages/effects/request/src/request-client/request-client.test.ts (1)

51-72: LGTM! Well-structured test coverage for the new feature.

The test case effectively validates all three response types ('raw', 'body', 'data') with clear assertions and consistent mock data.

Consider adding edge cases for comprehensive testing.

While the happy path is well covered, consider adding test cases for:

  • Empty response data
  • Missing or null fields in the response
  • Invalid responseReturn option values

Example test case:

it('should handle edge cases for different response types', async () => {
  const emptyMockData = { code: 0, msg: '', data: null };
  mock.onGet('/test/empty').reply(200, emptyMockData);

  // Test with null data
  const responseData = await requestClient.get('/test/empty', {
    responseReturn: 'data',
  });
  expect(responseData).toBeNull();

  // Test with invalid responseReturn option
  await expect(
    requestClient.get('/test/empty', {
      // @ts-expect-error - Testing invalid option
      responseReturn: 'invalid',
    })
  ).rejects.toThrow();
});
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f1b8287 and 1d8293f.

📒 Files selected for processing (1)
  • packages/effects/request/src/request-client/request-client.test.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (9)
  • GitHub Check: Test (windows-latest)
  • GitHub Check: Lint (windows-latest)
  • GitHub Check: Check (windows-latest)
  • GitHub Check: post-update (windows-latest)
  • GitHub Check: Test (ubuntu-latest)
  • GitHub Check: post-update (ubuntu-latest)
  • GitHub Check: Lint (ubuntu-latest)
  • GitHub Check: Check (ubuntu-latest)
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (1)
packages/effects/request/src/request-client/request-client.test.ts (1)

51-72: Verify consistent implementation across the codebase.

Let's ensure the responseReturn option is consistently implemented across all request methods.

✅ Verification successful

Implementation verified as consistent and complete

The responseReturn option is properly implemented:

  • Centralized response processing via interceptor ensures consistent behavior across all HTTP methods
  • All three modes ('raw', 'body', 'data') are handled correctly
  • Default configuration and usage patterns are consistent across the codebase
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if all HTTP methods support the responseReturn option consistently

# Search for request method implementations
echo "Searching for request method implementations..."
ast-grep --pattern 'class $_ {
  $$$
  (get|post|put|delete)($_) {
    $$$
  }
  $$$
}'

# Search for responseReturn option usage
echo "Checking responseReturn option usage..."
rg -A 2 'responseReturn:' 

Length of output: 1956


Script:

#!/bin/bash
# Search for the implementation of HTTP methods and response processing
echo "Searching for HTTP method implementations..."
ast-grep --pattern 'async $method($$$) {
  $$$
}'  packages/effects/request/src/request-client/request-client.ts

echo "\nSearching for response processing..."
rg -A 10 'processResponse' packages/effects/request/src/request-client/request-client.ts

Length of output: 388


Script:

#!/bin/bash
# First verify the file exists and show its content
echo "Checking file content..."
cat packages/effects/request/src/request-client/request-client.ts

echo "\nSearching for method implementations with broader pattern..."
ast-grep --pattern 'class RequestClient {
  $$$
}'

Length of output: 15176

@mynetfan mynetfan merged commit 5611f6c into vbenjs:main Jan 19, 2025
14 of 15 checks passed
@mynetfan mynetfan deleted the feat/request-options branch January 19, 2025 09:41
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
1 participant