Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: allow to set symbol property on request, response, context and app #12

Merged
merged 2 commits into from
Dec 18, 2024

Conversation

fengmk2
Copy link
Member

@fengmk2 fengmk2 commented Dec 18, 2024

Summary by CodeRabbit

  • New Features

    • Introduced a CustomRequest class for enhanced host value retrieval.
    • Added support for additional Node.js versions in CI testing.
  • Improvements

    • Updated ESLint configuration to include more linting rules.
    • Enhanced error handling and middleware management in the Application class.
    • Added symbol key properties in Context, Request, and Response classes for increased flexibility.
  • Refactor

    • Simplified import paths in example files for better maintainability.

Copy link

coderabbitai bot commented Dec 18, 2024

Caution

Review failed

The pull request is closed.

Walkthrough

This pull request introduces several modifications across the project, focusing on enhancing flexibility and expanding compatibility. The changes include updating the ESLint configuration to extend additional rules, expanding the Node.js CI testing matrix to include version 23, adding a CustomRequest class for advanced host resolution, simplifying import paths in example files, and introducing symbol-based property support in core classes like Application, Context, Request, and Response. The modifications aim to improve the project's adaptability and error handling without fundamentally altering the existing architecture.

Changes

File Change Summary
.eslintrc Extended ESLint configuration to include eslint-config-egg/lib/rules/enforce-node-prefix
.github/workflows/node.js.yml Added Node.js version 23 to CI testing matrix
example/extend/Request.ts Added CustomRequest class with advanced host resolution logic
example/helloworld.cjs Simplified Application import path from specific to parent directory
example/helloworld.mjs Simplified Application import path from specific to parent directory
src/application.ts Updated debug namespace, added symbol-based property, enhanced middleware and error handling
src/context.ts Added symbol-based property to enhance flexibility
src/request.ts Added symbol-based property to enhance flexibility
src/response.ts Added symbol-based property to enhance flexibility

Sequence Diagram

sequenceDiagram
    participant App as Application
    participant MW as Middleware
    participant Req as Request
    participant Res as Response
    participant Ctx as Context

    App->>MW: use middleware
    MW-->>App: register middleware
    App->>Req: create request
    App->>Res: create response
    App->>Ctx: create context
    Ctx->>Req: delegate methods
    Ctx->>Res: delegate methods
    App->>MW: compose and execute middleware
Loading

Poem

🐰 A Rabbit's Ode to Code Refinement 🌟

Symbols dance, imports grow light,
Middleware flows with newfound might,
Versions expand, our tests take flight,
Flexibility blooms, pure and bright,
In CodeRabbit's realm of pure delight!

hop hop 🚀


📜 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 f0653f8 and 949d4d0.

📒 Files selected for processing (1)
  • example/extend/Request.ts (1 hunks)

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

Open in Stackblitz

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

commit: 949d4d0

Copy link

codecov bot commented Dec 18, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 100.00%. Comparing base (2967724) to head (949d4d0).
Report is 3 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff            @@
##            master       #12   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files            6         6           
  Lines         1714      1718    +4     
  Branches       315       319    +4     
=========================================
+ Hits          1714      1718    +4     

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

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 (6)
example/extend/Request.ts (1)

6-18: Add JSDoc documentation

Consider adding JSDoc to document the host getter's behavior, especially regarding proxy handling.

Add documentation like this:

