Skip to content

feat(server): check prefix inside handlers#295

Merged
dinwwwh merged 2 commits intomainfrom
feat/server/check-prefix-inside-handler-2
Mar 25, 2025
Merged

feat(server): check prefix inside handlers#295
dinwwwh merged 2 commits intomainfrom
feat/server/check-prefix-inside-handler-2

Conversation

@dinwwwh
Copy link
Copy Markdown
Member

@dinwwwh dinwwwh commented Mar 25, 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 integrations to ensure consistent API and RPC responses, including reliable handling of unmatched requests.
  • Tests
    • Added coverage to verify proper behavior when an invalid request prefix is provided.
  • Chores
    • Updated URL formatting to standardize trailing slash removal and removed an unused utility for cleaner maintenance.

@vercel
Copy link
Copy Markdown

vercel Bot commented Mar 25, 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 25, 2025 2:34pm

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Mar 25, 2025

Walkthrough

This pull request refactors the request handling logic across multiple integrations by removing the creation of intermediate URL objects and the associated pathname checks. Instead, the code now directly calls the handler’s method and inspects the returned matched flag and response value to determine the outcome. Additionally, some helper functions have been replaced or removed, and tests have been updated to cover the new prefix handling logic.

Changes

File(s) Summary of Changes
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/openapi/openapi-handler.md
apps/content/docs/openapi/scalar.md
apps/content/docs/rpc-handler.md
Removed creation of URL object and pathname prefix checks. Now directly calls handler.handle and conditionally returns the response or a 404.
apps/content/docs/integrations/node.md Eliminated the initial conditional check (req.url.startsWith('/rpc')) in createServer/createSecureServer, calling handler.handle directly instead.
packages/client/src/adapters/standard/rpc-link-codec.ts Replaced use of the trim function with a regex replacement (.replace(/\/$/, '')) to remove a trailing slash from the base URL.
packages/server/src/adapters/standard/handler.ts
packages/server/src/adapters/standard/handler.test.ts
Updated request handling logic by adding an early exit if the URL prefix does not match and restructured the pathname derivation. A new test has been added to verify prefix checking.
packages/shared/src/index.ts Removed the export of the trim function from the 'radash' library.
playgrounds/contract-first/src/main.ts Streamlined the API and RPC request dispatcher by directly awaiting the handle method calls and checking the resulting matched values.

Sequence Diagram(s)

sequenceDiagram
    participant C as Client
    participant S as Server (Fetch Function)
    participant H as Handler

    C->>S: Send request
    S->>H: Call handler.handle(request)
    H-->>S: Return {matched, response}
    alt matched is true
      S->>C: Return response
    else
      S->>C: Return 404 response
    end
Loading

Possibly related PRs

  • unnoq/orpc#290: Refactors the fetch method to remove unnecessary conditional checks and directly utilize the handler’s results.
  • unnoq/orpc#267: Simplifies the request handling logic by eliminating redundant checks in the fetch method.
  • unnoq/orpc#236: Streamlines request handling by removing intermediary URL and pathname checks, similar to the changes in this PR.

Poem

Hoppin’ through code with ears so keen,
I trim the clutter from each routine.
No more URL detours in my maze,
Direct calls set my heart ablaze.
With each refactor, I dance in delight –
A rabbit’s cheer in pure code light! 🐰

✨ 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 plan to trigger planning for file edits and PR creation.
  • @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 25, 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 25, 2025

Open in Stackblitz

More templates

@orpc/arktype

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

@orpc/client

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

@orpc/openapi

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

@orpc/contract

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

@orpc/openapi-client

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

@orpc/react-query

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

@orpc/server

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

@orpc/shared

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

@orpc/solid-query

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

@orpc/standard-server

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

@orpc/standard-server-fetch

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

@orpc/standard-server-node

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

@orpc/svelte-query

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

@orpc/valibot

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

@orpc/vue-colada

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

@orpc/vue-query

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

@orpc/zod

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

commit: f6a3c8e

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/client/src/adapters/standard/rpc-link-codec.ts (1)

82-82: Regex replacement for trim works, but consider handling multiple slashes

The regular expression replacement for the trim function works well for removing a single trailing slash. However, the current regex only handles a single trailing slash, while trim might have handled multiple consecutive slashes.

