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: add API Proxy in dataSource, add some mock API, add some cases #1218

Open
wants to merge 2 commits into
base: develop
Choose a base branch
from

Conversation

1degrees
Copy link
Contributor

@1degrees 1degrees commented Mar 13, 2025

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

  • New Features

    • Introduced flexible proxy support to route API requests and a new API configuration for data fetching.
    • Added endpoints to streamline app configuration updates.
  • Enhancements / Refactors

    • Improved HTTP request handling with robust error management and consistent promise behavior.
    • Refined data source management with dynamic function handling.
    • Enhanced UI options to directly configure proxy settings.
  • Dependency Updates

    • Upgraded network libraries including axios and added new proxy middleware for improved performance.
  • Cleanup

    • Removed an obsolete localization file.

Copy link
Contributor

coderabbitai bot commented Mar 13, 2025

Walkthrough

This pull request introduces multiple enhancements focused on proxy handling and data source management. A new dependency for HTTP proxy middleware is added, and various JSON configuration files receive a new data source entry ("testProxyApi") with associated proxy settings and JavaScript function handlers. Server routes now include an update endpoint and a catch-all proxy route. Service methods and build configurations are adjusted to work with the new proxy settings, and HTTP client and Vue generator code are refactored for improved interceptor flexibility. Additional minor UI and dependency adjustments are also included.

Changes

File(s) Change Summary
mockServer/package.json, packages/design-core/package.json, and test package files (…/expected/appdemo01/package.json) Added new dependency "http-proxy-middleware": "^3.0.3" in mockServer and updated "axios" to ~0.28.0 in multiple package files.
mockServer/src/assets/json/appinfo.json, .../sources.json, .../detail/918.json, .../sources/list/918.json, .../v1/apps/schema/918.json, and test dataSource JSON (…/dataSource.json) Added a new data source entry "testProxyApi" with properties including id, name, proxy configuration, and several JavaScript handler functions; also performed formatting improvements.
mockServer/src/mock/post/app-center/apps/update/918.json Removed outdated localization file.
mockServer/src/routes/main-routes.js Added a new POST route for updating apps (/app-center/api/apps/update/:id) and a catch-all proxy route (/app-proxy/api/*) using createProxyMiddleware.
mockServer/src/services/app.js, mockServer/src/services/source.js Updated service methods: refactored getAppPreviewMetaData to use nested proxy config and introduced an update(source_global) method to modify JSON configuration files.
packages/build/vite-config/src/default-config.js Added proxy configuration for /app-proxy/api directing to a local origin.
Files under packages/design-core/src/preview/src/preview/ (e.g., Preview.vue, generate.js, srcFiles.js, dataSourceMap.js, srcFiles/http.js) Modified preview generation: changed variable handling, introduced a new generateDataSource function, imported a new HTTP client module, and added functions for dynamic function creation and HTTP requests.
Files under packages/vue-generator/src/templates/vue-template/templateFiles/ (e.g., genViteConfig.js, src/http/index.js, src/lowcodeConfig/dataSource.js) Updated function signatures to accept a schema and multiple HTTP interceptors; refactored global handler integration in data source generation.
Vue Generator test cases (…/expected/appdemo01/src/http/index.js and …/lowcodeConfig/dataSource.js) Adjusted HTTP interceptor signatures and integrated global handlers in test case configurations.
packages/plugins/datasource/src/DataSourceGlobalDataHandler.vue, RemoteDataAdapterForm.vue, js/datasource.ts, and packages/plugins/materials/src/composable/useResource.ts Enhanced Vue plugin components by adding proxy configuration in the global data handler UI, updating prop types and options, refining promise returns in datasource functions, and introducing a DEFAULT_PROXY constant.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Router
    participant SourceService
    participant FileSystem

    Client->>Router: POST /app-center/api/apps/update/:id with source_global
    Router->>SourceService: update(source_global)
    SourceService->>FileSystem: Read JSON config files (appinfo, detail, schema)
    FileSystem-->>SourceService: Return file data
    SourceService->>FileSystem: Write updated JSON data back
    SourceService-->>Router: Return update result
    Router-->>Client: Respond with updated status
Loading
sequenceDiagram
    participant Client
    participant Router
    participant ProxyMiddleware
    participant TargetServer

    Client->>Router: Request /app-proxy/api/...
    Router->>Router: Extract app ID & load JSON config
    Router->>ProxyMiddleware: Forward request based on proxy settings
    ProxyMiddleware->>TargetServer: Proxy the request
    TargetServer-->>ProxyMiddleware: Return response
    ProxyMiddleware-->>Router: Pass response back
    Router-->>Client: Deliver proxied response
Loading

Possibly related PRs

Suggested labels

ready_for_review

Suggested reviewers

  • hexqi
  • rhlin
  • gene9831

Poem

I’m a rabbit in a code-filled field,
Hopping through changes that the devs have sealed.
With proxy paths and JSON treats,
I nibble updates in little beats.
Codes and functions all in sight—
A playful dance by day and night 🐇!

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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.

@github-actions github-actions bot added the enhancement New feature or request label Mar 13, 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: 10

🧹 Nitpick comments (30)
packages/design-core/src/preview/src/preview/srcFiles/http.js (1)

89-97: Consider translating comments to English

The code properly implements interceptor chains for both request and response handling. However, there's a comment in Chinese that should be translated to English for consistency and broader accessibility.

- // axios对于request拦截器是后注册先执行
+ // For axios request interceptors, the last registered interceptor executes first
packages/build/vite-config/src/default-config.js (1)

55-60: New proxy route added for API proxy functionality.

The addition of the /app-proxy/api proxy route properly configures the development server to forward requests to the mock server. This configuration works in conjunction with the newly added http-proxy-middleware package.

Consider uncommenting and utilizing the rewrite function to strip the /app-proxy/api prefix, which might make backend integration cleaner:

-        '/app-proxy/api': {
-          target: origin,
-          changeOrigin: true
-          // rewrite: (path) => path.replace(/^\/app-proxy\/api/, ''),
-        }
+        '/app-proxy/api': {
+          target: origin,
+          changeOrigin: true,
+          rewrite: (path) => path.replace(/^\/app-proxy\/api/, ''),
+        }
packages/vue-generator/src/templates/vue-template/templateFiles/genViteConfig.js (1)

1-1: Enhanced Vite config with dynamic proxy configuration.

The function now accepts a schema parameter and uses it to generate a dynamic proxy configuration in the Vite server settings. This allows generated applications to inherit the proxy settings defined in the data source.

Consider adding validation for the schema parameter to handle potential edge cases:

-export default (schema) => {
+export default (schema = {}) => {
  // 避免在构建的时候,被 process. env 替换
  const processStr = ['process', 'env']
+  const dataSource = schema.dataSource || {}

And then update the proxy line:

-      proxy: ${JSON.stringify(schema.dataSource.proxy || {}, null, 2)},
+      proxy: ${JSON.stringify(dataSource.proxy || {}, null, 2)},

This provides better error handling if schema or schema.dataSource is undefined.

Also applies to: 11-14

mockServer/src/services/source.js (1)

22-35: New update method handles multiple file updates.

The added update method manages configuration updates across multiple JSON files. This is a well-structured implementation that uses fs-extra for reliable file operations.

Consider adding error handling for cases where files might not exist or when file operations fail:

  update(source_global) {
    const appPath = path.join(__dirname, '../assets/json/appinfo.json')
    const detailPath = path.join(__dirname, '../mock/get/app-center/apps/detail/918.json')
    const appSchemaPath = path.join(__dirname, '../mock/get/app-center/v1/apps/schema/918.json')
-   const appJson = fs.readJSONSync(appPath)
-   const detailJson = fs.readJSONSync(detailPath)
-   const schemaJson = fs.readJSONSync(appSchemaPath)
+   try {
+     const appJson = fs.readJSONSync(appPath)
+     const detailJson = fs.readJSONSync(detailPath)
+     const schemaJson = fs.readJSONSync(appSchemaPath)
      
      appJson.app.data_source_global = source_global
      detailJson.data.data_source_global = source_global
      schemaJson.data.dataSource = {...schemaJson.data.dataSource, ...source_global}
      
      fs.outputJSONSync(appPath, appJson, { spaces: 2 })
      fs.outputJSONSync(detailPath, detailJson, { spaces: 2 })
      fs.outputJSONSync(appSchemaPath, schemaJson, { spaces: 2 })
+     return true
+   } catch (error) {
+     console.error('Failed to update source files:', error)
+     return false
+   }
  }
mockServer/src/routes/main-routes.js (1)

258-266: Consider adding timeout handling for proxy requests

The proxy implementation correctly creates and awaits the proxy middleware, but it might benefit from timeout handling for long-running requests.

Consider adding a timeout to prevent hanging requests:

await new Promise((resolve, reject) => {
+  const timeoutId = setTimeout(() => {
+    reject(new Error('Proxy request timeout'));
+  }, 30000); // 30 seconds timeout
  
  proxy(ctx.req, ctx.res, (err) => {
+    clearTimeout(timeoutId);
    err? reject(err) : resolve();
  });
});
packages/vue-generator/test/testcases/generator/expected/appdemo01/src/http/index.js (1)

18-22: Double-check interceptors' registration order.

Axios request interceptors run LIFO, which can be counterintuitive. Carefully confirm that the local (willFetch, errorHandler) and global (globalWillFetch, globalErrorHandler) interceptors are triggered in the correct sequence to avoid unexpected overrides.

If the order is critical, consider adding explicit comments or reordering the calls for better clarity:

- http.interceptors.request.use(willFetch, errorHandler)
- http.interceptors.request.use(globalWillFetch, globalErrorHandler)
+ // Register global interceptors first, then local interceptors
+ http.interceptors.request.use(globalWillFetch, globalErrorHandler)
+ http.interceptors.request.use(willFetch, errorHandler)
packages/vue-generator/test/testcases/element-plus-case/expected/appdemo01/src/lowcodeConfig/dataSource.js (1)

17-21: Be cautious with dynamic code execution.

Using new Function(fnContent) can lead to security vulnerabilities if fnContent is not strictly controlled. Ensure that content is sanitized or from a trusted source to prevent execution of malicious code.

If user-generated content is not expected, consider safer evaluation strategies or validating the script before execution.

packages/design-core/src/preview/src/preview/srcFiles/dataSourceMap.js (2)

15-20: Exercise caution with dynamic function creation.

Similar to other locations, creating functions via new Function poses security risks if the incoming content is untrusted. Validate the source of fnContent to mitigate potential code injection threats.


28-62: “load” function usage.

  1. Returning promises in all branches (no config case, not fetching case, normal request) ensures a uniform async interface, reducing confusion for consumers.
  2. Consider adding logging or error-boundary checks if “globalDataHandle” modifies data, so developers can debug transformations more easily.
mockServer/src/assets/json/appinfo.json (21)

4136-4154: Review UI Configuration for Shortcuts and Context Menu
The "shortcuts" and "contextMenu" objects have been updated.
• Notice that one of the context menu actions is "bindEevent". Please verify if this is a typo for "bindEvent".


4261-4279: Consistency Check for Context Menu Actions
Once again, "bindEevent" appears in the context menu actions.
• Consider whether this should be corrected to "bindEvent" for clarity and consistency.


4524-4542: Validation of New Shortcut Properties
A new property called "show-checkbox" has been added within "options".
• Also, the use of "bindEevent" in this hunk is noted—please ensure it is deliberate.


4909-4932: Enhanced ContextMenu Configuration
The context menu now includes refined action lists and slot specifications.
• Double-check the usage of "bindEevent" within the action list.


5714-5732: Component Configuration with Invalidity Field
The "invalidity" field is defined as an array with an empty string ([""]).
• Consider whether an empty array ([]) might be a clearer way to indicate “no validation error.”


6020-6043: Updated Component Layout with Event Configurations
The configuration now contains updated "shortcuts" and "contextMenu" objects with an "invalidity" field holding an empty string.
• Consider whether it might be better to use an empty array if no error state exists.


6236-6244: Refined Shortcuts Configuration
The updated "properties" array is now slightly adjusted.
• Please check that the empty string included in the array is intended.


6490-6514: Component Configuration with Potential Invalidity Issue
The "invalidity" key again appears as an array with an empty string.
• Consider standardizing this to an empty array ([]) unless the empty string is required.


6949-6973: Component ContextMenu and Shortcut Updates
The context menu actions have been refreshed.
• Once again, please verify whether "bindEevent" should be corrected to "bindEvent".


7113-7137: Revised Component Configuration with Invalidity
The configuration again uses an "invalidity" field that holds [""].
• Check for consistency—using an empty array might be clearer if no invalid state is detected.


8189-8213: Component Configuration with Invalidity Field
The "invalidity" field — again set as [""] — appears here.
• It might be more semantically clear to use an empty array if no invalid state exists.


8642-8661: Component Configuration Consistency
Ensure that the context menu actions (including the recurring "bindEevent") are accurate.


9666-9689: Layout Configuration for Flex Components
The configuration contains an "invalidity" field with an empty string.
• Consider revising this to an empty array for clarity if no invalid state should be indicated.


11296-11315: Review of Invalidity Field Usage
Again, the "invalidity" field appears as [""].
• Consider switching to an empty array ([]) for clarity if no invalidity applies.


13029-13053: Layout Component Configuration with Invalidity Issue
The configuration here includes an "invalidity" field set to [""] along with the other updated layout properties.
• It might be clearer to use an empty array if no invalidity is intended.


15675-15693: Component Layout with Empty Shortcut Property
The "shortcuts" array contains an empty string, and "invalidity" is set as an empty array.
• If the empty string is meant to denote “no property,” consider using an empty array for clarity.


16863-16886: Component Layout and Configuration
The block shows updated "shortcuts" and an "invalidity" field again containing an empty string.
• Consider whether using an empty array ([]) might be clearer.


17138-17146: Assets URL Update
The "assets_url" entries have been updated (pointing to localhost).
• Ensure that these URLs are applicable for your current testing/development environment and remember to update for production if needed.


17487-17511: Updated UI Component Settings
The component now includes "invalidity", "clickCapture", and the framework is explicitly set to Vue.
• Again, note the use of [""] for "invalidity" and consider if an empty array is preferable.


17822-17846: Component Layout Update with Inline and Label-Width
The shortcuts now include options for "inline" and "label-width".
• Also note the "invalidity" field format—if no errors exist, an empty array ([]) may be clearer.


27694-27708: Sortable and Columns Settings for Table Component
The "onBeforeMount" inline code (logging and variable assignments) is included along with shortcuts for "sortable" and "columns".
• Please review that inline script for safety and correctness before deployment.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 38fe39c and 99e8b30.

⛔ Files ignored due to path filters (1)
  • mockServer/src/database/pages.db is excluded by !**/*.db
📒 Files selected for processing (32)
  • mockServer/package.json (1 hunks)
  • mockServer/src/assets/json/appinfo.json (116 hunks)
  • mockServer/src/assets/json/sources.json (1 hunks)
  • mockServer/src/mock/get/app-center/apps/detail/918.json (1 hunks)
  • mockServer/src/mock/get/app-center/sources/list/918.json (1 hunks)
  • mockServer/src/mock/get/app-center/v1/apps/schema/918.json (2 hunks)
  • mockServer/src/mock/post/app-center/apps/update/918.json (0 hunks)
  • mockServer/src/routes/main-routes.js (3 hunks)
  • mockServer/src/services/app.js (1 hunks)
  • mockServer/src/services/source.js (1 hunks)
  • packages/build/vite-config/src/default-config.js (1 hunks)
  • packages/design-core/package.json (1 hunks)
  • packages/design-core/src/preview/src/preview/Preview.vue (3 hunks)
  • packages/design-core/src/preview/src/preview/generate.js (2 hunks)
  • packages/design-core/src/preview/src/preview/srcFiles.js (2 hunks)
  • packages/design-core/src/preview/src/preview/srcFiles/dataSourceMap.js (1 hunks)
  • packages/design-core/src/preview/src/preview/srcFiles/http.js (1 hunks)
  • packages/plugins/datasource/src/DataSourceGlobalDataHandler.vue (5 hunks)
  • packages/plugins/datasource/src/RemoteDataAdapterForm.vue (1 hunks)
  • packages/plugins/datasource/src/js/datasource.js (3 hunks)
  • packages/plugins/materials/src/composable/useResource.js (2 hunks)
  • packages/utils/src/constants/index.js (1 hunks)
  • packages/vue-generator/src/templates/vue-template/templateFiles/genViteConfig.js (1 hunks)
  • packages/vue-generator/src/templates/vue-template/templateFiles/src/http/index.js (1 hunks)
  • packages/vue-generator/src/templates/vue-template/templateFiles/src/lowcodeConfig/dataSource.js (2 hunks)
  • packages/vue-generator/test/testcases/element-plus-case/expected/appdemo01/package.json (1 hunks)
  • packages/vue-generator/test/testcases/element-plus-case/expected/appdemo01/src/http/index.js (1 hunks)
  • packages/vue-generator/test/testcases/element-plus-case/expected/appdemo01/src/lowcodeConfig/dataSource.js (2 hunks)
  • packages/vue-generator/test/testcases/generator/expected/appdemo01/package.json (1 hunks)
  • packages/vue-generator/test/testcases/generator/expected/appdemo01/src/http/index.js (1 hunks)
  • packages/vue-generator/test/testcases/generator/expected/appdemo01/src/lowcodeConfig/dataSource.js (2 hunks)
  • packages/vue-generator/test/testcases/generator/expected/appdemo01/src/lowcodeConfig/dataSource.json (1 hunks)
💤 Files with no reviewable changes (1)
  • mockServer/src/mock/post/app-center/apps/update/918.json
🧰 Additional context used
🪛 GitHub Actions: Push And Create PR Check
mockServer/src/services/source.js

[warning] 1-1: File ignored because of a matching ignore pattern. Use '--no-ignore' to disable file ignore settings or use '--no-warn-ignored' to suppress this warning.

packages/design-core/src/preview/src/preview/srcFiles/dataSourceMap.js

[error] 79-79: Expected an assignment or function call and instead saw an expression @typescript-eslint/no-unused-expressions.

mockServer/src/routes/main-routes.js

[warning] 1-1: File ignored because of a matching ignore pattern. Use '--no-ignore' to disable file ignore settings or use '--no-warn-ignored' to suppress this warning.

mockServer/src/services/app.js

[warning] 1-1: File ignored because of a matching ignore pattern. Use '--no-ignore' to disable file ignore settings or use '--no-warn-ignored' to suppress this warning.

🪛 GitHub Check: push-check
packages/design-core/src/preview/src/preview/srcFiles/dataSourceMap.js

[failure] 79-79:
Expected an assignment or function call and instead saw an expression

packages/plugins/datasource/src/DataSourceGlobalDataHandler.vue

[failure] 108-108:
Expected an assignment or function call and instead saw an expression

packages/vue-generator/src/templates/vue-template/templateFiles/src/lowcodeConfig/dataSource.js

[failure] 71-71:
Expected an assignment or function call and instead saw an expression

🔇 Additional comments (143)
packages/design-core/package.json (1)

95-95: Good addition of axios dependency

Adding axios as a dependency is appropriate for implementing API proxy functionality as mentioned in the PR objectives. Using the tilde version specifier (~0.28.0) is a good practice as it allows for patch-level updates while keeping the major and minor versions locked.

packages/design-core/src/preview/src/preview/srcFiles/http.js (2)

13-18: Good configuration setup with appropriate defaults

The configuration is well-structured with sensible defaults. Using window.parent.location.origin as the baseURL is appropriate for iframe contexts which is likely how the preview operates.


20-87: Well-implemented HTTP client wrapper

The axios wrapper implementation provides a comprehensive set of HTTP methods and properly exposes necessary Axios functionality like interceptors, defaults, and cancel tokens.

packages/utils/src/constants/index.js (1)

133-133: Good addition of DEFAULT_PROXY constant

Adding the DEFAULT_PROXY constant as an empty object is appropriate. This will serve as a fallback value for proxy configuration throughout the application, which aligns with the PR's objective of adding API proxy functionality to the data source.

packages/vue-generator/test/testcases/generator/expected/appdemo01/package.json (1)

16-16: Good practice using fixed version instead of 'latest'

Changing the axios version from "latest" to "~0.28.0" is a good practice that ensures consistent and deterministic builds. This version matches the one added to the design-core package, maintaining consistency across the project.

mockServer/package.json (1)

43-44:

✅ Verification successful

New dependency added for HTTP proxy functionality.

The addition of http-proxy-middleware (v3.0.3) aligns with the PR objective to add API proxy functionality to the data source. This package will allow for request proxying between different endpoints.

Let's verify if this is the latest stable version and if there are any known security issues:


🌐 Web query:

What is the latest version of http-proxy-middleware and are there any security vulnerabilities?

💡 Result:

The latest version of http-proxy-middleware is 3.0.3 as of October 2024[1][10][13]. This version addresses critical security vulnerabilities found in earlier releases.

Security Vulnerabilities

A high-severity Denial of Service (DoS) vulnerability (CVE-2024-21536) affects:

  • Versions <2.0.7
  • Versions 3.0.0 to 3.0.2[2][3][5][11][16]

Key details:

Vulnerability Type CVSS Score Impact
Unhandled Promise Rejection in micromatch 7.5 (High) Allows attackers to crash Node.js processes via malicious path requests[2][3][6]

Mitigation

  • For v2.x users: Upgrade to v2.0.7[1][11]
  • For v3.x users: Upgrade to v3.0.3[1][13][15]
  • IBM watsonx Assistant users should upgrade to v4.8.8+[6]

The vulnerability stems from improper error handling when processing malformed URLs (e.g., //x@x), leading to TypeError crashes in path-matching logic[3][11]. The maintainers patched this by fixing error handling in the micromatch dependency[1][7].

Additional medium-severity vulnerability CVE-2024-4067 was also reported in older versions, though details remain limited[14]. Regular dependency monitoring using tools like Snyk or npm audit is recommended[2][7].

Citations:


HTTP Proxy Dependency Verified

  • The dependency "http-proxy-middleware": "^3.0.3" in mockServer/package.json is confirmed to be the latest stable version as of October 2024.
  • The released version addresses prior high-severity vulnerabilities (e.g., CVE-2024-21536), ensuring that the API proxy functionality is secured.

The addition of this dependency aligns with the PR's objective to implement API proxying without introducing security risks. No further changes are needed.

packages/design-core/src/preview/src/preview/srcFiles.js (1)

26-26:

❓ Verification inconclusive

HTTP client module added to source files.

The addition of the HTTP module to the srcFiles object provides HTTP client functionality for the preview environment. This change supports the new API proxy feature.

However, I noticed that while you've added the HTTP module to the srcFiles object, it's not included in the genPreviewTemplate function. Was this intentional or should it be added to maintain consistency?

Also applies to: 38-38


🏁 Script executed:

#!/bin/bash
# Check if http.js is referenced elsewhere in preview-related files
rg -A 3 -B 3 "http\.js" --type js packages/design-core/src/preview/

Length of output: 1981


Action Required: Confirm HTTP Module Inclusion in Template Function

The HTTP client module is correctly imported and added to the srcFiles object (as seen by the import on line 26 in packages/design-core/src/preview/src/preview/srcFiles.js). However, our search confirms that the genPreviewTemplate function does not reference the HTTP module—even though similar modules are handled there (also affecting lines 38). Please confirm whether this omission is intentional or if the HTTP module should be integrated into genPreviewTemplate for consistency with the rest of the source files.

mockServer/src/services/app.js (1)

34-35: Refactored dataSource structure to include proxy configuration.

The implementation now properly extracts both the proxy configuration and data handler from the data_source_global object, which aligns with the PR objective of adding API proxy functionality.

packages/plugins/materials/src/composable/useResource.js (3)

29-29: Added DEFAULT_PROXY import

The DEFAULT_PROXY constant is now imported alongside other constants, which supports the new proxy configuration functionality being added in this PR.


140-143: Enhanced data handler and proxy configuration

Changes add proxy support and improve data source configuration:

  1. Using globalDataHandler instead of dataHandler for better semantics
  2. Adding proxy configuration with fallback to DEFAULT_PROXY
  3. Ensuring dataSource always defaults to an empty array

This implementation properly supports the new proxy feature while maintaining backward compatibility.


147-148: Improved property naming convention

Changed from snake_case to camelCase for consistency in JavaScript naming conventions:

  • is_demoisDemo
  • global_stateglobalState

This improves code readability and follows standard JavaScript naming practices.

mockServer/src/mock/get/app-center/apps/detail/918.json (3)

72-77: Added proxy configuration for mock API

New proxy configuration that maps requests to /mock path to https://mock.apipost.net with cross-origin support enabled. This aligns with the PR objective to add API proxy capabilities to dataSource.


78-81: Added willFetch interceptor

Implemented a willFetch function that gets executed before making API requests, allowing for request preprocessing. The current implementation simply passes through the option parameter.


86-89: Added error handling interceptor

Implemented an errorHandler function that properly rejects the Promise with the error, allowing for centralized error handling for all data source requests.

packages/design-core/src/preview/src/preview/generate.js (2)

15-35: Added generateDataSource function for enhanced data source processing

This new function provides structured handling of data source configuration:

  1. Extracts the list, handlers (dataHandler, errorHandler) and willFetch from the source
  2. Properly maps data source list items to include their id, name, and data properties
  3. Conditionally adds handlers when they exist
  4. Returns processed data using generateDefaultExport

This implementation provides better organization and structure for data source processing, supporting the new proxy and interceptor capabilities.


179-179: Updated dataSource generation in exports

Replaced direct JSON export with the new generateDataSource function, ensuring proper processing of data source configuration including the new proxy and interceptor features.

packages/design-core/src/preview/src/preview/Preview.vue (1)

200-206: Added proxy configuration to preview environment

Important changes:

  1. Changed appJsCode from const to let to allow modification
  2. Extracted proxy configuration from metadata
  3. Created an info object with proxy and app details
  4. Appended the info to window.appInfo for runtime access

This implementation makes the proxy configuration available to the application in the preview environment, enabling proper testing of API proxying functionality.

packages/vue-generator/test/testcases/generator/expected/appdemo01/src/lowcodeConfig/dataSource.json (1)

627-660: New proxy API data source looks good

The added data source entry for "testProxyApi" follows the established pattern in the codebase and correctly includes all required configuration properties (willFetch, dataHandler, shouldFetch, errorHandler).

packages/vue-generator/test/testcases/generator/expected/appdemo01/src/lowcodeConfig/dataSource.js (4)

19-19: Security improvement: Using Function constructor instead of eval

Replacing eval with the Function constructor is a good security practice as it provides better isolation of the executed code.


24-28: Well-structured global handlers implementation

The addition of global handlers with proper default functionality provides a consistent approach to fetch operations and error handling across all data sources.


33-33: Improved consistency with Promise returns

The changes ensure all code paths return a Promise, which makes the API more predictable and easier to work with in async contexts.

Also applies to: 37-37


75-82: Enhanced HTTP interceptor configuration

The refactored useHttp call with a structured object parameter improves code readability and makes the interceptor setup more maintainable.

packages/plugins/datasource/src/js/datasource.js (3)

25-25: Consistent Promise return

Ensuring all code paths return a Promise makes the API more consistent and easier to use.


108-108: Improved interceptor order

Moving the global data and error handlers to be registered after the specific handlers ensures the data flow is processed in the correct order.


37-49:

✅ Verification successful

API proxy implementation

The implementation correctly checks if the URL matches any proxy configuration and modifies the request appropriately by adding the proxy prefix and required headers.


🏁 Script executed:

#!/bin/bash
# Check for other usage of the proxy_app_id to ensure consistency
rg -p "proxy_app_id" --type js

Length of output: 360


Verified: API Proxy Implementation is Consistent and Correct

The implementation in packages/plugins/datasource/src/js/datasource.js is confirmed to correctly check if the URL should be proxied by comparing against the proxy configuration. The code updates the URL and headers appropriately by adding the proxy prefix and setting the proxy_app_id. Our search for "proxy_app_id" confirms that its usage—including the fallback value 918—is consistent across the codebase (notably in mockServer/src/routes/main-routes.js and packages/design-core/src/preview/src/preview/srcFiles/dataSourceMap.js).

  • The proxy logic properly detects a matching URL and prefixes it with /app-proxy/api.
  • The header proxy_app_id is consistently applied with the fallback 918 where applicable.
packages/vue-generator/test/testcases/element-plus-case/expected/appdemo01/src/http/index.js (1)

16-22: Comprehensive HTTP interceptor configuration

The HTTP module now accepts a more flexible and structured configuration object, allowing for better separation of concerns and more granular control over the request/response flow. The comment about the execution order of request interceptors is also helpful for maintainability.

packages/plugins/datasource/src/RemoteDataAdapterForm.vue (2)

22-24: Enhanced flexibility for modelValue prop type

The type change from Object to [Object, String] allows the component to accept both object and string values, making it more versatile when used with different data sources.


25-32: Good addition of configurable editor options

Adding the options prop with sensible defaults improves component configurability while maintaining backward compatibility. The Monaco editor can now be customized with language, mouse style, and minimap settings.

mockServer/src/mock/get/app-center/v1/apps/schema/918.json (3)

684-718: Added new testProxyApi data source configuration

This addition properly structures a new data source entry with appropriate configuration for API proxying. The empty data array and type configuration follow the pattern of other data sources in the file.


724-729: Added proxy configuration for external API integration

The proxy configuration for the /mock path with changeOrigin: true is correctly set up to forward requests to the external mock API service.


803-808: Improved readability of dataDisk array

The multi-line formatting of the dataDisk array improves code readability and makes it easier to maintain.

packages/vue-generator/src/templates/vue-template/templateFiles/src/http/index.js (1)

16-22: Enhanced HTTP interceptor configuration with more flexible handlers

The updated function signature and interceptor configuration significantly improve the HTTP client's flexibility and error handling capabilities. The implementation now:

  1. Accepts multiple handler functions via a structured object
  2. Properly sets up request interceptors with global and specific handlers
  3. Configures response interceptors with proper error handling chain

This architecture follows best practices by separating concerns and allowing for more granular control of the request/response lifecycle.

mockServer/src/routes/main-routes.js (2)

19-19: Added http-proxy-middleware dependency

The import of createProxyMiddleware is necessary for implementing the proxy functionality.


63-69: Added route for updating app data sources

This route handler properly extracts and processes data source global configuration from the request body.

packages/vue-generator/test/testcases/generator/expected/appdemo01/src/http/index.js (1)

16-16:

❓ Verification inconclusive

Ensure consumer code has been updated accordingly.

The updated export signature introduces new parameters for interceptors. Verify that all importing modules pass the newly required fields (globalWillFetch, globalDataHandle, globalErrorHandler, willFetch, dataHandler, errorHandler) correctly.

You can confirm usage consistency with this script:


🏁 Script executed:

#!/bin/bash
# Find all imports of this file in the codebase, checking for usage of the new parameters
rg "import .* from .*/http/index" -A 5

Length of output: 517


Update Export Signature – Verify Consumer Parameter Usage

The export in packages/vue-generator/test/testcases/generator/expected/appdemo01/src/http/index.js now expects six parameters for interceptors. Our search shows that the file is imported as raw content in the template at packages/vue-generator/src/templates/vue-template/index.js, which means it isn’t directly invoked with parameters.

  • Action: Ensure that any consumer code that directly calls this function (post-generation) is updated to pass all six required parameters (globalWillFetch, globalDataHandle, globalErrorHandler, willFetch, dataHandler, errorHandler).
  • Note: If this file is used solely as a template, review downstream code that processes the template to confirm that it incorporates the new interceptor parameters correctly.
packages/vue-generator/test/testcases/element-plus-case/expected/appdemo01/src/lowcodeConfig/dataSource.js (2)

24-28: Global error, fetch, and data handlers look good.

Defining default handlers ensures no unhandled exceptions occur. This setup is clear and modular.


33-37: Consistent promise returns.

Returning promises in these early-return scenarios is good for uniform async handling. This helps avoid unhandled promise rejections and ensures the rest of the chain sees a resolved promise.

mockServer/src/assets/json/sources.json (1)

668-695: New “testProxyApi” data source added.

This new configuration for a proxy endpoint under ID 152 is well-structured and consistent with the existing format. Confirm it’s properly referenced in the application where necessary (e.g., the UI or load functions).

packages/design-core/src/preview/src/preview/srcFiles/dataSourceMap.js (2)

22-26: Global interceptors look good.

The fallback handlers and usage of Promise.reject for errors help maintain consistent error handling across the application.


92-93: Initialization and load assignment.

Setting the data source status and exposing load is cleanly structured. Defaulting status to 'init' helps track usage states for debugging or UI feedback.

mockServer/src/assets/json/appinfo.json (93)

1791-1801: Updated 'createVm' Page Content Structure
The hunk updates the page configuration with a "dataDisk" array and associated "page_content" changes.
• Ensure that the new state (and the empty "methods" block) are consistent with the UI requirements for the page.


2832-2842: Revised Pagination Configuration
The "pageSizes" array is now clearly defined with options [10, 20, 50].
• Double‐check that the pagination behavior in the application uses these values as intended.


3570-3579: Updated Loop Arguments in Component Configuration
The addition of "loopArgs": ["item", "idx"] makes the loop structure explicit.
• Confirm that these names match the expected parameters in your component logic.


4094-4101: Refined Materials Component Structure
An empty snippet object has been inserted into the "snippets" array, which could serve as a placeholder.
• Please confirm that this is intentional and that consumers of this configuration can handle an empty object.


5469-5494: Updated Layout Configuration with Slots
The settings now include a "slots": ["content"] entry, which should help in rendering.
• Please verify that the revised layout meets the design needs.


6000-6006: Component Grouping Enhancements
The "snippets" array now includes an empty object.
• Verify that this placeholder is intentional for future content.


6409-6417: Event Function Configuration Update
Event handling in this block uses null for the parameters.
• Verify that using null here is acceptable for your event handling strategy.


6424-6432: Consistent Event Function Settings
Similar to the previous block, ensure that the event function’s parameters (set as null) are correctly handled by the related code.


6716-6740: Layout and Event Configuration Update
The layout properties now include the "invalidity" attribute.
• Confirm that the representation of “no error” as [""] is intentional.


7328-7347: Form Component UI Configuration Update
The changes in this block (specifically shortcuts and context menu actions) are comprehensive.
• Confirm that the modifications meet the overall design intent.


7628-7636: Event Configuration Accuracy Check
The "functionInfo" block using null for parameters is updated here.
• Please ensure that this is compatible with your event handler implementation.


7643-7651: Consistent Event Configuration
The event function’s parameter configuration is similar to prior blocks.
• No discrepancies noted.


7765-7784: Component Layout Configuration Update
The updated configuration for "shortcuts" and "contextMenu" appears to be in line with previous updates.
• Please verify overall integration with your UI component system.


7968-7976: Form Component Snippets Update
The insertion of an empty object into "snippets" is noted.
• Confirm that this serves as the intended placeholder.


7987-8010: Enhanced Layout Settings for Component
The update now includes "slots": ["label"] along with updated shortcuts.
• Please verify that this matches the visual structure you require.


8578-8586: Event Configuration Check
The event parameters remain set as null.
• Confirm that this setup is fully documented and intended.


9238-9258: Updated Component Settings for Tabs or Similar
The updated "shortcuts" (e.g. for tab styling) look good.
• Double-check that the "tab-style" setting is applied as expected in the UI.


10011-10019: Event Function Information Updated
The "functionInfo" block now details the event handler parameters.
• Confirm that no additional parameters are required.


10026-10034: Consistency in Event Function Settings
The event parameters remain set to null for this instance.
• Verify consistency with similar event configurations in the file.


10041-10049: Review Event Configuration Update
The current event function configuration is consistent with previous ones.


10110-10127: Dialog Box Component Configuration
The settings for the dialog box (including a specified "rootSelector": ".tiny-dialog-box") look good.


10499-10517: Component Shortcuts Update
The updated shortcuts for "disabled" and "mini" are clear and seem to follow the established pattern.


10794-10814: Layout Properties Updated
The "shortcuts" now include properties like "horizontal", an empty string, and "active".
• Please verify that these are the correct and expected values.


11110-11129: UI Configuration for Name and Title
The updated shortcuts now include "name" and "title".
• Please ensure that these properties are used in the expected manner across the UI.


11674-11681: Component Shortcuts Verification
The changes for "label-width" and "disabled" in the shortcuts are proper.


12154-12181: Framework and Invalidity Config Update
The framework is clearly set to Vue, and the structure appears sound.
• Again, reflect on the use of [""] for "invalidity".


12417-12426: Widget Configuration Enhancement
The new widget configuration using "JsSlotConfigurator" along with its "slots" ("header" and "default") looks well formed.


12936-12944: Event Handler Configuration Verification
Review the "functionInfo" block for this event. Parameters are set as null—please verify that this is acceptable.


12951-12959: Consistent Event Function Format
The event configuration in this block is consistent with others.


12966-12974: Updated Event Parameter
The event now takes a parameter "e".
• Confirm that this change matches the caller’s expectations in the event handling code.


13632-13640: Event Configuration Detail Check
The "functionInfo" block here appears correct.


13647-13655: Event Function Consistency
The event function’s configuration is in step with similar definitions.


13662-13670: Confirm Event Function Parameters
Again, event parameters remain null here—please ensure that this fits with the overall event handling implementations.


13703-13712: New Schema for TinyCheckboxGroup
The schema now defines "modelValue", "type", and "options" correctly.
• Verify that the initial "modelValue" array (with "name1" and "name2") is as expected for your use case.


13767-13786: Component Text Configuration Update
The "shortcuts" for "text" and "size" have been updated.
• Ensure that the context menu actions remain consistent following these changes.


14071-14091: Multi-selection Options Updated
The shortcuts now include properties for multiple selections.
• Confirm that these values meet the UI and interaction specifications.


14579-14598: Form Component Adjustment
Updated properties for "disabled" and "size" are clearly set, and the Vue framework is specified.


14767-14775: Event Handler Configuration Check
Review the event configuration here and ensure that the function info (with parameters as null) aligns with other similar event handlers.


14855-14878: Arrow Shortcut and Slot Configuration
The update now includes an "arrow" property in shortcuts and defines "slots": ["default"].
• Verify that these changes integrate correctly into the component’s rendering logic.


15269-15288: Placeholder and Clear Button Update
New properties "placeholder" and "show-clear-btn" have been added.
• Please verify that these align with your input field design expectations.


16359-16383: Updated Trigger and Size Configuration
The shortcuts for "size" and "trigger" are updated and appear correct.
• Please verify that the accompanying "invalidity" and "clickCapture" settings are as intended.


16725-16733: Event Function Parameters Verification
This event configuration uses null for parameters and appears standard.


16740-16748: Consistent Event Handling Update
The event configuration remains in line with the previously established pattern.


16755-16763: Final Event Function Check
No discrepancies noted in this event setup; it matches similar handlers.


16797-16807: TinyChartHistogram Configuration Update
The "columns" array and the "rows" structure have been defined.
• Confirm that this structure meets the expected schema for your chart component.


17195-17219: Component Configuration Check
The updated shortcuts and context menu actions are consistent.


17811-17819: Nesting Rule Configuration for ElFormItem
The "childWhitelist" includes "ElFormItem".
• Confirm that this restriction is correctly applied in nested components.


18291-18315: Consistent UI Configuration
The updated configuration appears to mirror previous changes regarding inline display and label-width.


18644-18652: Nesting Rule Update for TinyTableColumn
The "childWhitelist" is updated with "ElTableColumn".
• Verify that nesting rules correctly reflect your component hierarchy.


18655-18679: UI Configuration with Inline and Label-Width
Review that the shortcuts and associated settings remain in sync with your design specifications.


19903-19927: Consistent UI Layout Configuration
The updated shortcuts, invalidity, and context menu actions are consistent with earlier blocks.


20068-20086: Configuration Update for Component
The shortcuts and context menu actions (e.g. for "disabled" and "size") have been refreshed.
• Make sure that these values match the component’s functional requirements.


20398-20406: Nesting Rule for TinyCarouselItem
The whitelist for "TinyCarouselItem" is now defined.
• Verify that this setting is correct for the carousel’s intended structure.


20409-20427: Component UI Configuration Accuracy
Ensure that the shortcuts for "disabled" and "size" are exactly as intended, and that the context menu actions are complete.


20577-20590: Component Metadata Update for Title
The metadata now supports multiple header tags (from h1 to h6).
• Confirm that the provided "icon" and "description" are correct.


20675-20693: Form Component Context Menu Update
The updated shortcuts for "disabled" and "size" are set, and the context menu action "create symbol" is introduced.


21056-21074: Configuration Update for Related Component
The shortcuts and context menu actions are consistent with previous patterns.


21321-21329: Content Menu vs. Context Menu Clarification
Notice that "contentMenu" is used here instead of "contextMenu".
• Please confirm that this naming difference is intentional and that consumers of this configuration expect it.


21998-22016: Component Configuration Consistency
The updated shortcuts for "disabled" and "size" align with your design specifications.


22156-22174: UI Layout Configuration for Label-Width
The updated shortcuts now include "label-width" and "disabled".
• Verify that the context menu actions remain in line with the components’ capabilities.


22517-22535: Review of Label-Width Shortcuts
Please double-check that the shortcuts for "label-width" and "disabled" match your intended UI behavior.


22652-22680: Updated Nesting Rules for TinyForm
The nesting rules and shortcuts (e.g. for "label" and "rules") appear accurate.


22952-22970: Component Shortcuts for Label and Rules
The updated "properties" (for "label" and "rules") are clearly defined.


23300-23318: Text and Size Shortcuts Update
The configuration for "text" and "size" in the shortcuts is clear.


23723-23741: Value and Disabled Property Configuration
The shortcuts settings here have been updated appropriately.


23970-23988: Component Visibility and Width Settings
The updated shortcuts for "visible" and "width" are in place.


24386-24404: Multiple Options for Component Updated
The shortcuts now include "multiple" and "options".
• Confirm that the context menu actions are still aligned with the functionality.


24596-24614: Disabled and Mini Settings Update
The new settings for "disabled" and "mini" appear as expected—please verify against your design.


24883-24901: Clearable and Mini Configuration
The updated shortcuts for "clearable" and "mini" are clear.


25150-25168: Border and Disabled Configuration Update
Re-check that the shortcuts for "border" and "disabled" meet styling requirements.


25349-25367: Text and Size Shortcuts Confirmation
The updated configuration appears consistent and correct.


25568-25586: Disabled and Type Shortcut Configuration
Verify that the shortcuts for "disabled" and "type" are correct and match the intended design.


25856-25874: Dialog Box Visibility and Width Settings
The configuration targeting .tiny-dialog-box with "visible" and "width" is properly outlined.


26140-26148: Nesting Rule for TinyTabItem
Confirm that the updated nesting rule (child whitelist for "TinyTabItem") meets your layout expectations.


26151-26169: Tab-Style Shortcuts Update
The shortcuts now include "size" and "tab-style".
• Ensure that these values are rendered and function as expected in the tab component.


26264-26292: Nesting Rule and Shortcuts for TinyTab
The nesting settings (with "parentWhitelist") as well as shortcuts for "name" and "title" are updated.


26409-26417: TinyBreadcrumbItem Nesting Rule
The whitelist for "TinyBreadcrumbItem" is correctly specified.


26420-26437: Separator Shortcut Configuration
Review that the shortcut for "separator" is defined as intended.


26512-26539: Nesting Rule for TinyBreadcrumb
The shortcuts now include a single property "to".
• Confirm that the nesting rules for "TinyBreadcrumb" are correct.


26661-26679: Shortcut Configuration for Label-Width in Tiny Components
The updated settings for "label-width" and "disabled" appear in line with the design.


26784-26802: Confirm Shortcut Settings for Label-Width
The configuration is consistent with previous similar blocks.


27013-27022: Widget Configuration for JS Slot Configurator
The widget block correctly uses "JsSlotConfigurator" with slots "header" and "default".


27722-27740: Table Component Sorting Configuration Update
The shortcuts for "sortable" and "columns" appear to be updated appropriately.


27761-27769: Content Menu Configuration Update
The block now specifies a "contentMenu" with the action "create symbol".
• Verify whether this alternate naming (compared to "contextMenu") is intentional.


27783-27795: Context Menu Settings in Table Component
The updated context menu includes a list of actions with a "disable" array.


28022-28040: Pagination Shortcut Update
The shortcuts now include "currentPage" and "total".
• Ensure that these values correctly reflect the pagination state.


28396-28414: Model Value and Disabled Shortcut Update for Form Component
The updated shortcuts here look correct; verify the corresponding context menu actions.


28720-28738: Data and Checkbox Configuration Update
The shortcuts now include "data" and "show-checkbox".
• Please ensure proper integration with your form component behavior.


28937-28955: Active State and Data Configuration Update
The updated configuration for "active" and "data" appears tidy.


29145-29163: Disabled Content Shortcut for Component Update
The shortcuts now combine "disabled" and "content"—verify that this meets your component’s needs.


29639-29657: Visibility and Width Shortcut Check
The updated shortcuts for "visible" and "width" are in place; please confirm their correctness in practice.


30063-30081: Value and Disabled Shortcut Update
The shortcuts have been updated for "value" and "disabled".


30516-30534: Final Shortcut Configuration Update
The configuration for "value" and "disabled" here remains consistent with other blocks.

packages/plugins/datasource/src/DataSourceGlobalDataHandler.vue (6)

6-8: Great addition of cross-origin proxy configuration!

The new proxy configuration section allows users to set up cross-origin requests, which is essential for dealing with API endpoints on different domains. This is a valuable feature for the data source handler.


33-34: Good use of constants for default values

Using the constants from the utils package ensures consistency across the application and makes maintenance easier.


54-69: Well-implemented editor options with helpful placeholder

The code provides excellent documentation in the placeholder with a practical example of proxy configuration, which will help users understand the expected format.


71-72: Good initialization with proper formatting

Using JSON.stringify with formatting parameters (null, 2) creates a well-formatted JSON string that will be more readable in the editor.


80-86: Robust handling of proxy configuration with fallback

The code properly parses the proxy configuration and uses DEFAULT_PROXY as a fallback, ensuring the application won't break if the configuration is missing or invalid.


92-94: Ensure state is properly updated after save

Good approach to update the appSchemaState with the new values. This ensures that the UI reflects the saved changes correctly.

packages/vue-generator/src/templates/vue-template/templateFiles/src/lowcodeConfig/dataSource.js (4)

19-19: Security improvement by using Function constructor instead of eval

Using the Function constructor is a safer approach than eval for dynamically creating functions from strings. This change improves security while maintaining the same functionality.


24-28: Well-structured global handlers with appropriate fallbacks

The global handlers are well-defined with proper fallback implementations. The globalErrorHandler properly returns a rejected promise to maintain consistent promise-based error handling.


33-34: Consistent Promise-based return values

Excellent improvement by ensuring all code paths return Promises. This makes the function's behavior more predictable and easier to work with in async contexts.

Also applies to: 37-38


75-82: Improved HTTP initialization with comprehensive handlers

The refactored HTTP initialization now accepts multiple handlers in a structured object, making the code more maintainable and clearer. This approach properly separates global and local handlers.

@@ -13,7 +13,7 @@
"@opentiny/tiny-engine-i18n-host": "^1.0.0",
"@opentiny/vue": "^3.10.0",
"@opentiny/vue-icon": "^3.10.0",
"axios": "^0.21.1",
"axios": "~0.28.0",
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Axios dependency updated to newer version with stricter versioning.

The change from ^0.21.1 to ~0.28.0 updates axios to a significantly newer version while also changing the versioning strategy from caret (^) to tilde (~). This means only patch updates will be allowed rather than minor version updates.

Let's verify the security implications of this version change:


🏁 Script executed:

#!/bin/bash
# Check if 0.28.0 is the latest version and if there are any security advisories

# Get the latest version
echo "Checking latest axios version..."
npm view axios version

# Check for known vulnerabilities in axios
echo "Checking for vulnerabilities in axios 0.28.0..."
npm audit --package [email protected] || echo "Audit command failed, but continuing..."

# Check GitHub security advisories
echo "Checking GitHub security advisories..."
gh api graphql -f query='
{
  securityVulnerabilities(first: 5, ecosystem: NPM, package: "axios") {
    nodes {
      advisory {
        summary
        severity
        publishedAt
      }
      vulnerableVersionRange
      firstPatchedVersion {
        identifier
      }
    }
  }
}'

Length of output: 2237


Security Advisory: Axios Dependency Update Needed

  • In packages/vue-generator/test/testcases/element-plus-case/expected/appdemo01/package.json the axios dependency was updated from ^0.21.1 to ~0.28.0, which restricts updates to only patch versions.
  • Verification shows that while this change reflects a newer release relative to 0.21.1, axios 0.28.0 is still affected by a HIGH severity vulnerability ("axios Requests Vulnerable To Possible SSRF and Credential Leakage via Absolute URL") that applies to versions below 1.8.2. The latest version is 1.8.3.
  • Recommendation: Upgrade the axios dependency to at least 1.8.2 (preferably 1.8.3) to mitigate this security risk.

Comment on lines +669 to 702
{
"id": 152,
"name": "testProxyApi",
"data": {
"data": [],
"type": "array",
"columns": [],
"options": {
"uri": "/mock/41534bc9c0e0000/province?apipost_id=1534d5e9f71002",
"method": "GET"
},
"willFetch": {
"type": "JSFunction",
"value": "function willFetch(option) {\n return option \n}"
},
"dataHandler": {
"type": "JSFunction",
"value": "function dataHandler(data) { \n return data \n}"
},
"shouldFetch": {
"type": "JSFunction",
"value": "function shouldFetch(option) {\n return true \n}"
},
"errorHandler": {
"type": "JSFunction",
"value": "function errorHandler(err) {}"
}
},
"tpl": null,
"app": "918",
"desc": null,
"created_at": "2022-07-04T02:20:07.000Z",
"updated_at": "2022-07-04T06:25:29.000Z"
}
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Added new testProxyApi data source for API proxy testing.

The new data source entry is well-structured and includes all necessary configurations for the mock API endpoint, including fetch handling functions.

Let's verify if the endpoint URI is accessible:


🏁 Script executed:

#!/bin/bash
# Check if the API endpoint format is valid and potentially reachable

echo "Checking API endpoint format..."
URI="/mock/41534bc9c0e0000/province?apipost_id=1534d5e9f71002"

# Validate URI format
if [[ $URI =~ ^/[a-zA-Z0-9/_\-\.?=&]+ ]]; then
  echo "URI format appears valid"
else
  echo "URI format appears invalid"
fi

# Check if this is likely an ApiPost mock endpoint
if [[ $URI == *"apipost_id"* ]]; then
  echo "This appears to be an ApiPost mock endpoint"
fi

# Note: We can't actually connect to the endpoint in this environment
# This would require running the application with the proxy middleware configured
echo "Note: Full connectivity testing would require running the application"

Length of output: 269


API Endpoint Verification – Action Required on Regex in Verification Script

  • The new testProxyApi data source entry in mockServer/src/mock/get/app-center/sources/list/918.json is correctly structured with all necessary configurations. The endpoint URI (/mock/41534bc9c0e0000/province?apipost_id=1534d5e9f71002) follows the expected ApiPost mock endpoint pattern.

  • However, the verification shell script encountered a syntax error due to the regex pattern—in particular, the unescaped ampersand (&) is causing the issue.

  • Recommendation: Update the regex pattern in the script. For example, consider quoting the entire regex or escaping the ampersand (e.g., use \&) so that the condition reads similar to:

    if [[ $URI =~ ^/[a-zA-Z0-9/_\-\.?=\\&]+$ ]]; then
      echo "URI format appears valid"
    fi
  • These changes will ensure reliable local verification of the endpoint format.

Comment on lines +730 to 737
"willFetch": {
"type": "JSFunction",
"value": "function willFetch(option) {\n return option\n}"
},
"errorHandler": {
"type": "JSFunction",
"value": "function errorHandler(err) {\n return Promise.reject(err)\n}"
}
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

Added request interceptor functions

The willFetch and errorHandler functions provide proper hooks for request processing and error handling. However, there's a typo in the existing function name on line 720-722.

Fix the typo in the function name from "dataHanlder" to "dataHandler":

"dataHandler": {
  "type": "JSFunction",
-  "value": "function dataHanlder(res){\n return res;\n}"
+  "value": "function dataHandler(res){\n return res;\n}"
}

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +236 to +267
// 定义一个拦截并转发的路由,
router.all('/app-proxy/api/*', async (ctx) => {
// 通过请求头获取APP-ID 来获取具体应用配置的代理
const appId = 918 || ctx.headers.proxy_app_id;
const { data } = getJsonPathData(path.resolve(__dirname, `../mock/get/app-center/apps/detail/${appId}.json`))
// 修改 ctx, req 路径、请求体, 用于代理
// TODO 请求体参数仅处理了body、query;JAVA服务端代码代理需要完整补全
ctx.req.url = ctx.url.replace('/app-proxy/api', '')
ctx.req.query = ctx.request.query;
ctx.req.body = ctx.request.body;
const config = data?.data?.data_source_global?.proxy || {}
let i = -1;
const keys = Object.keys(config);
keys.forEach((item, index) => {
if (ctx.path.includes(item)) {
i = index;
}
})
if (i === -1) {
ctx.body = { msg: '无数据', data: [] }
} else {
const conf = Object.values(config)[i];
// 添加拦截逻辑,代理转发接口
const proxy = createProxyMiddleware(conf);
// 使用代理中间件处理请求
await new Promise((resolve, reject) => {
proxy(ctx.req, ctx.res, (err) => {
err? reject(err) : resolve();
});
});
}
});
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

Implemented API proxy route with dynamic configuration

The new catch-all route (/app-proxy/api/*) creates a flexible proxy mechanism that:

  1. Retrieves app-specific proxy configuration
  2. Modifies the request context for proper forwarding
  3. Dynamically selects the appropriate proxy configuration based on the request path
  4. Provides fallback handling for unmatched paths

However, there's a potential issue with the app ID retrieval logic.

The app ID assignment uses a logical OR with a constant, which means it will always use 918:

- const appId = 918 || ctx.headers.proxy_app_id;
+ const appId = ctx.headers.proxy_app_id || 918;

This change ensures it first tries to get the app ID from headers and falls back to 918 if not present.

📝 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
// 定义一个拦截并转发的路由,
router.all('/app-proxy/api/*', async (ctx) => {
// 通过请求头获取APP-ID 来获取具体应用配置的代理
const appId = 918 || ctx.headers.proxy_app_id;
const { data } = getJsonPathData(path.resolve(__dirname, `../mock/get/app-center/apps/detail/${appId}.json`))
// 修改 ctx, req 路径、请求体, 用于代理
// TODO 请求体参数仅处理了body、query;JAVA服务端代码代理需要完整补全
ctx.req.url = ctx.url.replace('/app-proxy/api', '')
ctx.req.query = ctx.request.query;
ctx.req.body = ctx.request.body;
const config = data?.data?.data_source_global?.proxy || {}
let i = -1;
const keys = Object.keys(config);
keys.forEach((item, index) => {
if (ctx.path.includes(item)) {
i = index;
}
})
if (i === -1) {
ctx.body = { msg: '无数据', data: [] }
} else {
const conf = Object.values(config)[i];
// 添加拦截逻辑,代理转发接口
const proxy = createProxyMiddleware(conf);
// 使用代理中间件处理请求
await new Promise((resolve, reject) => {
proxy(ctx.req, ctx.res, (err) => {
err? reject(err) : resolve();
});
});
}
});
// 定义一个拦截并转发的路由,
router.all('/app-proxy/api/*', async (ctx) => {
// 通过请求头获取APP-ID 来获取具体应用配置的代理
const appId = ctx.headers.proxy_app_id || 918;
const { data } = getJsonPathData(path.resolve(__dirname, `../mock/get/app-center/apps/detail/${appId}.json`))
// 修改 ctx, req 路径、请求体, 用于代理
// TODO 请求体参数仅处理了body、query;JAVA服务端代码代理需要完整补全
ctx.req.url = ctx.url.replace('/app-proxy/api', '')
ctx.req.query = ctx.request.query;
ctx.req.body = ctx.request.body;
const config = data?.data?.data_source_global?.proxy || {}
let i = -1;
const keys = Object.keys(config);
keys.forEach((item, index) => {
if (ctx.path.includes(item)) {
i = index;
}
})
if (i === -1) {
ctx.body = { msg: '无数据', data: [] }
} else {
const conf = Object.values(config)[i];
// 添加拦截逻辑,代理转发接口
const proxy = createProxyMiddleware(conf);
// 使用代理中间件处理请求
await new Promise((resolve, reject) => {
proxy(ctx.req, ctx.res, (err) => {
err ? reject(err) : resolve();
});
});
}
});

Comment on lines 70 to 83
const shouldFetch = config.shouldFetch?.value ? createFn(config.shouldFetch.value) : () => true
const willFetch = config.willFetch?.value ? createFn(config.willFetch.value) : (options) => options
const dataHandler = (res) => {
const data = config.dataHandler?.value ? createFn(config.dataHandler.value)(res) : res
dataSource.status = 'loaded'
dataSource.data = data
return data
}
const errorHandler = (error) => {
config.errorHandler?.value && createFn(config.errorHandler.value)(error)
dataSource.status = 'error'
dataSource.error = 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

Resolve linter warning by avoiding lone short-circuiting.

Line 79 uses a short-circuit operator to call createFn(config.errorHandler.value) if present. This triggers an ESLint rule, “no-unused-expressions.” Replace it with an if-statement:

- config.errorHandler?.value && createFn(config.errorHandler.value)(error)
+ if (config.errorHandler?.value) {
+   createFn(config.errorHandler.value)(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 shouldFetch = config.shouldFetch?.value ? createFn(config.shouldFetch.value) : () => true
const willFetch = config.willFetch?.value ? createFn(config.willFetch.value) : (options) => options
const dataHandler = (res) => {
const data = config.dataHandler?.value ? createFn(config.dataHandler.value)(res) : res
dataSource.status = 'loaded'
dataSource.data = data
return data
}
const errorHandler = (error) => {
config.errorHandler?.value && createFn(config.errorHandler.value)(error)
dataSource.status = 'error'
dataSource.error = error
}
const shouldFetch = config.shouldFetch?.value ? createFn(config.shouldFetch.value) : () => true
const willFetch = config.willFetch?.value ? createFn(config.willFetch.value) : (options) => options
const dataHandler = (res) => {
const data = config.dataHandler?.value ? createFn(config.dataHandler.value)(res) : res
dataSource.status = 'loaded'
dataSource.data = data
return data
}
const errorHandler = (error) => {
if (config.errorHandler?.value) {
createFn(config.errorHandler.value)(error)
}
dataSource.status = 'error'
dataSource.error = error
}
🧰 Tools
🪛 GitHub Check: push-check

[failure] 79-79:
Expected an assignment or function call and instead saw an expression

🪛 GitHub Actions: Push And Create PR Check

[error] 79-79: Expected an assignment or function call and instead saw an expression @typescript-eslint/no-unused-expressions.

if (value) {
window.dispatchEvent(new Event('resize'))
}
value && window.dispatchEvent(new Event('resize'))
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

Fix expression statement linting issue

The line is flagged by the static analyzer because it's an expression statement without assignment or function call effect.

-          value && window.dispatchEvent(new Event('resize'))
+          if (value) {
+            window.dispatchEvent(new Event('resize'))
+          }
📝 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
value && window.dispatchEvent(new Event('resize'))
if (value) {
window.dispatchEvent(new Event('resize'))
}
🧰 Tools
🪛 GitHub Check: push-check

[failure] 108-108:
Expected an assignment or function call and instead saw an expression

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

♻️ Duplicate comments (1)
packages/vue-generator/src/templates/vue-template/templateFiles/src/lowcodeConfig/dataSource.js (1)

71-72: ⚠️ Potential issue

Fix missing return statement in errorHandler function.

The code still contains the issue identified in a previous review. The expression statement doesn't properly handle the error flow or return a value.

-    // eslint-disable-next-line @typescript-eslint/no-unused-expressions
-    config.errorHandler?.value && createFn(config.errorHandler.value)(error)
+    if (config.errorHandler?.value) {
+      return createFn(config.errorHandler.value)(error)
+    }
+    return Promise.reject(error)
🧹 Nitpick comments (1)
packages/plugins/datasource/src/DataSourceGlobalDataHandler.vue (1)

71-71: Consider adding validation for proxy JSON.

The proxy value is stored as a stringified JSON. Consider adding validation to ensure it's always in valid JSON format.

-      proxy: JSON.stringify(proxy, null, 2),
+      proxy: proxy ? JSON.stringify(proxy, null, 2) : '{}',
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 99e8b30 and c700ed1.

📒 Files selected for processing (3)
  • packages/design-core/src/preview/src/preview/srcFiles/dataSourceMap.js (1 hunks)
  • packages/plugins/datasource/src/DataSourceGlobalDataHandler.vue (5 hunks)
  • packages/vue-generator/src/templates/vue-template/templateFiles/src/lowcodeConfig/dataSource.js (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/design-core/src/preview/src/preview/srcFiles/dataSourceMap.js
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: push-check
🔇 Additional comments (9)
packages/vue-generator/src/templates/vue-template/templateFiles/src/lowcodeConfig/dataSource.js (5)

19-19: Security improvement by replacing eval with Function constructor.

Using new Function() instead of eval() provides better security by restricting the execution scope. This is a good change that adheres to best practices for handling dynamic code execution.


24-28: Good addition of standardized global handlers for request pre-processing and error handling.

The addition of globalWillFetch and globalErrorHandler improves the code by:

  1. Providing consistent request pre-processing behavior
  2. Ensuring proper Promise rejection in error cases
  3. Following the same pattern as the existing globalDataHandle

This creates a more uniform and predictable API.


33-33: Consistent Promise return for static data.

Wrapping the static data handler with Promise.resolve() ensures consistent behavior for synchronous and asynchronous data flow, which is a good practice.


37-37: Consistent Promise return when shouldFetch is false.

The change to return Promise.resolve(undefined) ensures a consistent Promise-based API regardless of the execution path, which improves predictability.


76-83: Improved HTTP client initialization with structured handler configuration.

Refactoring the useHttp initialization to use a structured object with all handlers improves readability and maintainability. This approach clearly shows the relationship between global and source-specific handlers.

packages/plugins/datasource/src/DataSourceGlobalDataHandler.vue (4)

6-8: Good addition of the proxy configuration UI section.

The new collapse item for cross-domain proxy configuration provides a clean way for users to configure proxy settings through the UI. The component reuses the existing data-handler-editor pattern for consistency.


33-33: Include DEFAULT_PROXY in constants import.

Good practice to destructure all required constants from the same import.


54-69: Well-structured proxy configuration options.

The JSON editor configuration with explanatory placeholder text is helpful for users. The example provides clear guidance on the expected format for proxy settings.


108-109: Fix expression statement linting issue properly.

The line is still using an expression statement with a linting disable comment. It would be better to implement the suggested fix from the previous review by using an if statement instead.

-          // eslint-disable-next-line @typescript-eslint/no-unused-expressions
-          value && window.dispatchEvent(new Event('resize'))
+          if (value) {
+            window.dispatchEvent(new Event('resize'))
+          }

@1degrees 1degrees force-pushed the feat/AddProxyInDataSource branch from c700ed1 to 187cf0a Compare March 14, 2025 01:25
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

♻️ Duplicate comments (2)
mockServer/src/routes/main-routes.js (1)

239-239: ⚠️ Potential issue

Fix app ID retrieval logic

The current implementation always uses 918 as the app ID due to the incorrect use of the logical OR operator. The right operand will never be evaluated.

-    const appId = 918 || ctx.headers.proxy_app_id;
+    const appId = ctx.headers.proxy_app_id || 918;
mockServer/src/assets/json/appinfo.json (1)

30604-30626: ⚠️ Potential issue

Critical: Typo in Global Data Source Proxy Configuration
In the global "data_source_global" section, the function intended to be "dataHandler" is misspelled as "dataHanlder" (line 30618–30619).
Action Required: Correct the spelling of this function name to "dataHandler" to avoid runtime errors.
Suggested Diff:

- "value": "function dataHanlder(res){\n return res;\n}"
+ "value": "function dataHandler(res){\n return res;\n}"
🧹 Nitpick comments (15)
packages/design-core/src/preview/src/preview/srcFiles/http.js (2)

13-18: Configuration settings should be more flexible

The HTTP client configuration sets hardcoded values for withCredentials and baseURL. Consider making these configurable through parameters to allow for different environments and use cases.

-const config = {
-  withCredentials: false,
-  baseURL: window.parent.location.origin
-}
+const getDefaultConfig = (customConfig = {}) => ({
+  withCredentials: false,
+  baseURL: window.parent.location.origin,
+  ...customConfig
+})

91-92: Translate Chinese comment to English for consistency

The codebase appears to use English for documentation. Consider translating this comment to maintain consistency.

-  // axios对于request拦截器是后注册先执行
+  // For axios request interceptors, the last registered one executes first
packages/vue-generator/src/templates/vue-template/templateFiles/src/http/index.js (1)

18-22: Translate Chinese comment to English for consistency

The codebase appears to use English for documentation. Consider translating this comment to maintain consistency.

-  // axios对于request拦截器是后注册先执行
+  // For axios request interceptors, the last registered one executes first
mockServer/src/routes/main-routes.js (3)

242-243: Document the TODO more clearly or implement the solution

The TODO comment about request body parameters is vague. Either provide more details about what needs to be completed or implement the solution to handle all necessary request parameters.

-    // TODO 请求体参数仅处理了body、query;JAVA服务端代码代理需要完整补全
+    // TODO: The request parameters currently only handle body and query. 
+    // The Java server-side proxy code needs to be fully complemented with headers, cookies, etc.

261-265: Improve error handling in proxy middleware

The current error handling simply rejects the promise but doesn't provide any detailed error information or logging. Consider enhancing this to give better visibility into proxy failures.

      await new Promise((resolve, reject) => {
        proxy(ctx.req, ctx.res, (err) => {
-          err? reject(err) : resolve();
+          if (err) {
+            console.error('Proxy error:', err);
+            ctx.status = 500;
+            ctx.body = { error: 'Proxy error', message: err.message };
+            reject(err);
+          } else {
+            resolve();
+          }
        });
      });

247-257: Inefficient path matching logic

The current implementation loops through all keys to find a match, which is inefficient. Consider using a more direct approach like find() or a map lookup.

-    let i = -1;
-    const keys = Object.keys(config);
-    keys.forEach((item, index) => {
-      if (ctx.path.includes(item)) {
-        i = index;
-      }
-    })
-    if (i === -1) {
-      ctx.body = { msg: '无数据', data: [] }
-    } else {
-      const conf = Object.values(config)[i];
+    const matchedKey = Object.keys(config).find(key => ctx.path.includes(key));
+    if (!matchedKey) {
+      ctx.body = { msg: 'No data available', data: [] }
+    } else {
+      const conf = config[matchedKey];
packages/vue-generator/test/testcases/generator/expected/appdemo01/src/http/index.js (1)

18-22: Translate Chinese comment to English for consistency

The codebase appears to use English for documentation. Consider translating this comment to maintain consistency.

-  // axios对于request拦截器是后注册先执行
+  // For axios request interceptors, the last registered one executes first
packages/design-core/src/preview/src/preview/srcFiles/dataSourceMap.js (1)

64-95: Comprehensive data source initialization with dynamic handlers.

This section initializes each data source with appropriate handlers created dynamically from configuration. The use of createFn for each handler ensures flexibility in how data sources can be configured.

The ESLint warning on line 79 has been addressed with a comment, but it would be better to refactor this to avoid the warning altogether.

Consider using an if statement instead of the short-circuit expression to avoid the ESLint warning:

-      // eslint-disable-next-line @typescript-eslint/no-unused-expressions
-      config.errorHandler?.value && createFn(config.errorHandler.value)(error)
+      if (config.errorHandler?.value) {
+        createFn(config.errorHandler.value)(error)
+      }
mockServer/src/assets/json/appinfo.json (7)

4097-4099: Empty Object as Placeholder in snippets Array
In the "materials" section, the "snippets" array now contains an empty object ({}).
Suggestion: If this empty object is meant as a placeholder, consider adding a brief comment or default values so that future maintainers understand its purpose.


4139-4151: Empty String in shortcuts.properties and Consistent Action Naming
Multiple configuration blocks (e.g. here in lines 4139–4151) include an empty string element in the "properties" array and list an action named "bindEevent".
Action Point:
 – Verify whether an empty string is intentional (perhaps a placeholder) or should be removed.
 – Double-check the spelling of "bindEevent"—if it is meant to be "bindEvent", please update it consistently across all configurations.


4261-4268: Reoccurring Empty Values in shortcuts.properties
The block starting at line 4261 also shows an empty string in the "properties" array.
Action Point: Please confirm if these empty entries are required; if not, consider removing them to avoid potential confusion downstream.


5469-5494: shortcuts.properties Includes an Empty String Element
In the block starting at line 5469 the "shortcuts.properties" array includes "text", then an empty string, then "size".
Action Point: Confirm if the empty string is intended as a placeholder; if not, it should be removed.


6000-6006: Empty snippets Array Element
The block for a component under the "group": "component" now defines "snippets": [{}].
Suggestion: If this empty object is only a placeholder, consider adding documentation or default snippet content.


6020-6026: Empty String Entries in shortcuts.properties
The configuration block here has "shortcuts.properties": [""].
Action Point: Check whether this empty string is intentional or an oversight.


6236-6243: Empty Value in shortcuts.properties for a UI Component
The shortcuts array now contains "text", then an empty string, then "size".
Suggestion: Revisit whether the empty string is needed; if it is not, removing it can help clarify the configuration.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c700ed1 and 187cf0a.

⛔ Files ignored due to path filters (1)
  • mockServer/src/database/pages.db is excluded by !**/*.db
📒 Files selected for processing (32)
  • mockServer/package.json (1 hunks)
  • mockServer/src/assets/json/appinfo.json (116 hunks)
  • mockServer/src/assets/json/sources.json (1 hunks)
  • mockServer/src/mock/get/app-center/apps/detail/918.json (1 hunks)
  • mockServer/src/mock/get/app-center/sources/list/918.json (1 hunks)
  • mockServer/src/mock/get/app-center/v1/apps/schema/918.json (2 hunks)
  • mockServer/src/mock/post/app-center/apps/update/918.json (0 hunks)
  • mockServer/src/routes/main-routes.js (3 hunks)
  • mockServer/src/services/app.js (1 hunks)
  • mockServer/src/services/source.js (1 hunks)
  • packages/build/vite-config/src/default-config.js (1 hunks)
  • packages/design-core/package.json (1 hunks)
  • packages/design-core/src/preview/src/preview/Preview.vue (3 hunks)
  • packages/design-core/src/preview/src/preview/generate.js (2 hunks)
  • packages/design-core/src/preview/src/preview/srcFiles.js (2 hunks)
  • packages/design-core/src/preview/src/preview/srcFiles/dataSourceMap.js (1 hunks)
  • packages/design-core/src/preview/src/preview/srcFiles/http.js (1 hunks)
  • packages/plugins/datasource/src/DataSourceGlobalDataHandler.vue (5 hunks)
  • packages/plugins/datasource/src/RemoteDataAdapterForm.vue (1 hunks)
  • packages/plugins/datasource/src/js/datasource.js (3 hunks)
  • packages/plugins/materials/src/composable/useResource.js (2 hunks)
  • packages/utils/src/constants/index.js (1 hunks)
  • packages/vue-generator/src/templates/vue-template/templateFiles/genViteConfig.js (1 hunks)
  • packages/vue-generator/src/templates/vue-template/templateFiles/src/http/index.js (1 hunks)
  • packages/vue-generator/src/templates/vue-template/templateFiles/src/lowcodeConfig/dataSource.js (2 hunks)
  • packages/vue-generator/test/testcases/element-plus-case/expected/appdemo01/package.json (1 hunks)
  • packages/vue-generator/test/testcases/element-plus-case/expected/appdemo01/src/http/index.js (1 hunks)
  • packages/vue-generator/test/testcases/element-plus-case/expected/appdemo01/src/lowcodeConfig/dataSource.js (2 hunks)
  • packages/vue-generator/test/testcases/generator/expected/appdemo01/package.json (1 hunks)
  • packages/vue-generator/test/testcases/generator/expected/appdemo01/src/http/index.js (1 hunks)
  • packages/vue-generator/test/testcases/generator/expected/appdemo01/src/lowcodeConfig/dataSource.js (2 hunks)
  • packages/vue-generator/test/testcases/generator/expected/appdemo01/src/lowcodeConfig/dataSource.json (1 hunks)
💤 Files with no reviewable changes (1)
  • mockServer/src/mock/post/app-center/apps/update/918.json
🚧 Files skipped from review as they are similar to previous changes (18)
  • packages/design-core/package.json
  • packages/utils/src/constants/index.js
  • mockServer/package.json
  • packages/vue-generator/test/testcases/generator/expected/appdemo01/package.json
  • packages/vue-generator/test/testcases/element-plus-case/expected/appdemo01/package.json
  • mockServer/src/services/source.js
  • packages/vue-generator/src/templates/vue-template/templateFiles/genViteConfig.js
  • mockServer/src/services/app.js
  • packages/build/vite-config/src/default-config.js
  • packages/design-core/src/preview/src/preview/srcFiles.js
  • packages/vue-generator/test/testcases/element-plus-case/expected/appdemo01/src/lowcodeConfig/dataSource.js
  • packages/plugins/materials/src/composable/useResource.js
  • packages/plugins/datasource/src/js/datasource.js
  • packages/design-core/src/preview/src/preview/Preview.vue
  • packages/plugins/datasource/src/RemoteDataAdapterForm.vue
  • packages/vue-generator/test/testcases/generator/expected/appdemo01/src/lowcodeConfig/dataSource.json
  • mockServer/src/mock/get/app-center/sources/list/918.json
  • mockServer/src/assets/json/sources.json
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: push-check
🔇 Additional comments (37)
mockServer/src/mock/get/app-center/apps/detail/918.json (3)

72-77: Good addition of proxy configuration for mock API integration.

The proxy configuration properly maps the /mock path to the external mock service with appropriate cross-origin settings. This enables the application to seamlessly integrate with the mock API service during development.


78-81: Well-structured willFetch handler function.

The willFetch function follows a good pattern of passing through the request options unmodified. This creates a useful extension point where request preprocessing can be added later if needed.


86-89: Appropriate error handler implementation.

The errorHandler function properly maintains the Promise rejection chain, which is essential for error propagation and consistent error handling throughout the application.

packages/design-core/src/preview/src/preview/generate.js (2)

15-35: Well-structured data source generator function.

The generateDataSource function properly extracts and restructures the data source configuration, conditionally including handler functions only when they're available. This provides a clean, consistent data structure for the preview functionality.

A few observations:

  1. The function safely handles the case when source is undefined
  2. The list mapping extracts only necessary properties
  3. Handler functions are conditionally added only when present

179-179: Good replacement of direct export with structured generator.

Replacing generateDefaultExport(data.dataSource) with generateDataSource(data.dataSource) enables more sophisticated data source processing, ensuring the exported structure is consistent and contains only the necessary properties.

packages/vue-generator/test/testcases/generator/expected/appdemo01/src/lowcodeConfig/dataSource.js (4)

19-19: Security improvement: Replaced eval with Function constructor.

Replacing eval with the Function constructor is a significant security improvement. While still allowing dynamic code execution, the Function constructor provides better isolation and is generally safer than direct eval.


24-28: Good implementation of global handler functions.

The global handler functions are well-implemented with appropriate fallbacks. The code properly checks for existence before creating functions, and provides sensible defaults when handlers aren't defined.


33-33: Improved Promise consistency in load function.

The changes ensure that the load function consistently returns a Promise in all code paths, which is essential for reliable async operation. Both the "no options" and "shouldFetch returns false" cases now properly resolve with appropriate values.

Also applies to: 37-37


75-82: Enhanced HTTP client configuration with comprehensive handlers.

The HTTP client instantiation has been improved to pass all relevant handlers in a structured object. This makes the code more maintainable and enables more sophisticated request/response processing with both global and specific handlers.

packages/vue-generator/test/testcases/element-plus-case/expected/appdemo01/src/http/index.js (2)

16-16: Improved function signature with comprehensive handler parameters.

The updated function signature accepts a structured object with multiple handlers instead of a single parameter, making the API more flexible and extensible for different handling scenarios.


18-22: Well-structured interceptor chain for request and response processing.

The interceptor setup follows best practices:

  1. Request interceptors are arranged with specific handler first, then global handler (since request interceptors execute in reverse registration order)
  2. Response interceptors provide both specific and global data handling with appropriate error handlers
  3. Clear comment explains the execution order of request interceptors

This structure enables sophisticated request/response processing with proper error handling at each step.

packages/design-core/src/preview/src/preview/srcFiles/http.js (1)

89-97: LGTM: Well-structured HTTP client setup with comprehensive interceptor handling

The HTTP client factory function is well-designed with a comprehensive approach to handling both request and response interceptors. It properly implements the global and local handlers for requests and responses.

packages/vue-generator/src/templates/vue-template/templateFiles/src/http/index.js (1)

16-16: Good API design with destructured parameters

The updated function signature with destructured parameters provides a clear, self-documenting API. This approach makes it easier to understand which handlers are needed and allows for optional parameters.

packages/vue-generator/test/testcases/generator/expected/appdemo01/src/http/index.js (1)

16-16: Good API design with destructured parameters

The updated function signature with destructured parameters provides a clear, self-documenting API. This approach makes it easier to understand which handlers are needed and allows for optional parameters.

packages/design-core/src/preview/src/preview/srcFiles/dataSourceMap.js (3)

15-20: Well-implemented function creation utility.

The createFn function provides a clean way to dynamically create functions from string content. This is a good approach for handling function definitions stored as strings in configuration.


22-26: Good initialization of global handlers.

The global handler functions are properly initialized using the new createFn utility, with appropriate fallbacks when handlers aren't defined in the configuration.


28-62: Well-implemented API proxy functionality.

The load function is well-structured and handles various scenarios appropriately:

  1. Returns static data if remote requests aren't configured
  2. Handles the case when fetching shouldn't occur
  3. Updates the data source status during loading
  4. Properly configures HTTP requests with appropriate parameters
  5. Implements proxy functionality based on window.appInfo configuration

The proxy implementation in lines 46-53 is particularly important as it adds the ability to route API requests through a proxy server, which is essential for the PR's objective of adding API proxy functionality.

mockServer/src/mock/get/app-center/v1/apps/schema/918.json (4)

684-718: Good addition of test proxy API configuration.

The new testProxyApi data source is well-configured with appropriate handlers. This provides a good test case for the proxy functionality implemented in the first file.

The URI path /mock/41534bc9c0e0000/province?apipost_id=1534d5e9f71002 will be correctly routed through the proxy configuration defined later in this file.


724-728: Well-configured proxy settings for mock API.

The proxy configuration is properly set up to route requests with paths starting with "/mock" to "https://mock.apipost.net". The changeOrigin: true setting is important for ensuring requests work correctly across different domains.

This configuration complements the proxy handling in the load function from the first file.


730-736: Improved error handling for API requests.

The updated error handler function now properly returns a rejected promise, ensuring that errors are propagated correctly through the promise chain.

This change improves error handling throughout the application when API requests fail.


803-807: Improved readability with array formatting.

The dataDisk array has been reformatted from a single line to multiple lines, improving readability. This is a good practice for maintaining clean, readable JSON.

mockServer/src/assets/json/appinfo.json (8)

1607-1646: New 'testProxyApi' Entry Added
A new configuration object for the API proxy with "id": 152 (named "testProxyApi") has been introduced. The object correctly defines properties including data, options, willFetch, dataHandler, shouldFetch, and errorHandler.
Action Point: Please verify that the empty implementation of the local "errorHandler" function is intentional. For consistency with the global configuration (which returns a rejected promise on error), you might consider returning a rejected promise here as well.


1791-1801: Addition of dataDisk Array in Page Content
A new "dataDisk" array is added to the "state" under the "page_content" section. The hardcoded values [1, 2, 3] appear to serve as mock data.
Action Point: Confirm that these numbers are the intended placeholder values for testing.


2835-2839: Added Pagination pageSizes Configuration
The pagination configuration now includes a "pageSizes" array (with values [10, 20, 50]) inside the "attrs" object.
Note: This enhancement allows for flexible page size options in the UI. Please verify that any consuming component accepts these values.


3570-3576: New loopArgs Property Introduced
A new property "loopArgs" (with values ["item", "idx"]) has been added along with existing keys such as "value" and "condition".
Action Point: Ensure that the downstream logic correctly uses these loop argument names.


4527-4530: Introduction of a New Shortcut Property: "show-checkbox"
A new shortcut property "show-checkbox" has been added (lines 4527–4529).
Note: This property should be supported by the UI component that consumes the JSON configuration.


4909-4932: Added slots Configuration and isPopper Flag
The configuration now includes a "slots" array (with "reference") and a boolean flag "isPopper": true for a component.
Note: These enhancements appear to enable popper functionality and slot support. Please verify alignment with the consuming logic.


6409-6417: Event Function Information with Null Parameter
The event configuration provided in this block defines "params": [null] for the event handler.
Action Point: Verify if using null as a parameter placeholder is acceptable. In some areas (see hunk 45) a descriptive parameter (e.g. "e") is used—which is preferable.


12966-12974: Improved Event Handler Parameter Naming
Unlike several blocks that use null, this event configuration now passes "e" as a parameter. This is a welcome improvement for clarity.

packages/plugins/datasource/src/DataSourceGlobalDataHandler.vue (4)

6-8: Feature addition for cross-origin proxy configuration looks good!

The new collapse item provides an intuitive UI for users to configure cross-origin proxies, which aligns well with the PR objectives to add API proxy functionality in the data source.


33-34: Good use of constants for default values

Importing DEFAULT_PROXY from constants is a good practice to maintain consistency across the application and avoid hardcoding values.


54-69: Well-structured editor configuration with helpful example

The editor options are well-configured with an appropriate language setting and a clear example that demonstrates the proper format for proxy configuration. The placeholder effectively guides users on how to set up proxies correctly.


108-109: Consider using a proper if statement instead of the logical AND pattern

While you've added an eslint-disable comment, it would be more maintainable to use a proper if statement as recommended in the previous review.

Apply this diff:

-          // eslint-disable-next-line @typescript-eslint/no-unused-expressions
-          value && window.dispatchEvent(new Event('resize'))
+          if (value) {
+            window.dispatchEvent(new Event('resize'))
+          }
packages/vue-generator/src/templates/vue-template/templateFiles/src/lowcodeConfig/dataSource.js (4)

19-19: Security improvement using Function constructor instead of eval

Replacing eval() with new Function() improves security by avoiding the most dangerous aspects of eval. However, be aware that new Function still introduces potential security risks if fnContent comes from untrusted sources.


24-28: Well-structured global handlers with sensible defaults

The implementation of global handlers with appropriate default behaviors ensures consistent data processing across all data sources, which is a good architectural approach.


33-33: Improved promise handling consistency

The changes ensure consistent Promise behavior by:

  1. Applying the global data handler to static data
  2. Always returning a resolved promise with appropriate values

This approach results in more predictable behavior and better error handling throughout the application.

Also applies to: 37-37


76-83: Improved HTTP client configuration with named parameters

Passing an object with named handler properties to useHttp instead of individual parameters makes the code more maintainable and the function signature more flexible. This is a great improvement that will make future additions easier.

feat: add API Proxy in dataSource, add some mock API, add some cases, Fixed ESlint

feat: Fixed JSON Parse
@1degrees 1degrees force-pushed the feat/AddProxyInDataSource branch from 6f8c94e to 22e83a8 Compare March 14, 2025 09:03
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.

Caution

Inline review comments failed to post. This is likely due to GitHub's limits when posting large numbers of comments. If you are seeing this consistently it is likely a permissions issue. Please check "Moderation" -> "Code review limits" under your organization settings.

Actionable comments posted: 1

♻️ Duplicate comments (2)
packages/plugins/datasource/src/DataSourceGlobalDataHandler.vue (2)

92-92: 🛠️ Refactor suggestion

Add error handling for JSON parsing in state update

Similar to the previous comment, add error handling when updating the app schema state with the parsed proxy configuration.

-          useResource().appSchemaState.proxy = JSON.parse(state.proxy || JSON.stringify(DEFAULT_PROXY))
+          try {
+            useResource().appSchemaState.proxy = JSON.parse(state.proxy || JSON.stringify(DEFAULT_PROXY))
+          } catch (e) {
+            console.error('Invalid proxy configuration JSON:', e)
+            useResource().appSchemaState.proxy = DEFAULT_PROXY
+          }

81-81: 🛠️ Refactor suggestion

Add error handling for JSON parsing

The JSON.parse operation could throw an exception if the input is malformed. Add try/catch block to handle potential parsing errors gracefully.

-        proxy: JSON.parse(state.proxy || JSON.stringify(DEFAULT_PROXY)),
+        proxy: (() => {
+          try {
+            return JSON.parse(state.proxy || JSON.stringify(DEFAULT_PROXY))
+          } catch (e) {
+            console.error('Invalid proxy configuration JSON:', e)
+            return DEFAULT_PROXY
+          }
+        })(),
🧹 Nitpick comments (1)
packages/plugins/datasource/src/DataSourceGlobalDataHandler.vue (1)

71-71: Consider validating the proxy configuration structure

It would be helpful to add validation for the proxy configuration structure before saving, ensuring that it follows the expected format with target and other required properties.

+    const validateProxyConfig = (config) => {
+      // Basic validation for proxy configuration
+      if (!config || typeof config !== 'object') return false
+      if (!config.proxy || typeof config.proxy !== 'object') return false
+      
+      for (const path in config.proxy) {
+        const entry = config.proxy[path]
+        if (!entry.target || typeof entry.target !== 'string') return false
+      }
+      
+      return true
+    }

     const state = reactive({
-      proxy: JSON.stringify(proxy || DEFAULT_PROXY, null, 2),
+      proxy: JSON.stringify(proxy || DEFAULT_PROXY, null, 2),
       willFetchValue: willFetch?.value,

And then use this in the save handler:

     const saveGlobalDataHandle = () => {
       const id = getMetaApi(META_SERVICE.GlobalService).getBaseInfo().id

+      // Parse and validate proxy configuration
+      let parsedProxy
+      try {
+        parsedProxy = JSON.parse(state.proxy || JSON.stringify(DEFAULT_PROXY))
+        if (!validateProxyConfig(parsedProxy)) {
+          return confirm({
+            title: '错误',
+            message: '代理配置格式不正确,请检查后重试'
+          })
+        }
+      } catch (e) {
+        console.error('Invalid proxy configuration JSON:', e)
+        return confirm({
+          title: '错误',
+          message: '代理配置JSON格式不正确: ' + e.message
+        })
+      }

       const handler = {
-        proxy: JSON.parse(state.proxy || JSON.stringify(DEFAULT_PROXY)),
+        proxy: parsedProxy,
🛑 Comments failed to post (1)
packages/plugins/datasource/src/DataSourceGlobalDataHandler.vue (1)

33-34: ⚠️ Potential issue

Missing DEFAULT_PROXY import from constants

The code uses DEFAULT_PROXY but it's not included in the import statement.

-const { DEFAULT_INTERCEPTOR } = constants
+const { DEFAULT_INTERCEPTOR, DEFAULT_PROXY } = constants
📝 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.

const { DEFAULT_INTERCEPTOR, DEFAULT_PROXY } = constants

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

♻️ Duplicate comments (5)
mockServer/src/routes/main-routes.js (1)

236-267: ⚠️ Potential issue

Fix the app ID assignment logic in the proxy middleware

The current implementation on line 239 will always use 918 as the app ID regardless of what's in the headers, due to how the logical OR operator works in JavaScript.

Apply this fix:

- const appId = 918 || ctx.headers.proxy_app_id;
+ const appId = ctx.headers.proxy_app_id || 918;

This ensures it first tries to get the app ID from headers and falls back to 918 if not present.

mockServer/src/mock/get/app-center/v1/apps/schema/918.json (1)

730-737: ⚠️ Potential issue

Added request interceptor functions

The willFetch and errorHandler functions provide proper hooks for request processing and error handling. However, there's a typo in the existing function name on line 720-722.

Fix the typo in the function name from "dataHanlder" to "dataHandler":

"dataHandler": {
  "type": "JSFunction",
-  "value": "function dataHanlder(res){\n return res;\n}"
+  "value": "function dataHandler(res){\n return res;\n}"
}
packages/vue-generator/src/templates/vue-template/templateFiles/src/lowcodeConfig/dataSource.js (1)

72-72: ⚠️ Potential issue

Fix missing return statement in errorHandler

The line is flagged by static analysis because it's an expression statement that doesn't affect the flow of the function. The error handler function should return a value or explicitly reject the promise.

-    config.errorHandler?.value && createFn(config.errorHandler.value)(error)
+    if (config.errorHandler?.value) {
+      return createFn(config.errorHandler.value)(error)
+    }
+    return Promise.reject(error)
packages/plugins/datasource/src/DataSourceGlobalDataHandler.vue (2)

81-81: 🛠️ Refactor suggestion

Add error handling for JSON parsing

JSON parsing can throw errors if the input is malformed. Add a try/catch block to handle potential parsing errors gracefully.

-        proxy: JSON.parse(state.proxy || JSON.stringify(DEFAULT_PROXY)),
+        proxy: (() => {
+          try {
+            return JSON.parse(state.proxy || JSON.stringify(DEFAULT_PROXY))
+          } catch (e) {
+            console.error('Invalid proxy configuration JSON:', e)
+            return DEFAULT_PROXY
+          }
+        })(),

92-92: 🛠️ Refactor suggestion

Add error handling for JSON parsing

Similar to the previous comment, add error handling when updating the app schema state with the parsed proxy configuration.

-          useResource().appSchemaState.proxy = JSON.parse(state.proxy || JSON.stringify(DEFAULT_PROXY))
+          try {
+            useResource().appSchemaState.proxy = JSON.parse(state.proxy || JSON.stringify(DEFAULT_PROXY))
+          } catch (e) {
+            console.error('Invalid proxy configuration JSON:', e)
+            useResource().appSchemaState.proxy = DEFAULT_PROXY
+          }
🧹 Nitpick comments (7)
mockServer/src/services/source.js (1)

23-25: Avoid hardcoded file paths and IDs

The method uses hardcoded paths and the ID "918", making it less reusable and harder to maintain.

Consider parameterizing these values or fetching them from a configuration file:

- update(source_global) {
+ update(source_global, appId = '918') {
    const appPath = path.join(__dirname, '../assets/json/appinfo.json')
-   const detailPath = path.join(__dirname, '../mock/get/app-center/apps/detail/918.json')
-   const appSchemaPath = path.join(__dirname, '../mock/get/app-center/v1/apps/schema/918.json')
+   const detailPath = path.join(__dirname, `../mock/get/app-center/apps/detail/${appId}.json`)
+   const appSchemaPath = path.join(__dirname, `../mock/get/app-center/v1/apps/schema/${appId}.json`)
packages/design-core/src/preview/src/preview/generate.js (1)

15-35: Add input validation to prevent runtime errors

The generateDataSource function assumes that list is an array and doesn't validate its existence or structure, which could lead to runtime errors.

 const generateDataSource = (source) => {
   const dataSource = source || {}
   const { dataHandler, errorHandler, willFetch, list } = dataSource
 
   const data = {
-    list: list.map(({ id, name, data }) => ({ id, name, ...data }))
+    list: Array.isArray(list) 
+      ? list.map(({ id, name, data = {} }) => ({ id, name, ...data }))
+      : []
   }
packages/vue-generator/test/testcases/generator/expected/appdemo01/src/lowcodeConfig/dataSource.js (1)

20-20: Fix potential 'this' context issue

The createFn function uses this in its apply call, but arrow functions don't bind their own this. This could lead to unexpected behavior.

 const createFn = (fnContent) => {
   return (...args) => {
     const fn = new Function(`return ${fnContent}`)()
-    return fn.apply(this, args)
+    return fn(...args)
   }
 }
packages/vue-generator/test/testcases/element-plus-case/expected/appdemo01/src/http/index.js (1)

16-22: Add documentation for handler implementations

While the interceptor structure is improved, there's no documentation about how these handlers should be implemented or what their expected signatures are.

Add JSDoc comments to describe the expected function signatures and behaviors for each handler:

+/**
+ * Configure HTTP client with request and response interceptors
+ * @param {Object} options - Configuration options
+ * @param {Function} options.globalWillFetch - Global request interceptor function (req) => req
+ * @param {Function} options.globalDataHandle - Global response handler function (res) => res
+ * @param {Function} options.globalErrorHandler - Global error handler function (err) => Promise.reject(err)
+ * @param {Function} options.willFetch - Request interceptor function (req) => req
+ * @param {Function} options.dataHandler - Response handler function (res) => res
+ * @param {Function} options.errorHandler - Error handler function (err) => Promise.reject(err)
+ * @returns {Object} Configured axios instance
+ */
 export default ({ globalWillFetch, globalDataHandle, globalErrorHandler, willFetch, dataHandler, errorHandler }) => {
mockServer/src/assets/json/appinfo.json (2)

1607-1646: New testProxyApi Configuration Entry Added:
The new configuration entry for "testProxyApi" (with id: 152) is structured correctly with nested settings for data, options, and functions. However, please review the errorHandler function defined here

"errorHandler": {
  "type": "JSFunction",
  "value": "function errorHandler(err) {}"
}

An empty error handler might lead to silent failures. For consistency and robust error propagation (as seen later in the global configuration), consider returning a rejected promise or handling the error appropriately.


1791-30534: UI Component Configuration Consistency Across Multiple Entries:
A large number of modified configuration entries (from roughly line 1791 up to line 30534) update properties for UI components—including arrays for "shortcuts", "contextMenu", "slots", and other attributes. Overall, the structure is maintained; however, please verify the following points:

  • Typo Check: The string "bindEevent" appears repeatedly in various "contextMenu" arrays. Confirm whether this is intentionally named or if it should be corrected to "bindEvent".
  • Placeholders and Empty Strings: Several arrays include empty strings (e.g., "properties": [""]). Ensure that these placeholders are deliberate and that the runtime logic tolerates or interprets them correctly.
  • Action Naming: Some context menu action values (such as "create symbol") recur in multiple entries. Please verify that these values align with the design guidelines and expected actions for the UI components.
🧰 Tools
🪛 Gitleaks (8.21.2)

2748-2748: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


3644-3644: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

packages/plugins/datasource/src/DataSourceGlobalDataHandler.vue (1)

71-71: Add error handling for JSON stringification

Although unlikely to fail, it's a good practice to add error handling around the JSON operations for robustness.

-      proxy: JSON.stringify(proxy || DEFAULT_PROXY, null, 2),
+      proxy: (() => {
+        try {
+          return JSON.stringify(proxy || DEFAULT_PROXY, null, 2)
+        } catch (e) {
+          console.error('Error stringifying proxy configuration:', e)
+          return JSON.stringify(DEFAULT_PROXY, null, 2)
+        }
+      })(),
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6f8c94e and 22e83a8.

⛔ Files ignored due to path filters (1)
  • mockServer/src/database/pages.db is excluded by !**/*.db
📒 Files selected for processing (32)
  • mockServer/package.json (1 hunks)
  • mockServer/src/assets/json/appinfo.json (116 hunks)
  • mockServer/src/assets/json/sources.json (1 hunks)
  • mockServer/src/mock/get/app-center/apps/detail/918.json (1 hunks)
  • mockServer/src/mock/get/app-center/sources/list/918.json (1 hunks)
  • mockServer/src/mock/get/app-center/v1/apps/schema/918.json (2 hunks)
  • mockServer/src/mock/post/app-center/apps/update/918.json (0 hunks)
  • mockServer/src/routes/main-routes.js (3 hunks)
  • mockServer/src/services/app.js (1 hunks)
  • mockServer/src/services/source.js (1 hunks)
  • packages/build/vite-config/src/default-config.js (1 hunks)
  • packages/design-core/package.json (1 hunks)
  • packages/design-core/src/preview/src/preview/Preview.vue (3 hunks)
  • packages/design-core/src/preview/src/preview/generate.js (2 hunks)
  • packages/design-core/src/preview/src/preview/srcFiles.js (2 hunks)
  • packages/design-core/src/preview/src/preview/srcFiles/dataSourceMap.js (1 hunks)
  • packages/design-core/src/preview/src/preview/srcFiles/http.js (1 hunks)
  • packages/plugins/datasource/src/DataSourceGlobalDataHandler.vue (5 hunks)
  • packages/plugins/datasource/src/RemoteDataAdapterForm.vue (1 hunks)
  • packages/plugins/datasource/src/js/datasource.js (3 hunks)
  • packages/plugins/materials/src/composable/useResource.js (2 hunks)
  • packages/utils/src/constants/index.js (1 hunks)
  • packages/vue-generator/src/templates/vue-template/templateFiles/genViteConfig.js (1 hunks)
  • packages/vue-generator/src/templates/vue-template/templateFiles/src/http/index.js (1 hunks)
  • packages/vue-generator/src/templates/vue-template/templateFiles/src/lowcodeConfig/dataSource.js (2 hunks)
  • packages/vue-generator/test/testcases/element-plus-case/expected/appdemo01/package.json (1 hunks)
  • packages/vue-generator/test/testcases/element-plus-case/expected/appdemo01/src/http/index.js (1 hunks)
  • packages/vue-generator/test/testcases/element-plus-case/expected/appdemo01/src/lowcodeConfig/dataSource.js (2 hunks)
  • packages/vue-generator/test/testcases/generator/expected/appdemo01/package.json (1 hunks)
  • packages/vue-generator/test/testcases/generator/expected/appdemo01/src/http/index.js (1 hunks)
  • packages/vue-generator/test/testcases/generator/expected/appdemo01/src/lowcodeConfig/dataSource.js (2 hunks)
  • packages/vue-generator/test/testcases/generator/expected/appdemo01/src/lowcodeConfig/dataSource.json (1 hunks)
💤 Files with no reviewable changes (1)
  • mockServer/src/mock/post/app-center/apps/update/918.json
🚧 Files skipped from review as they are similar to previous changes (18)
  • packages/design-core/package.json
  • packages/utils/src/constants/index.js
  • packages/vue-generator/test/testcases/generator/expected/appdemo01/package.json
  • mockServer/src/services/app.js
  • mockServer/src/mock/get/app-center/apps/detail/918.json
  • packages/vue-generator/test/testcases/element-plus-case/expected/appdemo01/package.json
  • packages/build/vite-config/src/default-config.js
  • packages/plugins/materials/src/composable/useResource.js
  • mockServer/package.json
  • packages/vue-generator/test/testcases/element-plus-case/expected/appdemo01/src/lowcodeConfig/dataSource.js
  • packages/design-core/src/preview/src/preview/Preview.vue
  • packages/plugins/datasource/src/js/datasource.js
  • packages/vue-generator/src/templates/vue-template/templateFiles/genViteConfig.js
  • packages/plugins/datasource/src/RemoteDataAdapterForm.vue
  • packages/design-core/src/preview/src/preview/srcFiles/http.js
  • packages/vue-generator/test/testcases/generator/expected/appdemo01/src/lowcodeConfig/dataSource.json
  • mockServer/src/mock/get/app-center/sources/list/918.json
  • packages/design-core/src/preview/src/preview/srcFiles.js
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: push-check
🔇 Additional comments (27)
packages/design-core/src/preview/src/preview/generate.js (1)

179-179: Approve change from generateDefaultExport to generateDataSource

The change from generateDefaultExport(data.dataSource) to generateDataSource(data.dataSource) provides better handling of data source properties.

packages/vue-generator/test/testcases/generator/expected/appdemo01/src/lowcodeConfig/dataSource.js (4)

19-19: Security improvement: Using Function constructor instead of eval

Replacing potential eval() usage with new Function() is a security improvement as it avoids executing arbitrary code in the global scope.


24-28: Good addition of global handlers

The addition of globalWillFetch and globalErrorHandler provides consistent behavior across all requests and improves error handling.


33-33: Improved promise handling for consistency

The function now consistently returns resolved promises for all code paths, making error handling more predictable.

Also applies to: 37-37


75-82: Enhanced HTTP configuration structure

The updated useHttp function call with a structured object parameter improves clarity and flexibility in configuration.

packages/vue-generator/test/testcases/element-plus-case/expected/appdemo01/src/http/index.js (2)

18-22: Improved interceptor structure with helpful comment

The restructured interceptors with the comment about execution order provide better organization and documentation. The separation of global and local handlers improves flexibility.


16-16:

❓ Verification inconclusive

Major API change to exported function

The exported function signature has been completely changed from accepting a single parameter to accepting an object with multiple parameters. This is a significant change that may break existing code.


🏁 Script executed:

#!/bin/bash
# Verify if there are other files calling this function with the old signature
echo "Searching for imports of http/index.js and usage patterns..."
rg -A 3 "import.*from.*http" --glob "*.js" | grep -v "globalWillFetch" || echo "No usages with old pattern found"

# Look for any places using the old pattern
rg "useHttp\([^{]" --glob "*.js" || echo "No direct calls with old pattern found"

Length of output: 5174


Critical API Change – Confirm Consumers Use New Parameter Object

The exported function in
packages/vue-generator/test/testcases/element-plus-case/expected/appdemo01/src/http/index.js
now accepts an object with named parameters rather than a single parameter. This update is a major API change. Our verification using ripgrep did not reveal any direct calls using the old signature. However, please ensure that all consumers—including external modules and plugins—are updated to pass an object with the appropriate keys:

  • Confirm that all imports (e.g., those in data source configurations and template files) correctly adapt to the new API.
  • Review external usage and update documentation/release notes to highlight this breaking change.
  • Double-check integration tests to ensure no calls rely on the deprecated, single-parameter signature.
packages/vue-generator/src/templates/vue-template/templateFiles/src/http/index.js (1)

16-22: Improved HTTP interceptor implementation with granular control

The function signature has been updated to accept individual handlers for different stages of the HTTP request/response lifecycle, which provides more flexibility and separation of concerns. The structure now properly separates global handlers from specific ones, and clearly orders their execution through the interceptor chain.

Note that in Axios, request interceptors execute in reverse order of registration (last registered runs first), which is correctly documented in the comment on line 18.

mockServer/src/routes/main-routes.js (2)

63-69: Update handler for app data sources properly implemented

This route handler appropriately updates the data source global configuration when provided in the request body. The implementation is clean and focused.


261-265: Well-implemented promise wrapper for proxy middleware

The proxy implementation correctly wraps the callback-based proxy middleware in a Promise to work with the async/await pattern used in the route handler. This is a good practice for handling middleware in an async context.

packages/vue-generator/test/testcases/generator/expected/appdemo01/src/http/index.js (1)

16-22: Improved HTTP interceptor implementation with granular control

The function signature has been updated to accept individual handlers for different stages of the HTTP request/response lifecycle, which provides more flexibility and separation of concerns. The structure now properly separates global handlers from specific ones, and clearly orders their execution through the interceptor chain.

Note that in Axios, request interceptors execute in reverse order of registration (last registered runs first), which is correctly documented in the comment on line 18.

packages/design-core/src/preview/src/preview/srcFiles/dataSourceMap.js (4)

15-20: Well-implemented dynamic function creation utility

The createFn utility elegantly transforms string content into executable functions using Function constructor, allowing for dynamically configurable behaviors. This is particularly useful for a low-code platform where function definitions might come from user configurations or database storage.


28-62: Comprehensive load function with proxy support

The new load function provides a robust implementation for data fetching with several key features:

  1. Static data fallback when no remote options are configured
  2. Early return when fetching is not needed
  3. Proper status tracking for the data source
  4. Handling of custom URLs and parameters
  5. Integration with the proxy mechanism via the /app-proxy/api path

This implementation creates a clean abstraction for data source loading that handles various edge cases appropriately.


79-80: Resolve linter warning by avoiding lone short-circuiting

Line 79 uses a short-circuit operator to call createFn(config.errorHandler.value) if present. While there's an ESLint disable comment, it would be better to follow standard practices.

Replace it with an if-statement:

- // eslint-disable-next-line @typescript-eslint/no-unused-expressions
- config.errorHandler?.value && createFn(config.errorHandler.value)(error)
+ if (config.errorHandler?.value) {
+   createFn(config.errorHandler.value)(error)
+ }

84-91: Well-structured HTTP client initialization

The HTTP client is properly initialized with both global and specific handlers, aligning with the updated HTTP interface. This ensures consistent error handling and data processing throughout the application's HTTP requests.

mockServer/src/assets/json/sources.json (1)

668-701: New proxy API data source added successfully.

This change adds a new API data source entry "testProxyApi" with ID 152 that properly includes all required handlers and configuration. The URI path starts with "/mock", which will be handled by the proxy configuration elsewhere in the codebase.

mockServer/src/mock/get/app-center/v1/apps/schema/918.json (3)

685-718: New API source entry added correctly.

The new "testProxyApi" entry in the dataSource list matches the configuration in sources.json, ensuring consistency across the application.


724-728: Proxy configuration added for external API requests.

The new proxy configuration properly routes "/mock" path requests to the external API host "https://mock.apipost.net" with changeOrigin enabled, which is necessary for proper host header handling.


803-807: Improved code readability for dataDisk array.

The dataDisk array has been reformatted from a single line to a multi-line format for better readability and maintainability.

packages/vue-generator/src/templates/vue-template/templateFiles/src/lowcodeConfig/dataSource.js (4)

19-19: Security enhancement: Replaced eval with Function constructor.

Using the Function constructor is a safer approach than eval for dynamically creating functions from strings, as it provides a more controlled execution environment.


24-28: Improved global handler implementation.

The new global handlers (globalWillFetch and globalErrorHandler) are properly implemented with sensible defaults. The error handler now correctly returns a rejected promise instead of silently failing.


33-33: Consistent promise returns for better predictability.

The load function now consistently returns resolved promises in all code paths, which improves predictability and prevents potential undefined returns.

Also applies to: 37-37


76-83: Enhanced HTTP client configuration with comprehensive handlers.

The HTTP client instantiation has been improved to include both global and local handlers for request processing, data handling, and error management. This structured approach provides better separation of concerns and more flexibility.

packages/plugins/datasource/src/DataSourceGlobalDataHandler.vue (4)

6-8: New proxy configuration UI looks good!

Good addition of the proxy configuration section to the interface. This matches the other configuration sections and provides a dedicated area for users to set up cross-origin proxies.


54-69: Good approach for reactive options and clean UI example

The JSON editor options with a working example is helpful for users. The use of useResource() to extract current schema values is also a good practice.


108-109: Fix expression statement linting issue

The line is flagged by the static analyzer because it's an expression statement without assignment or function call effect.

-          // eslint-disable-next-line @typescript-eslint/no-unused-expressions
-          value && window.dispatchEvent(new Event('resize'))
+          if (value) {
+            window.dispatchEvent(new Event('resize'))
+          }

83-86: Good fallback mechanism for the dataHandler

Using the DEFAULT_INTERCEPTOR.globalDataHandler.value as a fallback ensures the system will have valid handling logic even if the user doesn't provide it.

Comment on lines +22 to +35
update(source_global) {
const appPath = path.join(__dirname, '../assets/json/appinfo.json')
const detailPath = path.join(__dirname, '../mock/get/app-center/apps/detail/918.json')
const appSchemaPath = path.join(__dirname, '../mock/get/app-center/v1/apps/schema/918.json')
const appJson = fs.readJSONSync(appPath)
const detailJson = fs.readJSONSync(detailPath)
const schemaJson = fs.readJSONSync(appSchemaPath)
appJson.app.data_source_global = source_global
detailJson.data.data_source_global = source_global
schemaJson.data.dataSource = {...schemaJson.data.dataSource, ...source_global}
fs.outputJSONSync(appPath, appJson, { spaces: 2 })
fs.outputJSONSync(detailPath, detailJson, { spaces: 2 })
fs.outputJSONSync(appSchemaPath, schemaJson, { spaces: 2 })
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Replace synchronous file operations with async and add error handling

The update method currently uses synchronous file operations (readJSONSync, outputJSONSync) which can block the Node.js event loop. Additionally, there's no error handling for these operations.

- update(source_global) {
+ async update(source_global) {
    const appPath = path.join(__dirname, '../assets/json/appinfo.json')
    const detailPath = path.join(__dirname, '../mock/get/app-center/apps/detail/918.json')
    const appSchemaPath = path.join(__dirname, '../mock/get/app-center/v1/apps/schema/918.json')
-   const appJson = fs.readJSONSync(appPath)
-   const detailJson = fs.readJSONSync(detailPath)
-   const schemaJson = fs.readJSONSync(appSchemaPath)
-   appJson.app.data_source_global = source_global
-   detailJson.data.data_source_global = source_global
-   schemaJson.data.dataSource = {...schemaJson.data.dataSource, ...source_global}
-   fs.outputJSONSync(appPath, appJson, { spaces: 2 })
-   fs.outputJSONSync(detailPath, detailJson, { spaces: 2 })
-   fs.outputJSONSync(appSchemaPath, schemaJson, { spaces: 2 })
+   try {
+     const appJson = await fs.readJSON(appPath)
+     const detailJson = await fs.readJSON(detailPath)
+     const schemaJson = await fs.readJSON(appSchemaPath)
+     
+     appJson.app.data_source_global = source_global
+     detailJson.data.data_source_global = source_global
+     schemaJson.data.dataSource = {...schemaJson.data.dataSource, ...source_global}
+     
+     await fs.outputJSON(appPath, appJson, { spaces: 2 })
+     await fs.outputJSON(detailPath, detailJson, { spaces: 2 })
+     await fs.outputJSON(appSchemaPath, schemaJson, { spaces: 2 })
+     
+     return true
+   } catch (error) {
+     console.error('Error updating source:', error)
+     return false
+   }
  }
📝 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
update(source_global) {
const appPath = path.join(__dirname, '../assets/json/appinfo.json')
const detailPath = path.join(__dirname, '../mock/get/app-center/apps/detail/918.json')
const appSchemaPath = path.join(__dirname, '../mock/get/app-center/v1/apps/schema/918.json')
const appJson = fs.readJSONSync(appPath)
const detailJson = fs.readJSONSync(detailPath)
const schemaJson = fs.readJSONSync(appSchemaPath)
appJson.app.data_source_global = source_global
detailJson.data.data_source_global = source_global
schemaJson.data.dataSource = {...schemaJson.data.dataSource, ...source_global}
fs.outputJSONSync(appPath, appJson, { spaces: 2 })
fs.outputJSONSync(detailPath, detailJson, { spaces: 2 })
fs.outputJSONSync(appSchemaPath, schemaJson, { spaces: 2 })
}
async update(source_global) {
const appPath = path.join(__dirname, '../assets/json/appinfo.json')
const detailPath = path.join(__dirname, '../mock/get/app-center/apps/detail/918.json')
const appSchemaPath = path.join(__dirname, '../mock/get/app-center/v1/apps/schema/918.json')
try {
const appJson = await fs.readJSON(appPath)
const detailJson = await fs.readJSON(detailPath)
const schemaJson = await fs.readJSON(appSchemaPath)
appJson.app.data_source_global = source_global
detailJson.data.data_source_global = source_global
schemaJson.data.dataSource = { ...schemaJson.data.dataSource, ...source_global }
await fs.outputJSON(appPath, appJson, { spaces: 2 })
await fs.outputJSON(detailPath, detailJson, { spaces: 2 })
await fs.outputJSON(appSchemaPath, schemaJson, { spaces: 2 })
return true
} catch (error) {
console.error('Error updating source:', error)
return false
}
}

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

♻️ Duplicate comments (1)
mockServer/src/mock/get/app-center/v1/apps/schema/918.json (1)

720-722: ⚠️ Potential issue

Fix typo in function name

There's a typo in the function name: dataHanlder should be dataHandler. This was noted in a previous review but hasn't been fixed in this PR.

"dataHandler": {
  "type": "JSFunction",
-  "value": "function dataHanlder(res){\n return res;\n}"
+  "value": "function dataHandler(res){\n return res;\n}"
}
🧹 Nitpick comments (2)
mockServer/src/assets/json/appinfo.json (2)

5469-5494: Review of UI Configuration Arrays with Empty Strings:
Multiple sections throughout the file (for example, in "shortcuts.properties" and "invalidity") contain empty string entries. These placeholders may be intentional; however, if they are not required for proper UI behavior, their removal could simplify the configuration. Please review these values across the affected ranges and confirm whether they are needed.

Also applies to: 6020-6043, 6236-6243, 7328-7336, 7987-8010, 9666-9689, 11674-11681, 12154-12179, 13029-13053, 14071-14078, 15675-15693, 16863-16886, 17195-17219, 17487-17511, 17822-17846, 18291-18315


4139-4142: Potential Typo in Context Menu Action "bindEevent":
The string "bindEevent" appears in several context menu action arrays. This may be a typo intended to be "bindEvent". Please verify the naming convention for this action and update it if necessary.

Also applies to: 5480-5486

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 22e83a8 and cfedcc7.

📒 Files selected for processing (7)
  • mockServer/src/assets/json/appinfo.json (116 hunks)
  • mockServer/src/mock/get/app-center/v1/apps/schema/918.json (2 hunks)
  • packages/design-core/src/preview/src/preview/srcFiles.js (2 hunks)
  • packages/plugins/datasource/src/DataSourceGlobalDataHandler.vue (5 hunks)
  • packages/plugins/datasource/src/RemoteDataAdapterForm.vue (1 hunks)
  • packages/plugins/datasource/src/js/datasource.ts (3 hunks)
  • packages/plugins/materials/src/composable/useResource.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • packages/plugins/datasource/src/RemoteDataAdapterForm.vue
  • packages/design-core/src/preview/src/preview/srcFiles.js
  • packages/plugins/datasource/src/DataSourceGlobalDataHandler.vue
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: push-check
🔇 Additional comments (14)
packages/plugins/materials/src/composable/useResource.ts (2)

29-29: Good addition of DEFAULT_PROXY constant

Adding the DEFAULT_PROXY constant from the constants module supports the new proxy configuration functionality, providing a fallback when no proxy configuration is present in the app data.


147-148: Good property name standardization to camelCase

Renaming is_demo to isDemo and global_state to globalState improves naming consistency by following JavaScript's camelCase convention.

packages/plugins/datasource/src/js/datasource.ts (3)

25-25: Improved return type consistency

Changing from returning undefined to Promise.resolve(undefined) ensures consistent Promise return type, making the function more predictable and easier to use with async/await.


37-49: Well-structured proxy handling logic added

The added code properly implements proxy functionality by:

  1. Checking for proxy configuration presence
  2. Determining if the current URL matches a proxy route
  3. Modifying URL with /app-proxy/api prefix
  4. Adding required proxy_app_id header

This implementation aligns with the PR objective of adding an API proxy to the data source.


108-108:

✅ Verification successful

Verify interceptor registration order

Moving the response interceptor registration might affect the order in which interceptors are executed. With axios, response interceptors are executed in order of registration, so this change ensures the globalDataHandle runs after the dataHandler.

This appears to be an intentional change to fix execution order, but let's verify if both interceptors are needed:


🏁 Script executed:

#!/bin/bash
# Check how these interceptors are used elsewhere
echo "Checking usage of interceptors:"
rg "http\.interceptors\.response\.use" --type ts

Length of output: 352


Interceptor Registration Order Verified

The search confirms that the file now registers two response interceptors in sequence:

  • http.interceptors.response.use(dataHandler, errorHandler)
  • http.interceptors.response.use(globalDataHandle, globalErrorHandler)

Since Axios executes response interceptors in the order of registration, having globalDataHandle registered after dataHandler is intentional and ensures that global processing happens after the primary data handling. Both interceptors are active and necessary, so no changes are required.

mockServer/src/mock/get/app-center/v1/apps/schema/918.json (4)

684-718: Good addition of testProxyApi data source

A new data source entry "testProxyApi" is properly configured with:

  • Empty initial data array
  • Correct array type
  • API endpoint for mock province data
  • All required handler functions

This provides a good test case for the proxy functionality implemented in this PR.


724-728: Well-configured proxy settings

The proxy configuration maps /mock to https://mock.apipost.net with changeOrigin: true, which aligns perfectly with the testProxyApi URL pattern. This ensures requests to the mock API are properly routed through the proxy.


730-736: Improved error handling implementation

The errorHandler function now properly returns a rejected promise with the error, which is the correct pattern for error handling in Promise chains.


803-807: Improved code readability

The dataDisk array has been reformatted from a single line to a multi-line format, improving readability and maintainability.

mockServer/src/assets/json/appinfo.json (5)

1791-1801: Added Data Disk Configuration in Page State:
The addition of the "dataDisk" array under the "state" object (with values [1, 2, 3]) appears to be used for the "createVm" route. Please confirm that these numeric values and this configuration align with the intended behavior for mock testing or UI rendering.


2832-2842: Pagination Options Update:
The updated "pageSizes" array providing options [10, 20, 50] will improve pagination flexibility. This change is clear and consistent with common pagination settings.


3570-3577: Inclusion of Loop Arguments:
The addition of the "loopArgs" array with values ["item", "idx"] will likely improve the dynamic handling of looped UI components. The configuration is self-explanatory and appears correct.


17138-17146: Development Asset URLs Check:
The "assets_url" configuration now includes local URLs (e.g., "http://localhost:9090/assets/json/bundle.json" and related script paths). Verify that these URLs are appropriately gated so that they are not inadvertently deployed to production environments.


1610-1644:

❓ Verification inconclusive

New Test Proxy API Configuration:
A new configuration entry for "testProxyApi" (id: 152) has been added with nested settings for data, options, and various function handlers. In particular, the "errorHandler" function is currently defined as an empty function. Please verify that this implementation meets your requirements – for consistency with the global error handling later in the file, you might consider returning a rejected promise (or otherwise raising an error) if an error occurs.


Below is a shell script that extracts the relevant region for the new proxy configuration (including the empty "errorHandler") and also searches for any global error handling references later in the file. This will help verify whether the empty function is consistent with the intended global error-handling behavior.

Please run this script to check:

  • That the "testProxyApi" configuration (id: 152) is correctly added.
  • That the "errorHandler" function is indeed empty.
  • And if a global error handling strategy (e.g., a rejected promise or thrown error) is defined in the expected region afterward.

Once you’ve verified the outputs, we can update the review comment accordingly.


🏁 Script executed:

#!/bin/bash
echo "Extracting testProxyApi configuration from mockServer/src/assets/json/appinfo.json (lines 1600-1644):"
sed -n '1600,1644p' mockServer/src/assets/json/appinfo.json

echo ""
echo "Searching for global error handling configuration (lines 1645-1700):"
sed -n '1645,1700p' mockServer/src/assets/json/appinfo.json | grep -i "error"

Length of output: 1856


Action Required: Verify Consistency of Error Handling Behavior

  • The new "testProxyApi" configuration (id: 152) has been correctly added in mockServer/src/assets/json/appinfo.json with all its nested settings.
  • The "errorHandler" is defined as an empty function (function errorHandler(err) {}).
  • A search for a global error handling configuration (expected after line 1644) did not yield any evidence of a mechanism (e.g., returning a rejected promise or raising an error) that the local "errorHandler" should mimic.
  • Please manually verify whether the absence of a global error handling strategy in the subsequent configuration was intentional. If a global strategy is documented elsewhere or intended to be implemented later, consider updating the "errorHandler" in "testProxyApi" accordingly (for example, by returning a rejected promise or throwing an error).

Comment on lines +140 to +143
appSchemaState.dataHandler = appData.dataSource?.dataHandler || DEFAULT_INTERCEPTOR.globalDataHandler
appSchemaState.errorHandler = appData.dataSource?.errorHandler || DEFAULT_INTERCEPTOR.errorHandler
appSchemaState.proxy = appData.dataSource?.proxy || DEFAULT_PROXY
appSchemaState.dataSource = appData.dataSource?.list || []
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Verify interceptor property name change and ensure consistent proxy handling

The code now uses DEFAULT_INTERCEPTOR.globalDataHandler instead of DEFAULT_INTERCEPTOR.dataHandler and adds proper proxy configuration support with a fallback to DEFAULT_PROXY.

Let's verify that this property name change doesn't cause issues elsewhere in the codebase:


🏁 Script executed:

#!/bin/bash
# Find occurrences of dataHandler and globalDataHandler to ensure consistency
echo "Checking dataHandler vs globalDataHandler usage:"
rg "DEFAULT_INTERCEPTOR\.dataHandler" --type ts
rg "DEFAULT_INTERCEPTOR\.globalDataHandler" --type ts

Length of output: 497


Interceptor Property Naming Consistency and Proxy Setup

The changes in useResource.ts now correctly use DEFAULT_INTERCEPTOR.globalDataHandler and introduce proper proxy fallback with DEFAULT_PROXY. However, our search revealed that in packages/plugins/datasource/src/js/datasource.ts the legacy DEFAULT_INTERCEPTOR.dataHandler is still in use. Please verify whether the datasource implementation should also be updated to use globalDataHandler to ensure consistent interceptor behavior across the codebase.

Comment on lines +14 to +16
import { read, utils, writeFileXLSX } from 'xlsx'
import { useResource } from '@opentiny/tiny-engine-meta-register'
import { isEmptyObject } from '@opentiny/vue-renderless/common/type'
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Added imports but some might be unused

The XLSX-related imports (read, utils, writeFileXLSX) are added, but it's not clear where they're used in the changed code. Verify if these are needed for the proxy functionality or are intended for use elsewhere.

Let's check if these imports are used:


🏁 Script executed:

#!/bin/bash
# Check if the imported functions are used in this file
echo "Checking for usage of XLSX functions in datasource.ts:"
rg "\bread\b|\bwriteFileXLSX\b" packages/plugins/datasource/src/js/datasource.ts

Length of output: 325


XLSX Imports: Usage Verified – Remove Unused utils

  • Confirmed that both read and writeFileXLSX are used in the datasource.ts file.
  • The utils import was not found to be used; please remove it unless you plan to use it in imminent changes.

Comment on lines 30604 to 30626
"data_hash": "ae128e37f6bc378f1b9c21d75bd05551",
"can_associate": true,
"data_source_global": {
"proxy": {
"/mock": {
"target": "https://mock.apipost.net",
"changeOrigin": true
}
},
"willFetch": {
"type": "JSFunction",
"value": "function willFetch(option) {\n return option\n}"
},
"dataHandler": {
"type": "JSFunction",
"value": "function dataHanlder(res){\n return res;\n}"
},
"errorHandler": {
"type": "JSFunction",
"value": "function errorHandler(err) {\n return Promise.reject(err)\n}"
}
}
}
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

Typo in Global Data Handler Function Name:
In the "data_source_global" section, the function intended to be "dataHandler" is defined as

function dataHanlder(res){
 return res;
}

This appears to be a typographical error. Please update the function name to "dataHandler" (unless the misspelling is deliberate for legacy reasons) to prevent potential runtime errors.

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

Successfully merging this pull request may close these issues.

1 participant