Skip to content

Conversation

@zhangjuncao
Copy link
Contributor

@zhangjuncao zhangjuncao commented Apr 15, 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 a new "Component-Library" resource with full CRUD API endpoints.
    • Added a structured data model for managing component libraries, including metadata, framework selection, and access controls.
    • Enabled associations between component libraries, tenants, and materials for improved resource management.
  • Improvements

    • Updated materials and tenant models to support relationships with the new component library resource.
    • Enhanced material-category relations to allow many-to-many associations with materials.
    • Extended user components to relate with materials, improving linkage between resources.
  • Bug Fixes

    • Removed certain controller methods from user components to streamline functionality.

@coderabbitai
Copy link

coderabbitai bot commented Apr 15, 2025

Walkthrough

This update introduces a new "component-library" resource to the API, including route definitions, a model schema, controller logic for deletion, and a service scaffold. The "component-library" model supports metadata, framework specification, access control, and relationships with tenants and materials. Related models—such as "materials," "tenant," and "material-category-relation"—are updated to establish new associations with the component library. The "user-components" controller has been refactored with the removal of its find, update, and create methods, and the user_components model now includes a relation to materials.

Changes

File(s) Change Summary
api/component-library/config/routes.json Added new API route definitions for the "component-library" resource, covering standard CRUD operations (GET, POST, PUT, DELETE) with corresponding handlers and no policies.
api/component-library/controllers/component-library.js Introduced a controller module exporting an asynchronous delete method to handle deletion of a component library and its associated user components, with error handling and entity sanitization.
api/component-library/models/component-library.js
api/component-library/services/component-library.js
Added new model and service module files for "component-library," both currently exporting empty objects and including license headers.
api/component-library/models/component-library.settings.json Defined a new collection type "Component-Library" with attributes for metadata, framework (enum), script, CSS (JSON), booleans for default/official status, access control, and relationships to users, tenants, and materials.
api/material-category-relation/models/material-category-relation.settings.json Added a many-to-many materials attribute to the model, establishing a dominant relationship with the "materials" collection via a custom join table.
api/materials/models/materials.settings.json Modified material_category_relations attribute to update the association key from "material" to "materials". Changed user_components from a string type to a dominant relational attribute referencing the "user-components" collection. Changed component_library from a string type to a dominant relational attribute referencing the "component-library" collection.
api/tenant/models/tenant.settings.json Added a component_library attribute to the tenant model, establishing a collection relationship with the "component-library" via "public_scope_tenants".
api/user-components/controllers/user-components.js Removed the find, update, and create controller methods for user components, leaving other methods unchanged.
api/user-components/models/user-components.settings.json Added a materials relational attribute linking user_components to the materials collection via the user_components relation.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant API_Router
    participant ComponentLibraryController
    participant ComponentLibraryService
    participant UserComponentsService

    Client->>API_Router: DELETE /component-library/:id
    API_Router->>ComponentLibraryController: delete(ctx)
    ComponentLibraryController->>ComponentLibraryService: Delete component library by ID
    ComponentLibraryService-->>ComponentLibraryController: Deletion result
    ComponentLibraryController->>UserComponentsService: Delete user components linked to library
    UserComponentsService-->>ComponentLibraryController: Deletion result (or error)
    ComponentLibraryController-->>API_Router: Response
    API_Router-->>Client: Response
Loading

Poem

In the warren of code, a new library appears,
With routes and relations, it hops free of fears.
Old methods retire, new models take root,
Tenants and materials now follow its suit.
A bunny applauds as the structure expands—
More features to nibble, in these digital lands!
🐇✨


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.
    • 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 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: 6

🧹 Nitpick comments (5)
api/component-library/services/component-library.js (1)

12-12: Consider adding a TODO or documentation for future service logic.

This file is currently a placeholder. If you plan to implement business logic here, consider adding a TODO comment or brief documentation to guide future contributors.

api/component-library/models/component-library.js (1)

12-12: Add a comment or TODO to clarify the purpose of this placeholder model file.

If this file is required by the framework, consider adding a comment to explain its presence for future maintainers.

api/user-components/controllers/user-components.js (1)

51-51: Document the removed methods.

The find, update, and create methods have been removed from this controller. Consider adding a comment explaining why these methods were removed and where these operations are now handled.

