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

fix: export EggAppConfig type let plugin can override it #286

Merged
merged 3 commits into from
Jan 3, 2025

Conversation

fengmk2
Copy link
Member

@fengmk2 fengmk2 commented Jan 3, 2025

Summary by CodeRabbit

  • Type Safety Improvements

    • Enhanced type definitions for application configuration
    • Centralized type management across modules
    • Introduced more precise type checking for configuration objects
  • Code Structure

    • Refactored type imports and exports
    • Updated case style handling with new enum
    • Simplified type management in loader components
  • Testing

    • Added type exposure tests
    • Updated test configurations to reflect new type structures

Copy link

coderabbitai bot commented Jan 3, 2025

Warning

Rate limit exceeded

@fengmk2 has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 8 minutes and 19 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 5a80a53 and 5579a42.

📒 Files selected for processing (5)
  • src/loader/egg_loader.ts (13 hunks)
  • src/types.ts (1 hunks)
  • test/index.test.ts (3 hunks)
  • test/loader/file_loader.test.ts (5 hunks)
  • test/loader/mixin/load_custom_loader.test.ts (4 hunks)

Walkthrough

This pull request introduces a comprehensive type system enhancement for the Egg framework. The changes centralize type definitions in a new types.ts file, refactor type handling across multiple source files, and improve type safety by introducing more specific type declarations. The modifications include updating interfaces, introducing new type definitions, and standardizing type usage in loader and configuration-related components.

Changes

File Change Summary
src/egg.ts Added explicit EggAppConfig return type for config getter
src/index.ts Added type re-export for all types from ./types.js
src/loader/egg_loader.ts Removed EggAppInfo and EggPluginInfo interfaces, updated method signatures with more specific types
src/loader/file_loader.ts Transformed CaseStyle from string literal to enum
src/types.ts Introduced new interfaces: EggAppInfo, EggPluginInfo, CustomLoaderConfigItem, EggAppConfig
test/index.test.ts Added type import and new test case for type exposure
test/loader/mixin/load_controller.test.ts Updated assertion with optional chaining
test/loader/mixin/load_custom_loader.test.ts Added coreMiddleware and appMiddleware to configuration

Sequence Diagram

sequenceDiagram
    participant Types as types.ts
    participant Index as index.ts
    participant Loader as egg_loader.ts
    participant FileLoader as file_loader.ts

    Types->>Index: Re-export all types
    Index-->>Loader: Import types
    Loader->>FileLoader: Use CaseStyle enum
    FileLoader-->>Loader: Provide type-safe case styles
Loading

Possibly related PRs

Poem

🐰 In the realm of types, a rabbit's delight,
Enums and interfaces now shine so bright!
From camel to lower, our styles now dance,
With CodeRabbit's magic, we enhance our chance!
Type safety leaps, with joy unbridled! 🌈


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

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

CodeRabbit Configuration File (.coderabbit.yaml)

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

Documentation and Community

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

Copy link

pkg-pr-new bot commented Jan 3, 2025

Open in Stackblitz

npm i https://pkg.pr.new/eggjs/core/@eggjs/core@286

commit: 5579a42

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

🧹 Nitpick comments (4)
src/loader/egg_loader.ts (2)

825-828: Clear initialization of essential middleware arrays.
Defining appMiddleware and coreMiddleware here aligns with EggAppConfig. Consider also documenting default usage to avoid confusion about empty arrays.


858-859: Potential naming mismatch.
coreMiddlewares = coreMiddleware and appMiddlewares = middleware can be confusing. Consider consistent naming across the codebase for clarity (e.g., coreMiddlewarecoreMiddlewares in config or vice versa).

src/egg.ts (1)

251-252: Fallback Return for Configuration

While casting an empty object to EggAppConfig avoids TypeScript errors, it might mask missing properties at runtime. Consider returning a properly shaped partial object or throwing an error to prevent hidden misconfigurations.

-    return this.loader ? this.loader.config : {} as EggAppConfig;
+    if (this.loader) {
+      return this.loader.config;
+    }
+    // Return a safe fallback or throw error instead of silent cast
+    return {
+      // Provide an actual minimal fallback or handle the scenario appropriately
+    } as EggAppConfig;
test/loader/mixin/load_controller.test.ts (1)

382-382: Safeguard Non-Null Assertion

Using the ! operator asserts controller is non-null. Ensure this is always valid here. Alternatively, you could safely guard this test logic to prevent potential runtime errors if controller becomes undefined.

-      assert.equal(app.config.controller!.supportParams, true);
+      assert.ok(app.config.controller && app.config.controller.supportParams === true,
+        'controller supports params should be true'
+      );
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 31f2580 and 5a80a53.

📒 Files selected for processing (8)
  • src/egg.ts (2 hunks)
  • src/index.ts (1 hunks)
  • src/loader/egg_loader.ts (14 hunks)
  • src/loader/file_loader.ts (3 hunks)
  • src/types.ts (1 hunks)
  • test/index.test.ts (3 hunks)
  • test/loader/mixin/load_controller.test.ts (1 hunks)
  • test/loader/mixin/load_custom_loader.test.ts (1 hunks)
🔇 Additional comments (23)
src/loader/egg_loader.ts (10)

13-13: No issues importing from file_loader.
Usage of CaseStyle should facilitate robust filename transformations.


22-22: Good centralization of type definitions.
Switching to EggAppConfig, EggAppInfo, and EggPluginInfo from a dedicated file helps maintain cleaner type references.


811-811: Improved type safety for config property.
Using EggAppConfig strengthens type coherence and enforces consistent config structures.


