refactor(api): 删掉 db ORPC middleware,handler 直接用 db
db middleware 的存在只是为了把 db 注入到 ORPC context——这是 Cloudflare
Workers / 多租户场景的模式(db 依赖 per-request 的 env binding)。在
Bun 单进程 + 模块级 const db 下,这层中间件是纯粹的仪式:一行 import
直接拿到 db,反而更清晰。
- 删除 src/server/api/middlewares/ 整个目录(不留空脚手架,KISS)
- context.ts 去掉 DBContext 与示例注释,只留 BaseContext { headers }
作为未来 auth/tenant 等 middleware 的扩展点
- routers/todo.router.ts 不再 .use(db),handler 内直接 db.query / db.insert
需要 per-request 上下文(auth、tenant、rate-limit)时再按 ORPC 的
os.middleware 模式新增,不在此预先铺陈。
This commit is contained in:
@@ -1,18 +1,17 @@
|
||||
import { ORPCError } from '@orpc/server'
|
||||
import { eq } from 'drizzle-orm'
|
||||
import { db } from '@/server/api/middlewares'
|
||||
import { os } from '@/server/api/server'
|
||||
import { db } from '@/server/db'
|
||||
import { todoTable } from '@/server/db/schema'
|
||||
|
||||
export const list = os.todo.list.use(db).handler(async ({ context }) => {
|
||||
const todos = await context.db.query.todoTable.findMany({
|
||||
export const list = os.todo.list.handler(async () => {
|
||||
return db.query.todoTable.findMany({
|
||||
orderBy: (table, { desc }) => desc(table.createdAt),
|
||||
})
|
||||
return todos
|
||||
})
|
||||
|
||||
export const create = os.todo.create.use(db).handler(async ({ context, input }) => {
|
||||
const [newTodo] = await context.db.insert(todoTable).values(input).returning()
|
||||
export const create = os.todo.create.handler(async ({ input }) => {
|
||||
const [newTodo] = await db.insert(todoTable).values(input).returning()
|
||||
|
||||
if (!newTodo) {
|
||||
throw new ORPCError('INTERNAL_SERVER_ERROR', { message: 'Failed to create todo' })
|
||||
@@ -21,8 +20,8 @@ export const create = os.todo.create.use(db).handler(async ({ context, input })
|
||||
return newTodo
|
||||
})
|
||||
|
||||
export const update = os.todo.update.use(db).handler(async ({ context, input }) => {
|
||||
const [updatedTodo] = await context.db.update(todoTable).set(input.data).where(eq(todoTable.id, input.id)).returning()
|
||||
export const update = os.todo.update.handler(async ({ input }) => {
|
||||
const [updatedTodo] = await db.update(todoTable).set(input.data).where(eq(todoTable.id, input.id)).returning()
|
||||
|
||||
if (!updatedTodo) {
|
||||
throw new ORPCError('NOT_FOUND')
|
||||
@@ -31,8 +30,8 @@ export const update = os.todo.update.use(db).handler(async ({ context, input })
|
||||
return updatedTodo
|
||||
})
|
||||
|
||||
export const remove = os.todo.remove.use(db).handler(async ({ context, input }) => {
|
||||
const [deleted] = await context.db.delete(todoTable).where(eq(todoTable.id, input.id)).returning({ id: todoTable.id })
|
||||
export const remove = os.todo.remove.handler(async ({ input }) => {
|
||||
const [deleted] = await db.delete(todoTable).where(eq(todoTable.id, input.id)).returning({ id: todoTable.id })
|
||||
|
||||
if (!deleted) {
|
||||
throw new ORPCError('NOT_FOUND')
|
||||
|
||||
Reference in New Issue
Block a user