Skip to content

feat: platform API and check file#216

Merged
hexqi merged 110 commits intoopentiny:developfrom
lu-yg:develop
May 14, 2025
Merged

feat: platform API and check file#216
hexqi merged 110 commits intoopentiny:developfrom
lu-yg:develop

Conversation

@lu-yg
Copy link
Collaborator

@lu-yg lu-yg commented May 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 REST API endpoints for managing Platform and Platform History records, including create, update, delete, and list operations.
    • Added a new Platform History entity with full CRUD support and database integration.
    • Implemented comprehensive file security and validation utility functions.
  • Improvements

    • Enhanced error handling with new descriptive error codes for file validation scenarios.
    • Updated API responses for Platform operations to provide more informative result objects.
    • Improved JSON serialization for Platform entities.
    • Added file name validation in upload endpoints for components and internationalization entries.
  • Database

    • Modified Platform History table columns to allow null values for certain fields.
    • Updated database schema and indexes for better flexibility and integrity.
  • Bug Fixes

    • Improved file validation and error reporting in component upload workflows.
  • Tests

    • Updated and expanded test coverage to reflect changes in service return types and file validation logic.

lu-yg and others added 30 commits December 26, 2024 00:15
@coderabbitai
Copy link

coderabbitai bot commented May 13, 2025

Walkthrough

This update introduces new REST controllers, service interfaces, implementations, and data mappers for managing PlatformHistory entities, including full CRUD operations and API documentation. The Platform service and controller are refactored to return detailed result wrappers. SQL DDL scripts are updated for column nullability and index adjustments. Utility classes for file validation and new exception enums are added. File upload endpoints in component and i18n controllers now validate file names. Tests are updated accordingly.

Changes

File(s) Change Summary
base/src/main/java/com/tinyengine/it/controller/PlatformController.java
base/src/main/java/com/tinyengine/it/controller/PlatformHistoryController.java
Added new REST controllers for Platform and PlatformHistory entities, exposing CRUD endpoints with API documentation and validation.
base/src/main/java/com/tinyengine/it/service/platform/PlatformService.java
base/src/main/java/com/tinyengine/it/service/platform/impl/PlatformServiceImpl.java
base/src/test/java/com/tinyengine/it/service/platform/impl/PlatformServiceImplTest.java
Refactored PlatformService and its implementation to return Result<Platform> for create, update, and delete methods; updated corresponding tests.
base/src/main/java/com/tinyengine/it/model/entity/Platform.java Added @JsonProperty("published") annotation to the isPublish field.
base/src/main/java/com/tinyengine/it/model/entity/PlatformHistory.java Introduced new entity class for PlatformHistory with schema and documentation annotations.
base/src/main/java/com/tinyengine/it/service/platform/PlatformHistoryService.java
base/src/main/java/com/tinyengine/it/service/platform/impl/PlatformHistoryServiceImpl.java
Added new service interface and implementation for PlatformHistory CRUD operations, including validation and result wrapping.
base/src/main/java/com/tinyengine/it/mapper/PlatformHistoryMapper.java
base/src/main/resources/mappers/PlatformHistoryMapper.xml
Introduced new MyBatis mapper interface and XML for PlatformHistory data access with dynamic SQL.
base/src/main/java/com/tinyengine/it/common/exception/ExceptionEnum.java Added new exception enums for file-related errors.
base/src/main/java/com/tinyengine/it/common/utils/SecurityFileCheckUtil.java Added new utility class for file security and validation checks.
base/src/main/java/com/tinyengine/it/service/material/impl/ComponentServiceImpl.java
base/src/test/java/com/tinyengine/it/service/material/impl/ComponentServiceImplTest.java
Refactored component file upload logic to use file security utility; updated tests to mock file name and type.
base/src/main/java/com/tinyengine/it/controller/ComponentController.java Added file name validation using SecurityFileCheckUtil in component upload endpoints.
base/src/main/java/com/tinyengine/it/controller/I18nEntryController.java
base/src/test/java/com/tinyengine/it/controller/I18nEntryControllerTest.java
Added file name validation in i18n file upload methods; updated tests to mock file names.
app/src/main/resources/sql/h2/create_all_tables_ddl_v1.h2.sql
app/src/main/resources/sql/mysql/create_all_tables_ddl_v1.mysql.sql
Made publish_url, sub_count, and vscode_url columns in t_platform_history nullable.
app/src/main/resources/sql/h2/update_all_tables_ddl.sql
app/src/main/resources/sql/mysql/update_all_tables_ddl.sql
Altered DDL scripts to adjust column nullability and update unique indexes.
base/src/test/java/com/tinyengine/it/service/app/impl/PageServiceImplTest.java Changed assertion in testGetDepth() to expect a successful result with depth value.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant PlatformHistoryController
    participant PlatformHistoryService
    participant PlatformHistoryMapper
    participant Database

    Client->>PlatformHistoryController: HTTP request (CRUD)
    PlatformHistoryController->>PlatformHistoryService: Call service method
    PlatformHistoryService->>PlatformHistoryMapper: DB operation (select/insert/update/delete)
    PlatformHistoryMapper->>Database: Execute SQL
    Database-->>PlatformHistoryMapper: Result
    PlatformHistoryMapper-->>PlatformHistoryService: Entity/List/Count
    PlatformHistoryService-->>PlatformHistoryController: Result<PlatformHistory>
    PlatformHistoryController-->>Client: HTTP response (Result wrapper)
Loading
sequenceDiagram
    participant Client
    participant PlatformController
    participant PlatformService
    participant PlatformMapper
    participant Database

    Client->>PlatformController: HTTP request (CRUD)
    PlatformController->>PlatformService: Call service method
    PlatformService->>PlatformMapper: DB operation (select/insert/update/delete)
    PlatformMapper->>Database: Execute SQL
    Database-->>PlatformMapper: Result
    PlatformMapper-->>PlatformService: Entity/List/Count
    PlatformService-->>PlatformController: Result<Platform>
    PlatformController-->>Client: HTTP response (Result wrapper)
