-
-
Notifications
You must be signed in to change notification settings - Fork 141
feat(contract): inferRPCMethodFromContractRouter & minifyContractRouter #578
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
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,51 @@ | ||
| --- | ||
| title: Router to Contract | ||
| description: Learn how to convert a router into a contract, safely export it, and prevent exposing internal details to the client. | ||
| --- | ||
|
|
||
| # Router to Contract | ||
|
|
||
| A normal [router](/docs/router) works as a contract router as long as it does not include a [lazy router](/docs/router#lazy-router). This guide not only shows you how to **unlazy** a router to make it compatible with contracts, but also how to **minify** it and **prevent internal business logic from being exposed to the client**. | ||
|
|
||
| ## Unlazy the Router | ||
|
|
||
| If your router includes a [lazy router](/docs/router#lazy-router), you need to fully resolve it to make it compatible with contract. | ||
|
|
||
| ```ts | ||
| import { unlazyRouter } from '@orpc/server' | ||
|
|
||
| const resolvedRouter = await unlazyRouter(router) | ||
| ``` | ||
|
|
||
| ## Minify & Export the Contract Router for the Client | ||
|
|
||
| Sometimes, you'll need to import the contract on the client - for example, to use [OpenAPILink](/docs/openapi/client/openapi-link) or define request methods in [RPCLink](/docs/client/rpc-link#custom-request-method). | ||
|
|
||
| If you're using [Contract First](/docs/contract-first/define-contract), this is safe: your contract is already lightweight and free of business logic. | ||
|
|
||
| However, if you're deriving the contract from a [router](/docs/router), importing it directly can be heavy and may leak internal logic. To prevent this, follow the steps below to safely minify and export your contract. | ||
|
|
||
| 1. **Minify the Contract Router and Export to JSON** | ||
|
|
||
| ```ts | ||
| import fs from 'node:fs' | ||
| import { minifyContractRouter } from '@orpc/contract' | ||
|
|
||
| const minifiedRouter = minifyContractRouter(router) | ||
|
|
||
| fs.writeFileSync('./contract.json', JSON.stringify(minifiedRouter)) | ||
| ``` | ||
|
|
||
| ::: warning | ||
| `minifyContractRouter` preserves only the metadata and routing information necessary for the client, all other data will be stripped out. | ||
| ::: | ||
|
|
||
| 2. **Import the Contract JSON on the Client Side** | ||
|
|
||
| ```ts | ||
| import contract from './contract.json' // [!code highlight] | ||
|
|
||
| const link = new OpenAPILink(contract as any, { | ||
| url: 'http://localhost:3000/api', | ||
| }) | ||
| ``` |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,10 @@ | ||
| import { RPCLink } from '@orpc/client/fetch' | ||
| import { router as contract } from '../tests/shared' | ||
| import { inferRPCMethodFromContractRouter } from './link-utils' | ||
|
|
||
| it('inferRPCMethodFromContractRouter', () => { | ||
| const link = new RPCLink({ | ||
| url: 'http://localhost:3000/rpc', | ||
| method: inferRPCMethodFromContractRouter(contract), | ||
| }) | ||
| }) | ||
dinwwwh marked this conversation as resolved.
Show resolved
Hide resolved
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| import { oc } from './builder' | ||
| import { inferRPCMethodFromContractRouter } from './link-utils' | ||
| import { minifyContractRouter } from './router-utils' | ||
|
|
||
| it('inferRPCMethodFromContractRouter', () => { | ||
| const method = inferRPCMethodFromContractRouter(minifyContractRouter({ | ||
| head: oc.route({ method: 'HEAD' }), | ||
| get: oc.route({ method: 'GET' }), | ||
| post: oc.route({}), | ||
| nested: { | ||
| get: oc.route({ method: 'GET' }), | ||
| delete: oc.route({ method: 'DELETE' }), | ||
| }, | ||
| })) | ||
|
|
||
| expect(method({}, ['head'])).toBe('GET') | ||
| expect(method({}, ['get'])).toBe('GET') | ||
| expect(method({}, ['post'])).toBe('POST') | ||
| expect(method({}, ['nested', 'get'])).toBe('GET') | ||
| expect(method({}, ['nested', 'delete'])).toBe('DELETE') | ||
|
|
||
| expect(() => method({}, ['nested', 'not-exist'])).toThrow(/No valid procedure found at path/) | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,27 @@ | ||
| import type { HTTPMethod } from '@orpc/client' | ||
| import type { AnyContractRouter } from './router' | ||
| import { get } from '@orpc/shared' | ||
| import { fallbackContractConfig } from './config' | ||
| import { isContractProcedure } from './procedure' | ||
|
|
||
| /** | ||
| * Help RPCLink automatically send requests using the specified HTTP method in the contract. | ||
| * | ||
| * @see {@link https://orpc.unnoq.com/docs/client/rpc-link#custom-request-method RPCLink Custom Request Method} | ||
| */ | ||
| export function inferRPCMethodFromContractRouter(contract: AnyContractRouter): (options: unknown, path: readonly string[]) => Exclude<HTTPMethod, 'HEAD'> { | ||
| return (_, path) => { | ||
| const procedure = get(contract, path) | ||
|
|
||
| if (!isContractProcedure(procedure)) { | ||
| throw new Error( | ||
| `[inferRPCMethodFromContractRouter] No valid procedure found at path "${path.join('.')}". ` | ||
| + `This may happen when the contract router is not properly configured.`, | ||
| ) | ||
| } | ||
|
|
||
| const method = fallbackContractConfig('defaultMethod', procedure['~orpc'].route.method) | ||
|
|
||
| return method === 'HEAD' ? 'GET' : method | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.