Skip to content

feat(server): check prefix inside handlers#285

Closed
dinwwwh wants to merge 1 commit intomainfrom
feat/server/check-prefix-inside-handler
Closed

feat(server): check prefix inside handlers#285
dinwwwh wants to merge 1 commit intomainfrom
feat/server/check-prefix-inside-handler

Conversation

@dinwwwh
Copy link
Copy Markdown
Member

@dinwwwh dinwwwh commented Mar 22, 2025

Mean you don't need manually check prefix, oRPC do that for you

Before:

export async function fetch(request: Request): Promise<Response> {
  const url = new URL(request.url)

  if (url.pathname.startsWith('/rpc')) {
    const { response } = await handler.handle(request, {
      prefix: '/rpc',
      context: {} // Provide initial context if needed
    })

    if (response)
      return response
  }

  return new Response('Not found', { status: 404 })
}

After:

export async function fetch(request: Request): Promise<Response> {
  const { matched, response } = await handler.handle(request, {
    prefix: '/rpc',
    context: {} // Provide initial context if needed
  })

  if (matched) {
    return response
  }

  return new Response('Not found', { status: 404 })
}

Summary by CodeRabbit

  • Refactor

    • Streamlined request processing across various server integrations to ensure efficient handling and consistent responses.
    • Improved URL handling and simplified internal logic for API and RPC endpoints.
    • Updated public utilities to provide a cleaner interface.
  • Tests

    • Expanded test coverage to confirm correct behavior when handling unexpected request prefixes.

Mean you don't need manually check prefix, oRPC do that for you
@vercel
Copy link
Copy Markdown

vercel bot commented Mar 22, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
orpc ✅ Ready (Inspect) Visit Preview 💬 Add feedback Mar 22, 2025 4:09am

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Mar 22, 2025

Walkthrough

This pull request refactors the request handling logic across various integration documents and server/client packages. The changes eliminate the creation of temporary URL objects and redundant pathname checks in favor of directly invoking the handler.handle method and using its returned matched and response values. Additionally, the changes update the URL trimming method in the client adapter, modify the test suite to account for invalid prefixes, and adjust the exported functions in the shared module.

Changes

File(s) Change Summary
apps/content/docs/integrations/bun.md
apps/content/docs/integrations/cloudflare-workers.md
apps/content/docs/integrations/deno.md
apps/content/docs/integrations/fetch-server.md
apps/content/docs/integrations/node.md
apps/content/docs/openapi/openapi-handler.md
apps/content/docs/openapi/scalar.md
apps/content/docs/rpc-handler.md
Refactored fetch methods to eliminate URL parsing and explicit pathname checks; now directly destructures the result of handler.handle to determine if a response should be returned.
packages/client/src/adapters/standard/rpc-link-codec.ts
packages/server/src/adapters/standard/handler.ts
packages/shared/src/index.ts
Replaced the use of the trim function with a regex-based replacement for trailing slashes, refactored URL/path processing logic, and updated exports to remove trim.
packages/server/src/adapters/standard/handler.test.ts Added a new test case to verify that the handler returns a mismatch when provided with an invalid prefix.
playgrounds/contract-first/src/main.ts Simplified API and RPC request handling by removing explicit URL prefix checks and directly using the responses from the corresponding handlers.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Server
    participant Handler
    Client->>Server: Send HTTP request
    Server->>Handler: Call handler.handle(request)
    Handler-->>Server: Return { matched, response }
    alt matched is true
        Server-->>Client: Return response
    else matched is false
        Server-->>Client: Return 404 Not Found
    end
Loading

Possibly related PRs

  • unnoq/orpc#241: Refactors request handling logic in the fetch method, similar to removing URL object creation and simplifying control flow.
  • unnoq/orpc#220: Involves similar changes to the fetch method, removing URL checks for more direct handler responses.
  • unnoq/orpc#246: Also refactors request handling by eliminating the URL object creation in favor of a more streamlined approach.

Poem

I'm a little rabbit, hopping with delight,
In a code garden where refactors shine bright.
URL checks hopped away, no more twists and twirls,
Handler's direct response now unfurls.
Code flows smooth as a burrow's secret run,
A whimsical march to a cleaner code sun!
🐇✨

✨ 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.
    • 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 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.

@codecov
Copy link
Copy Markdown

codecov bot commented Mar 22, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