1177-1177: Using CaseStyle.lower for service loading.
Ensures consistent case transformation, avoiding collisions when naming service classes.


1217-1217: Applying CaseStyle.lower for middleware loading.
Consistent usage improves naming conventions, minimizing letter-case drift in middleware files.


1292-1292: Controller loader now enforces CaseStyle.lower.
This aligns controllers with a standardized naming pattern across the application.


1372-1372: Extending caseStyle: CaseStyle.lower for custom loader injections.
Maintaining uniform naming ensures less confusion when referencing dynamically loaded classes.


1383-1383: Initializer for custom loader also uses CaseStyle.lower.
This continues the uniform approach, simplifying code support.


1502-1503: Enhanced type for loadToApp signature.
By omitting 'inject' and 'target', you prevent accidental overriding and maintain clearer, safer defaults. The usage of new FileLoader(loadOptions).load() is coherent with the updated signature.

Also applies to: 1506-1506, 1515-1515


1526-1528: Refined context loader signature.
Similar to loadToApp, this ensures consistent injection mechanics for context objects. Keep verifying that other parts of the framework properly adopt these new type constraints.

Also applies to: 1537-1537

✅ Verification successful

Let me analyze the usage of loadToContext across the codebase to verify the type constraints.


Let me check one more aspect to verify the type constraints implementation.


Type constraints for loadToContext are properly implemented and used

Based on the verification results:

  • The loadToContext method's signature correctly enforces type constraints through ContextLoaderOptions interface
  • The interface extends FileLoaderOptions with proper omission of 'target' property
  • All usages in the codebase follow the type constraints:
    • Service loading uses proper type casting: options as ContextLoaderOptions
    • Custom loader implementation properly constructs the options object
    • Test cases validate the type constraints through various scenarios
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Searching references to loadToContext calls, verifying parameter usage
rg -A 5 "loadToContext"

Length of output: 4846


Script:

#!/bin/bash
# Check the type definitions and implementations
ast-grep --pattern 'interface ContextLoaderOptions {
  $$$
}'

# Check test cases for type validation
rg -B 3 -A 3 "loadToContext.*options"

Length of output: 867


Script:

#!/bin/bash
# Check the interface definitions and type constraints
rg -B 5 -A 5 "interface.*LoaderOptions"

# Check test cases with type validation
ast-grep --pattern 'loadToContext($$$, $_, {
  $$$
})'

Length of output: 2587

src/index.ts (1)

13-13: Re-exporting types from a centralized file.
This is beneficial: it exposes all type definitions at a single import entry point for consumers.

test/index.test.ts (3)

3-3: Explicit type import fosters clarity.
Importing EggAppConfig improves tests’ maintainability and ensures alignment with the actual app config shape.


14-14: Added 'CaseStyle' to the assertion list.
Verifying that CaseStyle is exposed from the index, ensuring the library’s public API remains stable.


37-44: Test ensures new config properties are exposed.
Demonstrates that coreMiddleware and appMiddleware match EggAppConfig expectations. Good coverage of the newly introduced fields.

src/types.ts (4)

1-16: EggAppInfo centralizes all essential app metadata.
The defined fields (e.g., baseDir, env, root) are well-structured, reflecting typical Egg usage patterns.


18-38: EggPluginInfo clarifies plugin metadata.
Properties like dependencies, optionalDependencies, and env are crucial for a robust plugin ecosystem.


40-47: CustomLoaderConfigItem structure is clear.
Capturing directory, inject, and loadunit offers direct guidance for customizing loader behavior in Egg.


49-56: EggAppConfig consolidates config fields.
Defining coreMiddleware, appMiddleware, customLoader, and controller support ensures that applications benefit from type-safe configuration.

test/loader/mixin/load_custom_loader.test.ts (1)

105-106: Explicitly adding coreMiddleware and appMiddleware.
Enhances clarity in your test config, proving that the application can handle these new fields without collisions.

src/loader/file_loader.ts (3)

14-18: Enums Provide Stronger Type Safety

Replacing the string literal union type with an enum is a solid move. It increases readability, ensures robust type-safety, and eases debugging and refactoring operations.


87-87: Good Default Value Usage

Setting CaseStyle.camel as a default aligns with typical naming conventions. This makes the loader behavior more intuitive out of the box.


96-96: Backward Compatibility Approach

Thanks for preserving backward compatibility by converting lowercaseFirst usage to CaseStyle.lower. Ensure the deprecation notice is adequately documented to guide users in migrating away from the legacy option.

src/egg.ts (1)

21-21: New Explicit Type Import

Importing EggAppConfig explicitly clarifies the contract for configuration objects, enhancing maintainability.

Copy link

codecov bot commented Jan 3, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 97.73%. Comparing base (84dc3b3) to head (5579a42).
Report is 2 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff             @@
##           master     #286      +/-   ##
==========================================
- Coverage   97.74%   97.73%   -0.02%     
==========================================
  Files          10       10              
  Lines        3376     3351      -25     
  Branches      595      596       +1     
==========================================
- Hits         3300     3275      -25     
  Misses         76       76              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@fengmk2 fengmk2 merged commit 62b1f97 into master Jan 3, 2025
24 checks passed
@fengmk2 fengmk2 deleted the export-type-EggAppConfig branch January 3, 2025 13:10
fengmk2 pushed a commit that referenced this pull request Jan 3, 2025
[skip ci]

## [6.2.12](v6.2.11...v6.2.12) (2025-01-03)

### Bug Fixes

* export EggAppConfig type let plugin can override it ([#286](#286)) ([62b1f97](62b1f97))
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.

1 participant