Define Contract
Contract-first development is a design pattern where you define the API contract before writing any implementation code. This methodology promotes a well-structured codebase that adheres to best practices and facilitates easier maintenance and evolution over time.
In oRPC, a contract specifies the rules and expectations for a procedure. It details the input, output, errors,... types and can include constraints or validations to ensure that both client and server share a clear, consistent interface.
Installation
npm install @orpc/contract@latestyarn add @orpc/contract@latestpnpm add @orpc/contract@latestbun add @orpc/contract@latestdeno add npm:@orpc/contract@latestProcedure Contract
A procedure contract in oRPC is similar to a standard procedure definition, but with extraneous APIs removed to better support contract-first development.
import { } from '@orpc/contract'
export const =
.(
.({
: .(),
: .().().(0),
}),
)
.(
.({
: .().().(0),
: .(),
: .().().(0),
}),
)Contract Router
Similar to the standard router in oRPC, the contract router organizes your defined contracts into a structured hierarchy. The contract router is streamlined by removing APIs that are not essential for contract-first development.
export const routerContract = {
example: exampleContract,
nested: {
example: exampleContract,
},
}Full Example
Below is a complete example demonstrating how to define a contract for a simple "Planet" service. This example extracted from our Getting Started guide.
export const = .({
: .().().(1),
: .(),
: .().(),
})
export const =
.(
.({
: .().().(1).(100).(),
: .().().(0).(0),
}),
)
.(.())
export const =
.(.({ : true }))
.()
export const =
.(.({ : true }))
.()
export const = {
: {
: ,
: ,
: ,
},
}Utilities
Infer Contract Router Input
import type { } from '@orpc/contract'
export type = <typeof >
type = ['planet']['find']This snippet automatically extracts the expected input types for each procedure in the router.
Infer Contract Router Output
import type { } from '@orpc/contract'
export type = <typeof >
type = ['planet']['find']Similarly, this utility infers the output types, ensuring that your application correctly handles the results from each procedure.