Consider using /\/+$/ to handle multiple consecutive trailing slashes:

-const url = new URL(`${baseUrl.toString().replace(/\/$/, '')}/${path.map(encodeURIComponent).join('/')}`)
+const url = new URL(`${baseUrl.toString().replace(/\/+$/, '')}/${path.map(encodeURIComponent).join('/')}`)
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6896c4f and f6a3c8e.

📒 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)
  • path (44-56)
🔇 Additional comments (16)
packages/server/src/adapters/standard/handler.test.ts (1)

344-360: Good test addition for prefix checking!

This new test case properly verifies that the handler checks the URL prefix before attempting to match routes. It ensures the handler returns { matched: false, response: undefined } when the URL doesn't match the specified prefix.

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

27-35: Simplified request handling looks good!

The code now directly calls handler.handle with the prefix specified as an option, removing the need for manual prefix checking. This aligns with the PR objective of automating prefix checking inside handlers.


65-72: Consistent implementation for HTTP/2 - LGTM!

The HTTP/2 implementation follows the same pattern as the HTTP implementation, correctly passing the prefix as an option to the handler.

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

13-13: LGTM: Removing unused trim function export

Removing the trim function from exports makes sense since it's no longer used in the codebase, as evidenced by the changes in rpc-link-codec.ts.

packages/client/src/adapters/standard/rpc-link-codec.ts (1)

5-5: LGTM: Import updated to match exports

Correctly updated import to match the change in exported functions from @orpc/shared.

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

80-87: Simplified request handling with automatic prefix checking.

The code now delegates the prefix checking to the handler instead of manually checking the URL path. This improves code clarity and reduces the amount of boilerplate required for each integration.

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

58-65: Improved handler logic with automatic prefix checking.

The implementation now correctly leverages the handler's built-in prefix checking capability by passing '/rpc' as a parameter, simplifying the code flow and making the example more maintainable.

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

33-39: Streamlined request handling with prefix injection.

The code now leverages the handler's built-in prefix checking by passing '/api' as a parameter rather than performing manual URL pathname checks. This creates a more consistent pattern across the documentation.

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

24-31: Enhanced Cloudflare Workers integration with automatic prefix checking.

The implementation has been streamlined by leveraging the handler's built-in prefix checking capability instead of manual URL parsing, making the integration example more concise and easier to follow.

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

41-48: Improved request handling for OpenAPI endpoints.

The code now directly handles the OpenAPI requests with built-in prefix checking using '/api' as the parameter, eliminating the need for manual URL parsing and making the control flow cleaner.


50-57: Enhanced RPC request handling with automatic prefix checking.

Similar to the OpenAPI handler implementation, the RPC request handling now leverages the built-in prefix checking mechanism, creating a consistent pattern across both handlers.

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

22-30: Great refactoring of request handling logic!

The implementation is now cleaner and more maintainable. By having the handler automatically check for the prefix, you've reduced boilerplate code and made the control flow more explicit through the matched flag. This is a nice DX improvement that aligns well with the PR's objectives.

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

23-30: Consistent implementation with other integrations

The changes properly align with the same pattern applied to other integrations, providing a consistent developer experience. The simplified request handling with automatic prefix checking reduces code verbosity and makes the control flow clearer.

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

22-30: Well-implemented consistent pattern

The changes maintain the same clean pattern used in other integrations, delegating prefix checking to the handler rather than manually parsing URLs. This consistency across integrations (Fetch, Bun, Deno) provides a unified developer experience and simplifies the framework's usage.

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

9-9: Simplified imports

Good cleanup by removing the unused trim import. This keeps the imports clean and reduces unnecessary dependencies.


88-96: Well-implemented prefix handling logic

The implementation of prefix checking is clean and efficient:

  1. The early return for non-matching prefixes is a good performance optimization
  2. The pathname construction logic is clear and explicit
  3. Path normalization ensures consistent handling regardless of leading/trailing slashes

This is the core change that enables the simplified integration code seen in the documentation files. The pattern of returning { matched, response } provides a clear API for consumers.

@dinwwwh dinwwwh merged commit d3b4900 into main Mar 25, 2025
8 checks 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.

1 participant