📢 Thoughts on this report? Let us know!

@pkg-pr-new
Copy link
Copy Markdown

pkg-pr-new bot commented Mar 22, 2025

Open in Stackblitz

More templates

@orpc/arktype

npm i https://pkg.pr.new/@orpc/arktype@285

@orpc/client

npm i https://pkg.pr.new/@orpc/client@285

@orpc/contract

npm i https://pkg.pr.new/@orpc/contract@285

@orpc/openapi

npm i https://pkg.pr.new/@orpc/openapi@285

@orpc/openapi-client

npm i https://pkg.pr.new/@orpc/openapi-client@285

@orpc/react-query

npm i https://pkg.pr.new/@orpc/react-query@285

@orpc/server

npm i https://pkg.pr.new/@orpc/server@285

@orpc/solid-query

npm i https://pkg.pr.new/@orpc/solid-query@285

@orpc/shared

npm i https://pkg.pr.new/@orpc/shared@285

@orpc/standard-server

npm i https://pkg.pr.new/@orpc/standard-server@285

@orpc/standard-server-fetch

npm i https://pkg.pr.new/@orpc/standard-server-fetch@285

@orpc/standard-server-node

npm i https://pkg.pr.new/@orpc/standard-server-node@285

@orpc/svelte-query

npm i https://pkg.pr.new/@orpc/svelte-query@285

@orpc/valibot

npm i https://pkg.pr.new/@orpc/valibot@285

@orpc/vue-colada

npm i https://pkg.pr.new/@orpc/vue-colada@285

@orpc/vue-query

npm i https://pkg.pr.new/@orpc/vue-query@285

@orpc/zod

npm i https://pkg.pr.new/@orpc/zod@285

commit: d05ce0e

Copy link
Copy Markdown

@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 (1)
packages/server/src/adapters/standard/handler.ts (1)

81-91: Improved request prefix handling with early return pattern.

The new implementation correctly checks if a prefix exists and whether the URL pathname starts with it before proceeding, returning early if there's no match. This aligns with the PR objective of automating prefix checking within handlers, making the code more robust and reducing the burden on developers.

The pathname construction is now more explicit, either replacing the prefix in the URL pathname or using the pathname as is, which improves clarity.

Consider adding a brief comment explaining the purpose of this prefix check and the expected behavior when the prefix doesn't match. Also, the regex pattern for removing leading and trailing slashes could be extracted to a named constant for better readability.

+ // Check if the request URL starts with the specified prefix
  if (prefix && !url.pathname.startsWith(prefix)) {
    return { matched: false, response: undefined }
  }

+ // Construct the pathname by removing the prefix if it exists
  const pathname = prefix
    ? url.pathname.replace(prefix, '')
    : url.pathname

+ // Format the pathname by removing leading and trailing slashes
+ const PATH_NORMALIZER = /^\/|\/$/g
  const match = await this.matcher.match(method, `/${pathname.replace(/^\/|\/$/g, '')}`)
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3e1c2e9 and d05ce0e.

📒 Files selected for processing (13)
  • apps/content/docs/integrations/bun.md (1 hunks)
  • apps/content/docs/integrations/cloudflare-workers.md (1 hunks)
  • apps/content/docs/integrations/deno.md (1 hunks)
  • apps/content/docs/integrations/fetch-server.md (1 hunks)
  • apps/content/docs/integrations/node.md (2 hunks)
  • apps/content/docs/openapi/openapi-handler.md (1 hunks)
  • apps/content/docs/openapi/scalar.md (1 hunks)
  • apps/content/docs/rpc-handler.md (1 hunks)
  • packages/client/src/adapters/standard/rpc-link-codec.ts (2 hunks)
  • packages/server/src/adapters/standard/handler.test.ts (1 hunks)
  • packages/server/src/adapters/standard/handler.ts (2 hunks)
  • packages/shared/src/index.ts (1 hunks)
  • playgrounds/contract-first/src/main.ts (1 hunks)
🧰 Additional context used
🧬 Code Definitions (1)
packages/client/src/adapters/standard/rpc-link-codec.ts (1)
packages/client/src/adapters/standard/link.ts (1) (1)
  • path (41-53)
🔇 Additional comments (18)
packages/client/src/adapters/standard/rpc-link-codec.ts (2)

5-5: Import statement updated to remove trim function.