+  // Note: find, update, and create methods have been moved to component-library service
   
  async associated(ctx) {
api/component-library/models/component-library.settings.json (2)

4-7: Add a descriptive description for the model.

The description field is empty, which misses an opportunity to document the purpose and usage of this model.

 "info": {
   "name": "Component-Library",
-  "description": ""
+  "description": "Collection of reusable UI components that can be shared across tenants and materials"
 },

76-77: Consider adding additional fields for component management.

The current model is missing some fields that might be useful for component library management, such as tags, documentation links, and dependency information.

Consider adding these fields:

   "materials": {
     "via": "component_library",
     "collection": "materials"
-  }
+  },
+  "tags": {
+    "type": "json",
+    "description": "Array of tags for categorization and filtering"
+  },
+  "documentationUrl": {
+    "type": "string",
+    "description": "URL to component documentation"
+  },
+  "dependencies": {
+    "type": "json",
+    "description": "Key-value pairs of package dependencies"
+  }
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between dcec056 and e52498b.

📒 Files selected for processing (9)
  • api/component-library/config/routes.json (1 hunks)
  • api/component-library/controllers/component-library.js (1 hunks)
  • api/component-library/models/component-library.js (1 hunks)
  • api/component-library/models/component-library.settings.json (1 hunks)
  • api/component-library/services/component-library.js (1 hunks)
  • api/material-category-relation/models/material-category-relation.settings.json (1 hunks)
  • api/materials/models/materials.settings.json (1 hunks)
  • api/tenant/models/tenant.settings.json (1 hunks)
  • api/user-components/controllers/user-components.js (1 hunks)
🧰 Additional context used
🪛 ESLint
api/component-library/controllers/component-library.js

[error] 12-12: '_' is assigned a value but never used.

(no-unused-vars)


[error] 13-13: 'sanitizeEntity' is assigned a value but never used.

(no-unused-vars)


[error] 14-14: 'ERROR_TYPE' is assigned a value but never used.

(no-unused-vars)


[error] 14-14: 'UNIT_TYPE' is assigned a value but never used.

(no-unused-vars)


[error] 14-14: 'AUTH_TYPE' is assigned a value but never used.

(no-unused-vars)


[error] 15-15: 'throwErrors' is assigned a value but never used.

(no-unused-vars)


[error] 15-15: 'getPublicSuperAdmin' is assigned a value but never used.

(no-unused-vars)


[error] 15-15: 'isTenantAdmin' is assigned a value but never used.

(no-unused-vars)


[error] 17-17: 'isTruthy' is assigned a value but never used.

(no-unused-vars)


[error] 18-18: 'findAllMaterial' is assigned a value but never used.

(no-unused-vars)


[error] 19-19: 'handlePublicScope' is assigned a value but never used.

(no-unused-vars)


[error] 25-25: 'entity' is assigned a value but never used.

(no-unused-vars)


[error] 30-30: 'res' is not defined.

(no-undef)


[error] 32-32: 'res' is not defined.

(no-undef)

🔇 Additional comments (3)
api/tenant/models/tenant.settings.json (1)

46-49: Component library relation added correctly to tenant model.

The many-to-many relationship with the component-library collection is well-defined and consistent with existing schema conventions.

api/material-category-relation/models/material-category-relation.settings.json (1)

20-25: Many-to-many relationship with materials defined correctly.

The new materials attribute establishes a proper many-to-many relationship with the materials collection, including join table and dominance settings.

api/materials/models/materials.settings.json (1)

95-96: Schema relationships updated correctly for material categories and component libraries.

The updates to the material_category_relations and component_library attributes are correct and align with the new relational structure.

Also applies to: 98-100

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)
api/component-library/controllers/component-library.js (2)

13-15: Remove unused imports if they're not needed elsewhere.

Your code currently only references sanitizeEntity, throwErrors, and ERROR_TYPE. Consider removing any imports that aren't used.


18-36: ⚠️ Potential issue

Fix critical issues in delete method implementation.

The current implementation has several issues:

  1. There's unreachable code at line 35 (the final return statement will never be executed)
  2. The second return statement has an extra semicolon
  3. The error handling could be improved to be more resilient