Loading

Poem

In fields of code, new seeds are sown,
With histories tracked and platforms grown.
Controllers leap, mappers hop,
Service layers never stop!
Now files are checked, exceptions neat—
This bunny’s work is quite a feat!
🐇✨

Tip

⚡️ Faster reviews with caching
  • CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.

Enjoy the performance boost—your workflow just got faster.


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 37e06a9 and 2df5550.

📒 Files selected for processing (1)
  • base/src/main/java/com/tinyengine/it/controller/I18nEntryController.java (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • base/src/main/java/com/tinyengine/it/controller/I18nEntryController.java
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 9

🧹 Nitpick comments (26)
app/src/main/resources/sql/h2/update_all_tables_ddl.sql (1)

2-5: Index recreation looks good, but ensure uniqueness consistency

The index recreation on t_component and t_datasource tables appears correct. However, I noticed that the index on t_datasource is named with a "u_" prefix (typically used for unique indexes) but is being created as a non-unique index.

Consider whether this index should be defined as UNIQUE for consistency with the naming convention:

-ALTER TABLE t_datasource ADD INDEX u_idx_datasource (`tenant_id`, `platform_id`, `name`, `app_id`);
+ALTER TABLE t_datasource ADD UNIQUE INDEX u_idx_datasource (`tenant_id`, `platform_id`, `name`, `app_id`);
base/src/main/java/com/tinyengine/it/mapper/PlatformHistoryMapper.java (3)

26-27: Fix the @SInCE date to reflect the current year.

The @SInCE tag shows "2025-05-09" which appears to be a future date. This should be updated to the current year or when this interface was actually introduced.

- * @since 2025-05-09
+ * @since 2023-05-09

39-42: Correct the return type in Javadoc comment.

The Javadoc comment incorrectly references "the platform" as the return type instead of "the platform history".

- * @return the platform
+ * @return the platform history

42-43: Add @param annotation for consistency.

The parameter annotation @param("id") is used in deletePlatformHistoryById but missing here. For consistency across the mapper, it should be added.

-PlatformHistory queryPlatformHistoryById(Integer id);
+PlatformHistory queryPlatformHistoryById(@Param("id") Integer id);
base/src/main/java/com/tinyengine/it/model/entity/PlatformHistory.java (3)

25-26: Fix the @SInCE date to reflect the current year.

The @SInCE tag shows "2025-05-09" which appears to be a future date. This should be updated to the current year or when this class was actually introduced.

- * @since 2025-05-09
+ * @since 2023-05-09

59-61: Fix inconsistent spacing in materialVersion declaration.

There are two spaces between String and materialVersion, which is inconsistent with the formatting in the rest of the file.

-    private String  materialVersion;
+    private String materialVersion;

38-40: Consider adding validation annotations for URLs.

The publishUrl field should have validation to ensure it contains a valid URL format, especially as it will be used to access static resources.

+import javax.validation.constraints.Pattern;
+
 @Schema(name = "publishUrl", description = "设计器静态资源托管地址")
+@Pattern(regexp = "^(https?|ftp)://[^\\s/$.?#].[^\\s]*$", message = "Invalid URL format")
 private String publishUrl;
base/src/main/java/com/tinyengine/it/service/platform/PlatformHistoryService.java (4)

24-25: Fix the @SInCE date to reflect the current year.

The @SInCE tag shows "2025-05-09" which appears to be a future date. This should be updated to the current year or when this interface was actually introduced.

- * @since 2025-05-09
+ * @since 2023-05-09

32-48: Consider consistent use of Result wrapper for all methods.

The service methods have inconsistent return types - some methods return direct entities or collections, while others return a Result wrapper. For consistency with the other modified methods in PlatformServiceImpl, consider wrapping all returns in Result.

-List<PlatformHistory> queryAllPlatformHistory();
+Result<List<PlatformHistory>> queryAllPlatformHistory();

-PlatformHistory queryPlatformHistoryById(@Param("id") Integer id);
+Result<PlatformHistory> queryPlatformHistoryById(@Param("id") Integer id);

-List<PlatformHistory> queryPlatformHistoryByCondition(PlatformHistory platformHistory);
+Result<List<PlatformHistory>> queryPlatformHistoryByCondition(PlatformHistory platformHistory);

40-41: Remove @param annotation at service interface level.

The @param annotation is typically used for MyBatis mappers, not service interfaces. It has no effect at this level and should be removed.

-PlatformHistory queryPlatformHistoryById(@Param("id") Integer id);
+PlatformHistory queryPlatformHistoryById(Integer id);

56-57: Remove @param annotation at service interface level.

The @param annotation is typically used for MyBatis mappers, not service interfaces. It has no effect at this level and should be removed.

-Result<PlatformHistory> deletePlatformHistoryById(@Param("id") Integer id);
+Result<PlatformHistory> deletePlatformHistoryById(Integer id);
base/src/main/java/com/tinyengine/it/service/platform/impl/PlatformServiceImpl.java (1)

114-120: Consider adding validation in createPlatform method.

While the implementation correctly validates the creation result, consider adding additional validation:

  1. Check for required fields before attempting creation
  2. Validate that the entity doesn't already exist to prevent duplicates
 public Result<Platform> createPlatform(Platform platform) {
+    // Validate required fields
+    if (platform.getName() == null || platform.getName().trim().isEmpty()) {
+        return Result.failed(ExceptionEnum.CM003);
+    }
+    
+    // Check for duplicate
+    Platform existing = new Platform();
+    existing.setName(platform.getName());
+    List<Platform> existingPlatforms = platformMapper.queryPlatformByCondition(existing);
+    if (!existingPlatforms.isEmpty()) {
+        return Result.failed(ExceptionEnum.CM009);
+    }
+    
     int createResult = platformMapper.createPlatform(platform);
     if (createResult != 1) {
         return Result.failed(ExceptionEnum.CM008);
     }
     return Result.success(platform);
 }
base/src/main/java/com/tinyengine/it/service/platform/impl/PlatformHistorySrviceImpl.java (1)

53-56: Consider adding null check for ID parameter.

The method doesn't validate the input parameter. Adding a null check would prevent potential NullPointerExceptions at the database layer.

@Override
public PlatformHistory queryPlatformHistoryById(Integer id) {
+    if (id == null) {
+        return null;
+    }
    return platformHistoryMapper.queryPlatformHistoryById(id);
}
base/src/main/resources/mappers/PlatformHistoryMapper.xml (3)

40-42: Remove string check for numeric field subCount.

The subCount field is likely numeric, but the condition checks both for null and empty string, which is not appropriate for a numeric field.

-<if test="subCount!=null and subCount!=''">
+<if test="subCount!=null">
    AND sub_count = #{subCount}
</if>

98-100: Remove string check for numeric field in SET clause.

Similar to the WHERE condition, the subCount field SET clause should not check for empty string.

-<if test="subCount!=null and subCount!=''">
+<if test="subCount!=null">
    sub_count = #{subCount},
</if>

197-238: Consider simplifying INSERT statement formatting.

While functionally correct, the INSERT statement has each column and value on a separate line, making it unnecessarily verbose. Consider a more compact format.

base/src/main/java/com/tinyengine/it/controller/PlatformController.java (2)

134-138: Use PUT HTTP method for update operations and add validation.

Consider using PUT instead of POST for update operations to better follow RESTful conventions. Also, add @Valid annotation to ensure the request body is validated.

@SystemControllerLog(description = "修改单个Platform信息")
-@PostMapping("/platform/update/{id}")
+@PutMapping("/platform/{id}")
-public Result<Platform> updatePlatform(@PathVariable Integer id, @RequestBody Platform platform) {
+public Result<Platform> updatePlatform(@PathVariable Integer id, @Valid @RequestBody Platform platform) {
    platform.setId(id);
    return platformService.updatePlatformById(platform);
}

37-46: Make class-level Javadoc consistent with actual implementation.

The class-level Javadoc says "设计器api" (Designer API) but the @tag annotation says "设计器" (Designer). Consider making them consistent.

/**
- * 设计器api
+ * 设计器
 *
 * @since 2024-10-20
 */
@Validated
@RestController
@RequestMapping("/platform-center/api")
@Tag(name = "设计器")
public class PlatformController {
base/src/main/java/com/tinyengine/it/controller/PlatformHistoryController.java (3)

37-46: Fix inconsistency between Javadoc and @tag annotation.

The class-level Javadoc says "设计器api" (Designer API) but the @tag annotation says "设计器历史" (Designer History). Make them consistent.

/**
- * 设计器api
+ * 设计器历史
 *
 * @since 2024-10-20
 */
@Validated
@RestController
@RequestMapping("/platform-center/api")
@Tag(name = "设计器历史")
public class PlatformHistoryController {

134-138: Use PUT HTTP method for update operations and add validation.

Similar to the PlatformController, consider using PUT instead of POST for update operations and add @Valid annotation for request validation.

@SystemControllerLog(description = "修改单个PlatformHistory信息")
-@PostMapping("/platform-history/update/{id}")
+@PutMapping("/platform-history/{id}")
-public Result<PlatformHistory> updatePlatformHistory(@PathVariable Integer id, @RequestBody PlatformHistory platformHistory) {
+public Result<PlatformHistory> updatePlatformHistory(@PathVariable Integer id, @Valid @RequestBody PlatformHistory platformHistory) {
    platformHistory.setId(id);
    return platformHistoryService.updatePlatformHistoryById(platformHistory);
}

127-128: Fix parameter description in Swagger annotation.

In the update operation, the parameter description refers to "appId" but should refer to "id" (or "platformHistoryId"). Also, the second parameter is named "PlatformHistory" which should be lowercase "platformHistory".

@Operation(summary = "修改单个PlatformHistory信息", description = "修改单个PlatformHistory信息", parameters = {
-            @Parameter(name = "id", description = "appId"),
-            @Parameter(name = "PlatformHistory", description = "入参对象")}, responses = {
+            @Parameter(name = "id", description = "platformHistoryId"),
+            @Parameter(name = "platformHistory", description = "入参对象")}, responses = {
base/src/test/java/com/tinyengine/it/service/material/impl/ComponentServiceImplTest.java (1)

137-138: Test updated to support file validation, but lacks failure cases.

The test now correctly mocks file name and content type to pass the new validation requirements, but only tests the "happy path" with valid inputs. Consider adding additional tests for invalid file names and content types to verify proper error handling.

@Test
void testReadFileAndBulkCreateInvalidFileType() {
+    // Setup
+    MultipartFile file = mock(MultipartFile.class);
+    when(file.getOriginalFilename()).thenReturn("example.txt");
+    when(file.getContentType()).thenReturn("text/plain");
+    
+    // Execute
+    Result<FileResult> result = componentServiceImpl.readFileAndBulkCreate(file);
+    
+    // Verify
+    Assertions.assertFalse(result.isSuccess());
+    Assertions.assertEquals(ExceptionEnum.CM325.getResultCode(), result.getCode());
}
base/src/main/java/com/tinyengine/it/service/material/impl/ComponentServiceImpl.java (1)

388-398: Simplify the checkFile method to remove redundant boolean and return.

The current implementation creates a temporary boolean variable before returning it, which is unnecessary.

public boolean checkFile(MultipartFile file) {
    SecurityFileCheckUtil.validFileName(file.getOriginalFilename());

    Map<String, String> fileTypeMap = new HashMap<>();
    fileTypeMap.put(".json", "application/json");
-    boolean isCheckFileType = SecurityFileCheckUtil.checkFileType(file, fileTypeMap);
-    if (!isCheckFileType) {
-        return false;
-    }
-    return true;
+    return SecurityFileCheckUtil.checkFileType(file, fileTypeMap);
}
base/src/main/java/com/tinyengine/it/common/utils/SecurityFileCheckUtil.java (3)

60-94: Improve file type validation to handle null filenames gracefully.

The method handles null files with a check at the start, but doesn't handle null originalFileName within the loop, which could cause NullPointerException. Also, the method implementations have redundant code.

public static boolean checkFileType(MultipartFile file, Map<String, String> fileTypeMap) {
    if (Objects.isNull(file) || fileTypeMap.isEmpty()) {
        throw new ServiceException(ExceptionEnum.CM307.getResultCode(), ExceptionEnum.CM307.getResultMsg());
    }
    String originalFileName = file.getOriginalFilename();
+    if (ObjectUtil.isEmpty(originalFileName)) {
+        return false;
+    }
    for (Map.Entry<String, String> entry : fileTypeMap.entrySet()) {
        if (originalFileName.endsWith(entry.getKey())) {
            return checkFileType(file, entry.getKey(), entry.getValue());
        }
    }
    return false;
}

public static boolean checkFileType(MultipartFile file, String fileNameEnd, String fileType) {
    String originalFileName = file.getOriginalFilename();
    String contentType = file.getContentType();
    if (ObjectUtil.isEmpty(originalFileName) || ObjectUtil.isEmpty(contentType)) {
        return false;
    }
-    if (!originalFileName.endsWith(fileNameEnd)) {
-        return false;
-    }
-    if (!contentType.equalsIgnoreCase(fileType)) {
-        return false;
-    }
-    return true;
+    return originalFileName.endsWith(fileNameEnd) && contentType.equalsIgnoreCase(fileType);
}

139-170: Enhance file path validation for cross-platform compatibility.

The filePathIsValid method uses OS-specific checks but could benefit from using Java's Path API for better cross-platform support. Also, the comments are in Chinese, which could be translated to English for better maintainability in international teams.

/**
 * Verify file path.
 *
 * @param fileName the fileName
 * @return true or false
 */
public static boolean filePathIsValid(String fileName) {
    if (fileName == null || fileName.trim().isEmpty()) {
        return false;
    }

-    // 获取当前操作系统的名称
+    // Get current operating system name
    String os = System.getProperty("os.name").toLowerCase();

-    // 定义通用的非法字符
+    // Define common illegal characters
    String illegalChars = "";

    if (os.contains("win")) {
-        // 针对Windows的非法字符
+        // Windows illegal characters
        illegalChars = "[<>:\"/\\|?*]";
    } else if (os.contains("nix") || os.contains("nux") || os.contains("mac")) {
-        // 针对Linux和macOS的非法字符(一般来说,Linux和macOS对文件名的限制较少,但有一些常见的非法字符)
-        illegalChars = "[/]"; // Linux和macOS的路径不能包含斜杠 '/'
+        // Linux and macOS illegal characters (fewer restrictions than Windows but some common ones)
+        illegalChars = "[/]"; // Linux and macOS paths cannot contain '/' in file names
    }
-    // 检查路径中是否包含非法字符
+    // Check if path contains illegal characters
    if (fileName.matches(".*" + illegalChars + ".*")) {
        return false;
    }
-    // 检查路径是否超过文件系统允许的最大长度(例如,Windows上的路径限制通常为260个字符)
+    // Check if path exceeds maximum length allowed by file system (e.g., Windows typically has 260 character limit)
    if (fileName.length() > 260) {
        return false;
    }

-    // 检查路径中是否包含空格或其他特殊字符,视需要进行定制
-    // 如果需要你也可以根据不同操作系统做不同的检查
+    // Check for additional special characters if needed
+    // Additional OS-specific checks can be added here

    return true;
}

172-175: Use Java's Path API for better file name extraction.

The current implementation uses File to extract the file name, which can have platform-specific behavior. Using Path would be more reliable.

private static String getFileName(String filePath) {
-    File file = new File(filePath);
-    return file.getName();
+    return Paths.get(filePath).getFileName().toString();
}

Don't forget to add the import:

import java.nio.file.Paths;
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4847dcf and 091ed5e.

📒 Files selected for processing (20)
  • app/src/main/resources/sql/h2/create_all_tables_ddl_v1.h2.sql (1 hunks)
  • app/src/main/resources/sql/h2/update_all_tables_ddl.sql (1 hunks)
  • app/src/main/resources/sql/mysql/create_all_tables_ddl_v1.mysql.sql (1 hunks)
  • app/src/main/resources/sql/mysql/update_all_tables_ddl.sql (1 hunks)
  • base/src/main/java/com/tinyengine/it/common/exception/ExceptionEnum.java (1 hunks)
  • base/src/main/java/com/tinyengine/it/common/utils/SecurityFileCheckUtil.java (1 hunks)
  • base/src/main/java/com/tinyengine/it/controller/PlatformController.java (1 hunks)
  • base/src/main/java/com/tinyengine/it/controller/PlatformHistoryController.java (1 hunks)
  • base/src/main/java/com/tinyengine/it/mapper/PlatformHistoryMapper.java (1 hunks)
  • base/src/main/java/com/tinyengine/it/model/entity/Platform.java (2 hunks)
  • base/src/main/java/com/tinyengine/it/model/entity/PlatformHistory.java (1 hunks)
  • base/src/main/java/com/tinyengine/it/service/material/impl/ComponentServiceImpl.java (4 hunks)
  • base/src/main/java/com/tinyengine/it/service/platform/PlatformHistoryService.java (1 hunks)
  • base/src/main/java/com/tinyengine/it/service/platform/PlatformService.java (2 hunks)
  • base/src/main/java/com/tinyengine/it/service/platform/impl/PlatformHistorySrviceImpl.java (1 hunks)
  • base/src/main/java/com/tinyengine/it/service/platform/impl/PlatformServiceImpl.java (2 hunks)
  • base/src/main/resources/mappers/PlatformHistoryMapper.xml (1 hunks)
  • base/src/test/java/com/tinyengine/it/service/app/impl/PageServiceImplTest.java (1 hunks)
  • base/src/test/java/com/tinyengine/it/service/material/impl/ComponentServiceImplTest.java (1 hunks)
  • base/src/test/java/com/tinyengine/it/service/platform/impl/PlatformServiceImplTest.java (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (3)
base/src/main/java/com/tinyengine/it/service/material/impl/ComponentServiceImpl.java (1)
base/src/main/java/com/tinyengine/it/common/utils/SecurityFileCheckUtil.java (1)
  • SecurityFileCheckUtil (30-178)
base/src/main/java/com/tinyengine/it/model/entity/PlatformHistory.java (1)
base/src/main/java/com/tinyengine/it/model/entity/Platform.java (1)
  • Getter (37-104)
base/src/main/java/com/tinyengine/it/service/platform/impl/PlatformHistorySrviceImpl.java (1)
base/src/main/java/com/tinyengine/it/service/platform/impl/PlatformServiceImpl.java (1)
  • Service (34-121)
🔇 Additional comments (39)
base/src/main/java/com/tinyengine/it/model/entity/Platform.java (1)

46-47: Proper JSON property naming improves API consistency.

Adding the @JsonProperty("published") annotation ensures that the boolean field is consistently serialized as "published" in JSON responses, which follows standard JSON naming conventions rather than the Java bean-style "isPublish" property name.

base/src/test/java/com/tinyengine/it/service/app/impl/PageServiceImplTest.java (1)

280-281: Test updated to reflect new success response pattern.

This test has been updated to align with a service layer change where methods now return Result<T> wrappers with successful responses containing actual data instead of returning error responses.

app/src/main/resources/sql/h2/create_all_tables_ddl_v1.h2.sql (2)

44-44: Making publish_url nullable allows more flexible platform history records.

This change removes the not null constraint from the publish_url column, allowing platform history records to be created without requiring a publish URL.


48-48: Making sub_count nullable increases flexibility of the schema.

This change removes the not null constraint from the sub_count column, allowing platform history records to be created without requiring a subscription count.

app/src/main/resources/sql/mysql/update_all_tables_ddl.sql (3)

1-2: Updated component index to include library_id.

This change modifies the index on the t_component table to include the library_id column, which may improve query performance when filtering components by library.


4-5: Datasource index now includes app_id for more granular uniqueness.

The unique index for datasources now includes app_id, allowing datasources with the same name to exist within different apps in the same platform and tenant.


7-8: Platform history column constraints aligned with H2 schema.

Making sub_count and publish_url nullable in MySQL aligns with the same changes in the H2 schema, ensuring consistency between the two database environments.

app/src/main/resources/sql/h2/update_all_tables_ddl.sql (1)

7-8: Schema changes align with PlatformHistory entity requirements

The modifications to make the sub_count and publish_url columns nullable in the t_platform_history table align with the introduction of the PlatformHistory entity support. This ensures flexibility in data storage.

app/src/main/resources/sql/mysql/create_all_tables_ddl_v1.mysql.sql (1)

44-48: Consistent nullable changes across database platforms

The changes to make publish_url, vscode_url, and sub_count columns nullable in the MySQL DDL are consistent with the H2 DDL changes. This ensures proper database compatibility across different platforms.

base/src/test/java/com/tinyengine/it/service/platform/impl/PlatformServiceImplTest.java (4)

17-17: Good addition of Result import

The addition of the Result import supports the service refactoring to use Result wrapper for platform operations.


75-84: Test properly reflects service method signature change

The test has been appropriately updated to reflect the change in return type from Integer to Result<Platform>. The mock setup now includes retrieving the platform by ID, which allows testing of the full operation flow.


86-95: Test properly updated for updatePlatformById method

The test now correctly mocks the platform retrieval after update and verifies the result contains the expected platform data. This ensures the service's behavior is properly tested.


97-104: Validation on Platform creation test

The test for createPlatform now correctly asserts that the Result object contains the original platform object. However, unlike the other methods, there's no mock for retrieving the platform after creation.

Consider whether this approach is consistent with the implementation:

  • If the service returns the input platform: test is correct
  • If the service retrieves the platform after creation: consider adding a mock for platform retrieval
base/src/main/java/com/tinyengine/it/service/platform/PlatformService.java (4)

15-15: Appropriate Result import addition

The import of the Result class is correctly added to support the updated method signatures.


51-57: Method signature update improves error handling

Changing the return type from Integer to Result<Platform> for deletePlatformById improves error handling and provides more context in the response. This is a good practice for REST APIs.


59-65: Improved return type for update operation

The updatePlatformById method now returns Result<Platform> instead of Integer, which allows returning the updated entity and providing better error handling. This is consistent with REST API best practices.


67-73: Enhanced create method return type

Changing the return type of createPlatform to Result<Platform> follows the same pattern as the other methods, providing consistent API design and better error handling.

base/src/main/java/com/tinyengine/it/mapper/PlatformHistoryMapper.java (1)

28-74: The mapper interface is well-structured with complete CRUD operations.

The mapper interface correctly extends BaseMapper and provides all necessary database operations for the PlatformHistory entity with appropriate method signatures and return types.

base/src/main/java/com/tinyengine/it/model/entity/PlatformHistory.java (1)

31-63: Entity class is well-structured with appropriate annotations.

The PlatformHistory class correctly extends BaseEntity with Lombok annotations for reducing boilerplate code and Swagger annotations for API documentation. The field mapping appears to correctly represent the database table structure.

base/src/main/java/com/tinyengine/it/service/platform/PlatformHistoryService.java (1)

26-72: Service interface provides complete CRUD operations with Result wrappers for modifications.

The service interface covers all necessary operations for PlatformHistory entities with appropriate method signatures and consistent use of Result wrappers for operations that modify data.

base/src/main/java/com/tinyengine/it/service/platform/impl/PlatformServiceImpl.java (3)

79-89: Good implementation of deletePlatformById with proper error handling.

The implementation correctly:

  1. Checks if the platform exists before attempting deletion
  2. Returns success if the platform doesn't exist (idempotent deletion)
  3. Validates the delete operation result
  4. Returns the deleted entity on success for reference

This is a more robust implementation than the previous version.


98-105: Implementation of updatePlatformById provides proper validation and returns updated entity.

The code correctly:

  1. Validates the update operation result
  2. Retrieves the updated entity to return fresh data
  3. Returns a failure result with appropriate error code if update fails

This implementation follows good practices for entity updating.


15-17: The refactoring to use Result wrapper improves consistency and error handling.

The addition of Result wrapper for CRUD operations provides a more consistent approach to error handling and response formatting, which aligns with the new PlatformHistoryService interface.

base/src/main/java/com/tinyengine/it/service/platform/impl/PlatformHistorySrviceImpl.java (3)

42-45: LGTM: Query method implementation is correct.

The implementation correctly delegates to the mapper layer.


64-67: LGTM: Condition-based query implementation is correct.

The implementation correctly delegates to the mapper layer for conditional queries.


75-86: LGTM: Delete operation handles edge cases properly.

The method correctly:

  1. Checks if the record exists before deletion
  2. Returns success if the record doesn't exist (idempotent behavior)
  3. Validates the deletion result
  4. Returns appropriate error handling via Result wrapper
base/src/main/resources/mappers/PlatformHistoryMapper.xml (4)

161-169: LGTM: Query by ID implementation is correct.

The mapper correctly queries the entity by its primary key.


171-178: LGTM: Query by condition uses dynamic SQL appropriately.

The mapper correctly implements dynamic SQL for flexible querying based on conditional parameters.


180-185: LGTM: Delete implementation is correct.

The delete query is properly constructed with the correct table name and WHERE clause.


187-195: LGTM: Update implementation uses dynamic SQL appropriately.

The update operation correctly:

  1. Uses dynamic SQL to update only non-null fields
  2. Has proper WHERE clause condition
base/src/main/java/com/tinyengine/it/controller/PlatformController.java (3)

114-117: LGTM: Create operation implementation is correct.

The create endpoint correctly:

  1. Validates the input using @Valid
  2. Delegates to the service layer
  3. Returns the Result from the service

90-94: LGTM: Get by ID operation implementation is correct.

The endpoint correctly retrieves the entity by ID and wraps it in a Result.


66-70: LGTM: List all operation implementation is correct.

The endpoint correctly retrieves all entities and wraps the result.

base/src/main/java/com/tinyengine/it/controller/PlatformHistoryController.java (3)

66-70: LGTM: List all operation implementation is correct.

The endpoint properly delegates to the service layer and wraps the result.


90-94: LGTM: Get by ID implementation is correct.

The endpoint correctly retrieves the entity by ID and wraps it in a Result.


114-117: LGTM: Create operation implementation is correct.

The create endpoint appropriately:

  1. Validates the input with @Valid
  2. Delegates to the service layer
  3. Returns the Result from the service
base/src/main/java/com/tinyengine/it/common/exception/ExceptionEnum.java (1)

238-253: Good addition of file validation error codes.

The new exception enum constants (CM323, CM324, CM325) clearly define specific error cases for file validation, which is a good practice for providing meaningful error messages to users. These codes align well with the file validation logic in the new SecurityFileCheckUtil class.

base/src/main/java/com/tinyengine/it/service/material/impl/ComponentServiceImpl.java (1)

325-328: Minor formatting improvement for null check.

The spacing in the null check has been improved for consistency.

base/src/main/java/com/tinyengine/it/common/utils/SecurityFileCheckUtil.java (1)

101-115:

Details

❓ Verification inconclusive

Consider consolidating error handling in validFileName method.

The validFileName method throws different exceptions based on different validation failures, but all are related to invalid file name. Consider a more unified approach or at least provide more specific error messages.

The current implementation throws multiple different exception codes for related file name validation issues. Is this intentional as part of a layered validation approach, or should the error handling be more consolidated?


🏁 Script executed:

#!/bin/bash
# Check if the same exception codes are used consistently across the codebase

echo "Looking for usages of CM323 (file name length error):"
rg -A 1 "CM323" --type java

echo "Looking for usages of CM324 (invalid file name error):"
rg -A 1 "CM324" --type java 

echo "Looking for how these errors are handled in the UI/controllers:"
rg -A 5 "validFileName" --type java

Length of output: 3362


Confirm error code granularity in validFileName
validFileName (lines 101–115 in SecurityFileCheckUtil.java) currently throws distinct ServiceExceptions for each failure:

  • CM320 for empty/blank name
  • CM323 for length violations (1–100 chars, alphanumeric start)
  • CM324 for invalid characters or paths

These separate codes enable more precise user feedback. If you’d rather simplify to a single error, consider consolidating; otherwise, the granular approach is appropriate. Please confirm your intended error-handling strategy.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

♻️ Duplicate comments (2)
base/src/main/java/com/tinyengine/it/controller/PlatformController.java (2)

158-162: Use DELETE HTTP method for deletion operations.

Using GET for deletion operations violates RESTful API conventions. Consider using the DELETE HTTP method instead.

@SystemControllerLog(description = "删除platform信息,与js同路由")
-@GetMapping("/platform/delete/{id}")
+@DeleteMapping("/platform/{id}")
public Result<Platform> delete(@PathVariable Integer id) {
    return platformService.deletePlatformById(id);
}

176-177: 🛠️ Refactor suggestion

Use consistent RESTful endpoint patterns.

The deletion endpoint uses "/platform/delete/{id}" which is not fully RESTful. Consider simplifying to "/platform/{id}" to follow REST resource naming conventions.

-@DeleteMapping("/platform/delete/{id}")
+@DeleteMapping("/platform/{id}")
🧹 Nitpick comments (11)
base/src/main/java/com/tinyengine/it/service/platform/impl/PlatformHistoryServiceImpl.java (3)

26-30: Fix the Javadoc comments.

There are two issues with the Javadoc:

  1. This is an implementation class, not an interface, yet the description says "The interface platform history service".
  2. The @since tag shows a future date (2025-05-09).
/**
- * The interface platform history service.
+ * Implementation of the platform history service.
 *
- * @since 2025-05-09
+ * @since 2023-05-09
 */

95-105: Consider maintaining consistency with PlatformServiceImpl.

In PlatformServiceImpl, the updated entity is fetched directly through the mapper, while here you're using this.queryPlatformHistoryById(). Both approaches work, but maintaining consistency across similar service implementations is preferable.

- PlatformHistory platformHistoryResult = this.queryPlatformHistoryById(platformHistory.getId());
+ PlatformHistory platformHistoryResult = platformHistoryMapper.queryPlatformHistoryById(platformHistory.getId());

114-133: Consider using specific error codes for different validation failures.

Currently, all validation failures return the same error code (ExceptionEnum.CM002), which might make debugging harder. Consider using different error codes for different validation failures, or at least including the field name in the error message.

base/src/main/java/com/tinyengine/it/controller/PlatformController.java (5)

135-136: Use PUT method for complete resource updates.

While POST works for updates, PUT is more appropriate for complete resource replacement in RESTful APIs. Also, consider simplifying the path.

-@PostMapping("/platform/update/{id}")
+@PutMapping("/platform/{id}")

115-116: Simplify creation endpoint path.

For a more RESTful API design, the creation endpoint should use the collection path without verbs.

-@PostMapping("/platform/create")
+@PostMapping("/platform")

51-52: Use constructor injection instead of field injection.

Constructor injection makes dependencies explicit and improves testability. Consider refactoring to use constructor injection instead of field injection with @Autowired.

-@Autowired
private PlatformService platformService;

+private final PlatformService platformService;
+
+@Autowired
+public PlatformController(PlatformService platformService) {
+    this.platformService = platformService;
+}

39-42: Update JavaDoc to reflect the current year.

The @SInCE tag shows 2024-10-20, which is a future date. Consider updating to the current date.

-* @since 2024-10-20
+* @since 2023-05-25

59-71: Results schema should indicate array type.

For endpoints returning collections, the schema implementation should reflect the array type for accurate API documentation.

@ApiResponse(responseCode = "200", description = "返回信息",
        content = @Content(mediaType = "application/json",
-                schema = @Schema(implementation = Platform.class))),
+                schema = @Schema(implementation = Platform.class, type = "array"))),
base/src/main/java/com/tinyengine/it/controller/PlatformHistoryController.java (3)

38-42: Update class-level Javadoc to match controller purpose

The class-level Javadoc comment "设计器api" (Designer API) doesn't accurately describe this controller's purpose. This controller is specifically for PlatformHistory management, not the general designer API.

/**
- * 设计器api
+ * PlatformHistory 管理API
 *
 * @since 2024-10-20
 */

48-52: Use constructor injection instead of field injection

Field-based @Autowired injection is less preferred than constructor injection in Spring applications. Constructor injection makes dependencies explicit, improves testability, and helps identify issues at startup time.

-    @Autowired
     private PlatformHistoryService platformHistoryService;
+
+    /**
+     * Constructor with required dependencies
+     * 
+     * @param platformHistoryService the platform history service
+     */
+    public PlatformHistoryController(PlatformHistoryService platformHistoryService) {
+        this.platformHistoryService = platformHistoryService;
+    }

158-160: Simplify DELETE endpoint path

The current DELETE endpoint path includes a redundant "delete" segment. Since you're already using the DELETE HTTP method, the path should be simplified to /platform-history/{id} to follow RESTful conventions.

    @SystemControllerLog(description = "删除platformHistory信息")
-   @DeleteMapping("/platform-history/delete/{id}")
+   @DeleteMapping("/platform-history/{id}")
    public Result<PlatformHistory> deletePlatformHistory(@PathVariable Integer id) {
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 091ed5e and 3438b96.

📒 Files selected for processing (7)
  • base/src/main/java/com/tinyengine/it/controller/PlatformController.java (1 hunks)
  • base/src/main/java/com/tinyengine/it/controller/PlatformHistoryController.java (1 hunks)
  • base/src/main/java/com/tinyengine/it/service/material/impl/ComponentServiceImpl.java (5 hunks)
  • base/src/main/java/com/tinyengine/it/service/platform/impl/PlatformHistoryServiceImpl.java (1 hunks)
  • base/src/main/java/com/tinyengine/it/service/platform/impl/PlatformServiceImpl.java (2 hunks)
  • base/src/main/resources/mappers/PlatformHistoryMapper.xml (1 hunks)
  • base/src/test/java/com/tinyengine/it/service/platform/impl/PlatformServiceImplTest.java (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (4)
  • base/src/main/java/com/tinyengine/it/service/material/impl/ComponentServiceImpl.java
  • base/src/test/java/com/tinyengine/it/service/platform/impl/PlatformServiceImplTest.java
  • base/src/main/java/com/tinyengine/it/service/platform/impl/PlatformServiceImpl.java
  • base/src/main/resources/mappers/PlatformHistoryMapper.xml
🧰 Additional context used
🧬 Code Graph Analysis (2)
base/src/main/java/com/tinyengine/it/service/platform/impl/PlatformHistoryServiceImpl.java (1)
base/src/main/java/com/tinyengine/it/service/platform/impl/PlatformServiceImpl.java (1)
  • Service (34-130)
base/src/main/java/com/tinyengine/it/controller/PlatformController.java (1)
base/src/main/java/com/tinyengine/it/controller/PlatformHistoryController.java (1)
  • Validated (43-163)
🔇 Additional comments (3)
base/src/main/java/com/tinyengine/it/service/platform/impl/PlatformHistoryServiceImpl.java (3)

76-86: LGTM: Delete operation properly handles edge cases.

The delete operation correctly:

  • Handles cases where the entity doesn't exist
  • Verifies exactly one row was affected
  • Returns the deleted entity on success

1-136: Overall, the implementation follows the established service pattern.

The implementation follows the same pattern as other service implementations in the codebase, with proper validation, error handling, and consistent return types. It provides standard CRUD operations for the PlatformHistory entity.


33-135:

Details

❌ Incorrect review comment

Verify if file validation is needed.

The PR is titled "feat: platform API and check file" but there's no file validation logic in this service implementation. If the PlatformHistory entity needs to undergo file validation related to the feature mentioned in the PR title, it should be added.


🏁 Script executed:

#!/bin/bash
# Check if there's any file validation related code in the codebase
echo "Searching for file validation utilities..."
rg -i "file.*check|file.*valid" --type java

echo "Searching for implementations of file validation in other service classes..."
rg -i "file.*check|file.*valid" --type java --glob "*ServiceImpl.java"

Length of output: 2490


No file validation needed in PlatformHistoryServiceImpl
PlatformHistoryServiceImpl doesn’t handle any file inputs or uploads, so it’s expected that no file‐validation logic appears here. The SecurityFileCheckUtil usage you found applies only to upload flows (e.g., in ComponentServiceImpl). You can ignore the suggestion to add file checks in this service.

Likely an incorrect or invalid review comment.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

♻️ Duplicate comments (2)
base/src/main/java/com/tinyengine/it/controller/PlatformHistoryController.java (2)

55-72: Add pagination support for list endpoint

The current implementation returns all PlatformHistory records without pagination, which could cause performance issues as the number of records grows. Consider adding pagination support for scalability.

    @SystemControllerLog(description = "查询表PlatformHistory信息")
-   @GetMapping("/platform-history/list")
-   public Result<List<PlatformHistory>> getAllPlatformHistory() {
-       List<PlatformHistory> appList = platformHistoryService.queryAllPlatformHistory();
-       return Result.success(appList);
-   }
+   @GetMapping("/platform-history")
+   public Result<Page<PlatformHistory>> getAllPlatformHistory(
+           @RequestParam(defaultValue = "0") int page,
+           @RequestParam(defaultValue = "20") int size) {
+       Page<PlatformHistory> platformHistories = platformHistoryService.queryAllPlatformHistory(page, size);
+       return Result.success(platformHistories);
+   }

This change would require updating the service interface to support pagination as well.


137-138: Add validation for update requests

Unlike the create endpoint, the update endpoint doesn't include the @Valid annotation for request validation. For consistency, add it here too.

-   public Result<PlatformHistory> updatePlatformHistory(@PathVariable Integer id, @RequestBody PlatformHistory platformHistory) {
+   public Result<PlatformHistory> updatePlatformHistory(@PathVariable Integer id, @Valid @RequestBody PlatformHistory platformHistory) {
🧹 Nitpick comments (5)
base/src/main/java/com/tinyengine/it/controller/PlatformHistoryController.java (5)

44-53: Consider using constructor injection instead of field injection.

While field injection with @Autowired works, constructor injection is preferred in modern Spring applications as it:

  • Makes dependencies explicit
  • Improves testability
  • Allows for final fields
  • Supports mandatory dependencies
@Validated
@RestController
@RequestMapping("/platform-center/api")
@Tag(name = "设计器历史")
public class PlatformHistoryController {
-    /**
-     * The PlatformHistory service.
-     */
-    @Autowired
-    private PlatformHistoryService platformHistoryService;
+    /**
+     * The PlatformHistory service.
+     */
+    private final PlatformHistoryService platformHistoryService;
+    
+    /**
+     * Constructor.
+     *
+     * @param platformHistoryService the platform history service
+     */
+    public PlatformHistoryController(PlatformHistoryService platformHistoryService) {
+        this.platformHistoryService = platformHistoryService;
+    }

98-119: Consider returning 201 Created status for resource creation

For resource creation endpoints, it's a RESTful best practice to return HTTP 201 Created status code instead of the default 200 OK, along with a Location header pointing to the newly created resource.

    @SystemControllerLog(description = "创建platformHistory")
    @PostMapping("/platform-history/create")
-   public Result<PlatformHistory> createPlatformHistory(@Valid @RequestBody PlatformHistory platformHistory) {
-       return platformHistoryService.createPlatformHistory(platformHistory);
+   public ResponseEntity<Result<PlatformHistory>> createPlatformHistory(@Valid @RequestBody PlatformHistory platformHistory) {
+       Result<PlatformHistory> result = platformHistoryService.createPlatformHistory(platformHistory);
+       return ResponseEntity
+           .created(URI.create("/platform-center/api/platform-history/" + result.getData().getId()))
+           .body(result);
    }

You'll need to add these imports:

import org.springframework.http.ResponseEntity;
import java.net.URI;

116-117: Simplify endpoint path for resource creation

According to RESTful conventions, the '/create' suffix is redundant since the HTTP method (POST) already indicates the operation.

-   @PostMapping("/platform-history/create")
+   @PostMapping("/platform-history")

136-137: Use consistent URL patterns for resource operations

The '/update/' in the path is redundant since the HTTP method (PUT) already indicates the operation. This also doesn't match the pattern used for retrieving a resource by ID.

-   @PutMapping("/platform-history/update/{id}")
+   @PutMapping("/platform-history/{id}")

160-161: Simplify endpoint path for resource deletion

According to RESTful conventions, the '/delete/' in the path is redundant since the HTTP method (DELETE) already indicates the operation.

-   @DeleteMapping("/platform-history/delete/{id}")
+   @DeleteMapping("/platform-history/{id}")
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3438b96 and 68b329a.

📒 Files selected for processing (1)
  • base/src/main/java/com/tinyengine/it/controller/PlatformHistoryController.java (1 hunks)

@hexqi hexqi merged commit c6b8c14 into opentiny:develop May 14, 2025
1 check passed
lu-yg added a commit to lu-yg/tiny-engine-backend-java that referenced this pull request Oct 23, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants