refactor: 重构ORPC模块结构与路由实现

- 更新导入路径以正确引用合约文件并重构导出结构。
- 使用 os 实例替换手动实现的 ORPC 处理函数,统一通过生成的合约接口调用并集成数据库中间件。
- 使用服务器实例的路由功能替换原有的路由定义。
- 添加ORPC服务器实现,基于合约定义并指定空上下文类型。
- 修正导入路径,将 './contracts' 更新为 './contract' 以匹配实际文件路径。
This commit is contained in:
2026-01-18 03:44:07 +08:00
parent ae36575256
commit 6092d82f34
5 changed files with 18 additions and 10 deletions

View File

@@ -1,4 +1,4 @@
import { todoContract } from './todo'
import { todoContract } from './contracts/todo'
export const contract = {
todo: todoContract,

View File

@@ -1,10 +1,10 @@
import { implement, ORPCError } from '@orpc/server'
import { ORPCError } from '@orpc/server'
import { eq } from 'drizzle-orm'
import { todoTable } from '@/db/schema'
import { dbProvider } from '@/orpc/middlewares'
import { contract } from '../contracts'
import { os } from '@/orpc/server'
export const list = implement(contract.todo.list)
export const list = os.todo.list
.use(dbProvider)
.handler(async ({ context }) => {
const todos = await context.db.query.todoTable.findMany({
@@ -13,7 +13,7 @@ export const list = implement(contract.todo.list)
return todos
})
export const create = implement(contract.todo.create)
export const create = os.todo.create
.use(dbProvider)
.handler(async ({ context, input }) => {
const [newTodo] = await context.db
@@ -28,7 +28,7 @@ export const create = implement(contract.todo.create)
return newTodo
})
export const update = implement(contract.todo.update)
export const update = os.todo.update
.use(dbProvider)
.handler(async ({ context, input }) => {
const [updatedTodo] = await context.db
@@ -44,7 +44,7 @@ export const update = implement(contract.todo.update)
return updatedTodo
})
export const remove = implement(contract.todo.remove)
export const remove = os.todo.remove
.use(dbProvider)
.handler(async ({ context, input }) => {
await context.db.delete(todoTable).where(eq(todoTable.id, input.id))

View File

@@ -1,5 +1,6 @@
import * as todo from './handlers/todo'
import { os } from './server'
export const router = {
export const router = os.router({
todo,
}
})

7
src/orpc/server.ts Normal file
View File

@@ -0,0 +1,7 @@
import { implement } from '@orpc/server'
import { contract } from './contract'
// biome-ignore lint/complexity/noBannedTypes: 暂无 context
export type ORPCContext = {}
export const os = implement(contract).$context<ORPCContext>()

View File

@@ -3,7 +3,7 @@ import type {
InferContractRouterInputs,
InferContractRouterOutputs,
} from '@orpc/contract'
import type { contract } from './contracts'
import type { contract } from './contract'
export type Contract = typeof contract
export type RouterClient = ContractRouterClient<Contract>