The trim function has been removed from the import statement as it's no longer needed after the URL handling refactoring.


82-82: URL trimming approach improved using regex.

The code now uses a regular expression to remove trailing slashes instead of the trim utility function. The regex replace(/\/$/, '') efficiently removes only a trailing slash if present.

apps/content/docs/integrations/fetch-server.md (2)

23-26: Handler now handles prefix checking internally.

The handler.handle method now accepts a prefix parameter which handles the URL prefix checking internally, eliminating the need for manual URL parsing and prefix validation.


28-30: Simplified response handling using matched flag.

The code now uses the matched boolean returned by the handler to determine if the request matches the RPC endpoint, simplifying the control flow.

packages/shared/src/index.ts (1)

11-11: Removed trim function from exports.

The trim function has been removed from the exports since it's no longer used after the URL handling refactoring in the client adapter. This helps keep the API surface clean.

apps/content/docs/integrations/node.md (3)

28-31: HTTP server now uses handler's prefix checking.

Similar to other integrations, the Node HTTP server now relies on the handler's internal prefix checking mechanism rather than manually checking the URL.


33-35: Simplified response flow using matched flag.

The code now uses the matched boolean to determine if the request was handled, improving readability and consistency with other integrations.


65-72: HTTP2 server implementation updated consistently.

The HTTP2 server implementation has been updated with the same pattern as the HTTP server, ensuring consistency across different server types. The prefix checking is now handled by the handler internally.

apps/content/docs/integrations/cloudflare-workers.md (1)

24-31: Implementation looks good and follows the PR objective.

The code has been refactored to simplify the request handling logic by leveraging the handler's built-in prefix checking. This eliminates the need for manual URL parsing and pathname validation, resulting in cleaner, more maintainable code.

apps/content/docs/integrations/deno.md (1)

23-29: Implementation correctly handles request routing.

The code has been simplified to use the handler's automatic prefix checking capability. This approach is consistent with the changes in other integration files and aligns with the PR objective of moving prefix validation into handlers.

packages/server/src/adapters/standard/handler.test.ts (1)

355-371: Good test addition for prefix validation.

This test case verifies a critical aspect of the new feature - ensuring that the handler properly checks the URL prefix before attempting to match a route. The test correctly validates that when an invalid prefix is provided, the handler returns { matched: false, response: undefined }.

apps/content/docs/openapi/openapi-handler.md (1)

80-86: Implementation is consistent with other handler changes.

The OpenAPI handler code has been refactored to use the same pattern as other integration examples, leveraging the handler's built-in prefix checking. This ensures a consistent approach across all handlers and documentation.

apps/content/docs/integrations/bun.md (1)

24-27: LGTM! Code refactoring improves handler usage

The integration now directly uses the handler's built-in prefix matching capability instead of manually checking URL paths. This simplifies the code and aligns with the PR objective of automating prefix checks in handlers.

Also applies to: 29-31

apps/content/docs/rpc-handler.md (1)

58-61: LGTM! Simplified request handling logic

The refactoring properly leverages the handler's built-in prefix matching capability, eliminating the need for manual URL parsing and prefix validation. This results in cleaner, more maintainable code.

Also applies to: 63-65

apps/content/docs/openapi/scalar.md (1)

33-35: LGTM! Streamlined OpenAPIHandler integration

The refactoring simplifies the request handling flow by utilizing the handler's built-in prefix matching capability, improving code clarity and maintainability.

Also applies to: 37-39

playgrounds/contract-first/src/main.ts (2)

41-44: LGTM! Improved API request handling

The refactoring properly utilizes the OpenAPIHandler's built-in prefix matching capability, resulting in cleaner and more maintainable code.

Also applies to: 46-48


50-53: LGTM! Improved RPC request handling

The refactoring properly utilizes the RPCHandler's built-in prefix matching capability, resulting in cleaner and more maintainable code. This approach consistently applies the same pattern used for the OpenAPIHandler above.

Also applies to: 55-57

packages/server/src/adapters/standard/handler.ts (1)

10-10: Import statement updated to remove unused 'trim' function.

The import statement now only includes the intercept function from @orpc/shared, removing the previously imported trim function which is no longer used after the refactoring.

@dinwwwh
Copy link
Copy Markdown
Member Author

dinwwwh commented Mar 25, 2025

Conflict

@dinwwwh dinwwwh closed this Mar 25, 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.

1 participant