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: make Context state property can be override by Sub Class #14

Merged
merged 1 commit into from
Dec 19, 2024

Conversation

fengmk2
Copy link
Member

@fengmk2 fengmk2 commented Dec 19, 2024

Summary by CodeRabbit

  • New Features

    • Introduced a CustomContext class for enhanced state management.
    • Added a new RequestSocket interface to simplify socket type definitions.
  • Bug Fixes

    • Improved error handling in the Context class.
  • Tests

    • Added new test cases for ctx.state functionality and Koa application context logging.

Copy link

coderabbitai bot commented Dec 19, 2024

Walkthrough

This pull request introduces several modifications to the Koa framework's core components. The changes primarily focus on enhancing the Context class by making the state property private and adding a getter method. A new RequestSocket interface is introduced in the request handling module to improve type definitions. Additionally, new test cases are added to validate the context state management and application behavior, including a test that demonstrates extending the Context class with a custom implementation.

Changes

File Change Summary
example/extend/Context.ts Added CustomContext class extending base Context with a custom state getter
src/context.ts Converted state to a private field #state with a new getter method
src/request.ts Introduced RequestSocket interface and updated socket type casting
test/application/index.test.ts Added a new test case for printing application context objects
test/context/state.test.ts Added tests for ctx.state functionality and custom state implementation

Sequence Diagram

sequenceDiagram
    participant App as Koa Application
    participant Context as Custom Context
    participant Middleware as Middleware

    App->>Context: Create Context
    Context-->>App: Initialize with empty state
    Middleware->>Context: Modify state
    Context-->>Middleware: Update state
    Middleware->>App: Continue request processing
Loading

Possibly related PRs

Poem

🐰 In the realm of Koa's embrace,
A context with state finds its place,
Private fields dance, getters shine bright,
Extending classes with rabbit's might!
Code evolves with playful grace 🌟


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 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 Dec 19, 2024

Open in Stackblitz

npm i https://pkg.pr.new/eggjs/koa/@eggjs/koa@14

commit: 6a47f7f

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

🧹 Nitpick comments (3)
example/extend/Context.ts (1)

4-6: Add return type annotation for better type safety.

Consider adding explicit return type annotation to the state getter:

-  get state() {
+  get state(): Record<string, any> {
     return { foo: 'bar' };
   }
test/context/state.test.ts (2)

34-36: Improve type safety by avoiding type assertion.

Instead of using type assertion, consider defining a proper interface for the state:

-      assert.deepStrictEqual(ctx.state, { foo: 'bar' });
-      (ctx.state as any).user = 'example';
+      interface CustomState extends Record<string, string> {
+        foo: string;
+        user?: string;
+      }
+      const state = ctx.state as CustomState;
+      assert.deepStrictEqual(state, { foo: 'bar' });
+      state.user = 'example';

25-42: Add test cases for additional scenarios.

Consider adding tests for:

  1. Nested state properties
  2. Multiple middleware state modifications
  3. Error cases (e.g., attempting to modify immutable state)

Would you like me to help generate these additional test cases?

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between dd1de9a and 6a47f7f.

📒 Files selected for processing (5)
  • example/extend/Context.ts (1 hunks)
  • src/context.ts (2 hunks)
  • src/request.ts (2 hunks)
  • test/application/index.test.ts (1 hunks)
  • test/context/state.test.ts (1 hunks)
🔇 Additional comments (4)
example/extend/Context.ts (1)

4-6: Consider implications of immutable state implementation.

The current implementation returns a new object on every state access. This means state modifications won't persist across middleware. If this is intentional, consider documenting this behavior.

src/context.ts (1)

22-22: LGTM! Well-structured encapsulation of the state property.

The changes effectively make the state property overridable by subclasses while maintaining proper encapsulation through the private field pattern. This is a good implementation that follows TypeScript best practices.

Also applies to: 222-224

src/request.ts (2)

15-17: LGTM! Good type definition for the socket interface.

The RequestSocket interface properly extends the Socket type and explicitly defines the encrypted property, improving type safety and maintainability.


306-306: LGTM! Clean type implementation in the socket getter.

The change simplifies the type casting by utilizing the newly defined RequestSocket interface, improving code readability while maintaining the same functionality.

Comment on lines +18 to +23
const server = app.listen();

return request(server)
.get('/')
.expect(404);
});
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add server cleanup after test completion.

The server should be closed after the test completes to prevent resource leaks:

   const server = app.listen();

   return request(server)
     .get('/')
-    .expect(404);
+    .expect(404)
+    .then(() => server.close());
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const server = app.listen();
return request(server)
.get('/')
.expect(404);
});
const server = app.listen();
return request(server)
.get('/')
.expect(404)
.then(() => server.close());
});

test/application/index.test.ts Show resolved Hide resolved
Copy link

codecov bot commented Dec 19, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 100.00%. Comparing base (320fbf5) to head (6a47f7f).
Report is 2 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff            @@
##            master       #14   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files            6         6           
  Lines         1718      1725    +7     
  Branches       319       321    +2     
=========================================
+ Hits          1718      1725    +7     

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

@fengmk2 fengmk2 merged commit 49abe7f into master Dec 19, 2024
23 checks passed
@fengmk2 fengmk2 deleted the make-state-override branch December 19, 2024 12:18
fengmk2 pushed a commit that referenced this pull request Dec 19, 2024
[skip ci]

## [2.20.2](v2.20.1...v2.20.2) (2024-12-19)

### Bug Fixes

* make Context state property can be override by Sub Class ([#14](#14)) ([49abe7f](49abe7f))
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