+  /**
+   * Get the host of the request.
+   * When app.proxy is true, supports X-Forwarded-Host
+   * @return {string} hostname:port
+   */
   get host(): string {
src/context.ts (1)

14-14: Add documentation for symbol property usage

While the implementation is type-safe using unknown, it would be helpful to add JSDoc comments explaining:

  • The intended use cases for symbol properties
  • Best practices for symbol management
  • Memory management considerations
+/**
+ * @description Allows setting custom properties using symbols as keys
+ * @example
+ * const customProp = Symbol('customProp');
+ * ctx[customProp] = value;
+ */
 [key: symbol]: unknown;
src/application.ts (1)

32-32: Add documentation for symbol property usage

For consistency with the Context class, please add documentation for the symbol property feature.

+/**
+ * @description Allows setting custom properties using symbols as keys
+ * @example
+ * const customProp = Symbol('customProp');
+ * app[customProp] = value;
+ */
 [key: symbol]: unknown;
src/response.ts (2)

20-20: Add documentation for symbol property usage

For consistency with other core classes, please add documentation for the symbol property feature.

+/**
+ * @description Allows setting custom properties using symbols as keys
+ * @example
+ * const customProp = Symbol('customProp');
+ * response[customProp] = value;
+ */
 [key: symbol]: unknown;

Line range hint 14-14: Consider adding comprehensive documentation for symbol property feature

The addition of symbol property support across core classes (Context, Application, and Response) is well-implemented with type safety in mind. However, consider adding:

  1. A central documentation section explaining:
    • The motivation behind this feature
    • Guidelines for creating and managing symbols
    • Best practices for symbol property lifecycle
  2. Example use cases in the README or documentation
  3. Performance implications and memory management considerations

This will help users understand and properly utilize this new feature.

Also applies to: 32-32, 20-20

src/request.ts (1)

16-16: Consider adding documentation for symbol property usage.

Since this introduces a new way to store properties on the Request class, it would be helpful to:

  1. Document the intended use cases
  2. Add examples of proper symbol property management
  3. Note any cleanup requirements to prevent memory leaks

Example documentation to add above the class:

/**
 * ...existing class documentation...
 * 
 * Symbol Properties:
 * The Request class supports symbol-based properties for storing metadata:
 * 
 * ```typescript
 * const metadataSymbol = Symbol('metadata');
 * req[metadataSymbol] = { /* custom data */ };
 * ```
 * 
 * Note: Ensure proper cleanup of symbol properties when they are no longer needed
 * to prevent memory leaks in long-running applications.
 */
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 80fcbf7 and f0653f8.

📒 Files selected for processing (9)
  • .eslintrc (1 hunks)
  • .github/workflows/node.js.yml (1 hunks)
  • example/extend/Request.ts (1 hunks)
  • example/helloworld.cjs (1 hunks)
  • example/helloworld.mjs (1 hunks)
  • src/application.ts (2 hunks)
  • src/context.ts (1 hunks)
  • src/request.ts (1 hunks)
  • src/response.ts (1 hunks)
✅ Files skipped from review due to trivial changes (2)
  • example/helloworld.cjs
  • example/helloworld.mjs
🔇 Additional comments (6)
.eslintrc (1)

3-4: LGTM! Verify rule compatibility

The addition of enforce-node-prefix rule aligns with the PR's objective of handling symbol properties consistently.

✅ Verification successful

Rule enforces node: prefix for Node.js built-in modules

The rule is correctly implemented and enforces the use of the node: protocol prefix for Node.js built-in modules (like node:fs, node:path, etc.) by using ESLint's no-restricted-imports and no-restricted-modules rules. This is a recommended practice for explicit module resolution in Node.js. The rule is compatible with the project's eslint-config-egg v14.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Verify the eslint rule exists and is properly documented
curl -s https://raw.githubusercontent.com/eggjs/eslint-config-egg/master/lib/rules/enforce-node-prefix.js | grep -q "module.exports" && echo "Rule exists" || echo "Rule not found"

Length of output: 165


Script:

#!/bin/bash
# Let's verify the actual content of the rule to understand its implementation
curl -s https://raw.githubusercontent.com/eggjs/eslint-config-egg/master/lib/rules/enforce-node-prefix.js

# Also check if there are any existing usages of this rule in the codebase
rg -l "node\." -t js -t ts

# And check package.json for eslint-config-egg version
cat package.json | jq '.dependencies["eslint-config-egg"] // .devDependencies["eslint-config-egg"]'

Length of output: 1342

.github/workflows/node.js.yml (1)

15-15: Consider Node.js version stability implications

Adding Node.js 23 expands test coverage to include the latest version. However, note that v23 is not an LTS release and may have stability implications.

✅ Verification successful

Node.js version matrix is compatible with package requirements

The package.json specifies >= 18.19.0 as the Node.js engine requirement, which aligns well with the CI test matrix (18.19.0, 18, 20, 22, 23). No version-specific APIs or features were found in the codebase that could cause stability issues. While Node.js 23 is not LTS, testing against it provides early feedback for future compatibility.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check package.json for engine constraints
fd package.json --exec sh -c 'echo "Checking engine constraints in {}:"; cat {} | jq -r ".engines.node"'

Length of output: 164


Script:

#!/bin/bash
# Check for Node.js version-specific features or APIs in the codebase
rg -i --type js --type ts 'node:[0-9]+' -A 2

# Look for potential version-sensitive Node.js APIs
rg -i --type js --type ts '(webcrypto|test_runner|--test|fetch|WebSocket|diagnostics_channel|worker_threads|performance\.timeOrigin|--experimental)' -A 2

Length of output: 202

example/extend/Request.ts (2)

3-3: LGTM! Good use of Symbol for private property

Using Symbol for the host cache prevents naming collisions and aligns with the PR's objective.


5-19: Verify consistency with existing patterns

Let's ensure this implementation aligns with existing patterns in the codebase.

✅ Verification successful

Let me gather more specific information about getter patterns in the codebase.


Based on the comprehensive results, I can now generate the final response:

Implementation follows existing patterns correctly

The host getter implementation in CustomRequest follows the established patterns in the codebase:

  • Uses Symbol for private storage (HOST) consistent with other Symbol usage
  • Follows the getter pattern seen throughout the codebase
  • Handles proxy cases similar to the base implementation
  • Uses the same string splitting pattern for handling multiple hosts

The main difference is the default to '127.0.0.1' when proxy is enabled, which is an intentional customization that doesn't break the overall pattern.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for similar Symbol usage patterns
ast-grep --pattern 'const $_ = Symbol($$$)'

# Check for similar getter implementations
ast-grep --pattern 'get $_() {
  $$$
  return $$$;
}'

Length of output: 166


Script:

#!/bin/bash
# Search for getter implementations in Request-related files
rg "get \w+\(\)" -A 10 

# Check for host-related patterns
rg "host" -A 5

Length of output: 42178

src/application.ts (1)

20-20: LGTM: Debug namespace update

The debug namespace change to '@eggjs/koa/application' improves consistency with the package structure.

src/request.ts (1)

16-16: LGTM! Well-designed symbol property support.

The addition of symbol-based property support is a good design choice:

  • Uses TypeScript's unknown type for type-safety
  • Prevents naming collisions via symbols
  • Enables plugins/middleware to safely store metadata

example/extend/Request.ts Outdated Show resolved Hide resolved
example/extend/Request.ts Show resolved Hide resolved
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
@fengmk2 fengmk2 merged commit 5e18ed2 into master Dec 18, 2024
23 checks passed
@fengmk2 fengmk2 deleted the allow-set-symbol-key branch December 18, 2024 15:33
fengmk2 pushed a commit that referenced this pull request Dec 18, 2024
[skip ci]

## [2.20.0](v2.19.2...v2.20.0) (2024-12-18)

### Features

* allow to set symbol property on request, response, context and app ([#12](#12)) ([5e18ed2](5e18ed2))
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