Skip to content

Commit

Permalink
strict contract when implement
Browse files Browse the repository at this point in the history
  • Loading branch information
unnoq committed Jan 20, 2025
1 parent 861256a commit 59f608b
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 6 deletions.
18 changes: 12 additions & 6 deletions packages/server/src/router-implementer.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
import type { ContractRouter } from '@orpc/contract'
import type { ConflictContextGuard, Context, TypeCurrentContext, TypeInitialContext } from './context'
import type { FlattenLazy } from './lazy'
import type { Middleware } from './middleware'
import type { Router } from './router'
import { flatLazy, type FlattenLazy, lazy } from './lazy'
import type { Router, RouterToContract } from './router'
import { flatLazy, lazy } from './lazy'
import { type UnshiftedMiddlewaresRouter, unshiftMiddlewaresRouter } from './router-utils'

export type EqualContractGuard<TContract extends ContractRouter<any>, TRouter extends Router<any, TContract>> =
TContract extends RouterToContract<TRouter> ? unknown : never

export interface RouterImplementerDef<
TInitialContext extends Context,
TCurrentContext extends Context,
Expand Down Expand Up @@ -48,13 +52,15 @@ export class RouterImplementer<

router<U extends Router<TCurrentContext, TContract>>(
router: U,
): UnshiftedMiddlewaresRouter<U, TInitialContext> {
return unshiftMiddlewaresRouter(router, this['~orpc'])
): EqualContractGuard<TContract, U> & UnshiftedMiddlewaresRouter<U, TInitialContext> {
const applied = unshiftMiddlewaresRouter(router, this['~orpc'])
return applied as typeof applied & EqualContractGuard<TContract, U>
}

lazy<U extends Router<TCurrentContext, TContract>>(
loader: () => Promise<{ default: U }>,
): UnshiftedMiddlewaresRouter<FlattenLazy<U>, TInitialContext> {
return unshiftMiddlewaresRouter(flatLazy(lazy(loader)), this['~orpc'])
): EqualContractGuard<TContract, U> & UnshiftedMiddlewaresRouter<FlattenLazy<U>, TInitialContext> {
const applied = unshiftMiddlewaresRouter(flatLazy(lazy(loader)), this['~orpc'])
return applied as typeof applied & EqualContractGuard<TContract, U>
}
}
9 changes: 9 additions & 0 deletions packages/server/src/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,15 @@ export type Router<
}
>

export type RouterToContract<T extends Router<any, any>> =
T extends Lazy<infer U extends Router<any, any>>
? RouterToContract<U>
: T extends Procedure<any, any, infer UInputSchema, infer UOutputSchema, any, infer UErrorMap, infer URoute>
? ContractProcedure<UInputSchema, UOutputSchema, UErrorMap, URoute>
: {
[K in keyof T]: T[K] extends Router<any, any> ? RouterToContract<T[K]> : never
}

export type ANY_ROUTER = Router<any, any>

export type InferRouterInputs<T extends ANY_ROUTER> =
Expand Down

0 comments on commit 59f608b

Please sign in to comment.