Apply these changes:

  async delete(ctx) {
    const { id } = ctx.params;
    try{
      const res = await strapi.services['component-library'].delete({ id });
      try{
        await strapi.services['user-components'].delete({ library: id });
      } catch (error) {
        strapi.log.error('user-component delete failed', error);
-       throwErrors('user-component delete failed.', ERROR_TYPE.badRequest);
+       // Log the error but continue execution since the main operation succeeded
+       // Consider adding a warning flag in the response if needed
      }
      return sanitizeEntity(res, {model: strapi.models['component-library']});

    }catch(error) {
      strapi.log.error('component-library delete failed', error);
      throwErrors('component-library delete failed.', ERROR_TYPE.badRequest);
    }
    
-   return sanitizeEntity(res, {model: strapi.models['component-library']});;
  }

This implementation logs user-component deletion failures without aborting the operation, which is more resilient as it allows the primary operation to succeed even if cleanup of related records fails.

🧰 Tools
🪛 Biome (1.9.4)

[error] 35-35: This code is unreachable

... because this statement will return from the function beforehand

(lint/correctness/noUnreachable)

🪛 ESLint

[error] 35-35: 'res' is not defined.

(no-undef)


[error] 35-35: Unnecessary semicolon.

(no-extra-semi)

🧹 Nitpick comments (1)
api/component-library/controllers/component-library.js (1)

18-36: Consider a more comprehensive error handling strategy.

Currently, if user-component deletion fails, the entire operation fails with a 400 bad request error. This might not be the best user experience as the main operation (deleting the component library) succeeded.

Consider implementing a more nuanced error handling approach:

  async delete(ctx) {
    const { id } = ctx.params;
    try {
      const res = await strapi.services['component-library'].delete({ id });
+     
+     // Track warnings for partial success scenarios
+     const warnings = [];
+     
      try {
        await strapi.services['user-components'].delete({ library: id });
      } catch (error) {
        strapi.log.error('user-component delete failed', error);
-       throwErrors('user-component delete failed.', ERROR_TYPE.badRequest);
+       warnings.push('Failed to delete some associated user components');
      }
      
-     return sanitizeEntity(res, {model: strapi.models['component-library']});
+     // Return a structured response with both the entity and any warnings
+     return {
+       data: sanitizeEntity(res, {model: strapi.models['component-library']}),
+       warnings: warnings.length ? warnings : undefined
+     };
    } catch(error) {
      strapi.log.error('component-library delete failed', error);
      throwErrors('component-library delete failed.', ERROR_TYPE.badRequest);
    }
-   
-   return sanitizeEntity(res, {model: strapi.models['component-library']});;
  }

This approach:

  1. Provides a more detailed response structure
  2. Allows the API to communicate partial success scenarios
  3. Gives clients information about what succeeded and what failed
🧰 Tools
🪛 Biome (1.9.4)

[error] 35-35: This code is unreachable

... because this statement will return from the function beforehand

(lint/correctness/noUnreachable)

🪛 ESLint

[error] 35-35: 'res' is not defined.

(no-undef)


[error] 35-35: Unnecessary semicolon.

(no-extra-semi)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e52498b and 34e8046.

📒 Files selected for processing (2)
  • api/component-library/controllers/component-library.js (1 hunks)
  • api/component-library/models/component-library.settings.json (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • api/component-library/models/component-library.settings.json
🧰 Additional context used
🧬 Code Graph Analysis (1)
api/component-library/controllers/component-library.js (2)
api/user-components/controllers/user-components.js (4)
  • require (12-12)
  • require (13-13)
  • require (14-14)
  • require (15-21)
config/toolkits.js (1)
  • throwErrors (155-157)
🪛 Biome (1.9.4)
api/component-library/controllers/component-library.js

[error] 35-35: This code is unreachable

... because this statement will return from the function beforehand

(lint/correctness/noUnreachable)

🪛 ESLint
api/component-library/controllers/component-library.js

[error] 35-35: 'res' is not defined.

(no-undef)


[error] 35-35: Unnecessary semicolon.

(no-extra-semi)

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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 34e8046 and 8544a2a.

📒 Files selected for processing (2)
  • api/materials/models/materials.settings.json (2 hunks)
  • api/user-components/models/user-components.settings.json (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • api/materials/models/materials.settings.json
🔇 Additional comments (1)
api/user-components/models/user-components.settings.json (1)

117-120: Verify the materials many-to-many relationship.
This adds a bidirectional relation to the materials collection via user_components. Confirm that the reciprocal field in api/materials/models/materials.settings.json is marked with "dominant": true" so Strapi manages the pivot table correctly. If already set, no further action is needed.

@hexqi hexqi merged commit 6ba323a into opentiny:main Apr 29, 2025
1 check passed
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