-
-
Notifications
You must be signed in to change notification settings - Fork 126
docs: add example of type-safe error in middleware #1306
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
base: main
Are you sure you want to change the base?
docs: add example of type-safe error in middleware #1306
Conversation
|
Note Other AI code review bot(s) detectedCodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review. WalkthroughAdds UNAUTHORIZED error specs to protected routes, introduces an AuthContext and authMiddleware that enforces those errors, rewires ORPC to use the middleware for authenticated routes, updates a handler signature, and adds documentation + a navigation entry for protected procedures. Changes
Sequence Diagram(s)sequenceDiagram
participant Client
participant ORPC as ORPC Server
participant AuthMW as authMiddleware
participant Handler as Route Handler
participant Contract as Contract Errors
Client->>ORPC: call protected procedure
ORPC->>AuthMW: invoke middleware with context
AuthMW->>Contract: verify UNAUTHORIZED declared (type-narrow)
alt context.user missing
AuthMW->>Contract: throw UNAUTHORIZED
Contract-->>Client: UNAUTHORIZED error
else context.user present
AuthMW->>Handler: forward call with enriched context
Handler-->>Client: handler response
end
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes
Possibly related PRs
Poem
Pre-merge checks and finishing touches✅ Passed checks (3 passed)
✨ Finishing touches🧪 Generate unit tests (beta)
📜 Recent review detailsConfiguration used: defaults Review profile: CHILL Plan: Pro 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
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. Comment |
Summary of ChangesHello @fernando-yaeda, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed! This pull request introduces a robust example of type-safe error handling within middleware, specifically for authentication. It demonstrates how to define errors directly within API contracts and then utilize these definitions in a dedicated authentication middleware. This approach enhances type safety and consistency in error responses across the application, making the API more predictable and easier to consume, addressing the request in #1282. Highlights
Using Gemini Code AssistThe full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips. Invoking Gemini You can request assistance from Gemini at any point by creating a comment using either
Customization To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a Limitations & Feedback Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here. You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension. Footnotes
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Code Review
This pull request adds a valuable example of type-safe error handling in middleware. The implementation is generally well-done, but I have a couple of suggestions to improve robustness and maintainability. The new authentication middleware currently throws a generic Error if a procedure's contract is missing the UNAUTHORIZED error, leading to a 500 Internal Server Error. I've proposed a more robust fallback that sends a proper UNAUTHORIZED response to the client. Additionally, I've noticed the UNAUTHORIZED error definition is duplicated across several files and suggest extracting it into a shared constant to improve code reuse and maintainability.
|
What about add and explain more detail on a vitpres doc page? |
Will do. Working on in right now. Also, could you share your thoughts on gemini suggestions? I'm not sure if they apply on playgrounds. |
I don't think you should follow it |
There was a problem hiding this 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 (1)
apps/content/docs/contract-first/protected-procedures.md (1)
41-61: Consider adding import statement for clarityThe code example references
implementwithout showing where it's imported from. While this keeps the example concise, beginners might benefit from seeing the complete import.🔎 Optional addition
Consider adding an import statement at the beginning of the code block:
import { implement } from '@orpc/server' export const authMiddleware = implement(contract) .$context<{ user?: { id: string, email: string } }>() .middleware(({ context, next, errors }) => { // ... rest of the code })
📜 Review details
Configuration used: defaults
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
apps/content/.vitepress/config.ts(1 hunks)apps/content/docs/contract-first/protected-procedures.md(1 hunks)
🔇 Additional comments (4)
apps/content/.vitepress/config.ts (1)
110-110: LGTM!The navigation entry is properly placed within the "Contract First" section and follows the correct format.
apps/content/docs/contract-first/protected-procedures.md (3)
10-35: LGTM!The section clearly demonstrates how to define errors in contracts using the
.errors()method. The code example is well-structured and uses TypeScript twoslash for type checking.
63-77: LGTM!The section effectively demonstrates the pattern of composing implementers using
pub.use(authMiddleware). The info box helpfully clarifies the middleware inheritance behavior.
79-96: LGTM!The examples clearly demonstrate the difference between public and protected procedures. The comment highlighting that
context.useris guaranteed to exist in protected handlers is particularly helpful for understanding the benefit of this pattern.
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
| @@ -0,0 +1,96 @@ | |||
| --- | |||
| title: Protected Procedures | |||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I want to clarify that type-safe errors are an optional pattern, not a requirement. Because of that, I don’t think the “Protected Procedure” title is suitable here, or alternatively, the content is missing the approach for handling a normal ORPCError.
I think we should roll back the changes made in the playground and only mention type-safe errors as an optional approach, rather than treating them as the default.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It makes sense.
Should I proceed with reverting the playground changes and focus on the documentation changes by adding the normal ORPCError approach as a default and adding the type-safe errors as an option?
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
More templates
@orpc/ai-sdk
@orpc/arktype
@orpc/client
@orpc/contract
@orpc/experimental-durable-iterator
@orpc/hey-api
@orpc/interop
@orpc/json-schema
@orpc/nest
@orpc/openapi
@orpc/openapi-client
@orpc/otel
@orpc/experimental-pino
@orpc/experimental-publisher
@orpc/experimental-publisher-durable-object
@orpc/experimental-ratelimit
@orpc/react
@orpc/react-query
@orpc/experimental-react-swr
@orpc/server
@orpc/shared
@orpc/solid-query
@orpc/standard-server
@orpc/standard-server-aws-lambda
@orpc/standard-server-fastify
@orpc/standard-server-fetch
@orpc/standard-server-node
@orpc/standard-server-peer
@orpc/svelte-query
@orpc/tanstack-query
@orpc/trpc
@orpc/valibot
@orpc/vue-colada
@orpc/vue-query
@orpc/zod
commit: |
Summary
Adds an example demonstrating contract-first type-safe error handling in middlewares, as requested in #1282.
Changes
using .errors()methodSummary by CodeRabbit
Bug Fixes
Chores
Refactor
Documentation
✏️ Tip: You can customize this high-level summary in your review settings.