refactor: 重构数据库实例管理,支持按需创建与上下文注入

- 移除默认导出的 db 实例,改为按需创建数据库实例
- 使用数据库中间件提供上下文中的数据库实例,统一通过上下文获取数据库连接并执行操作。
- 添加数据库中间件以在请求上下文中注入数据库实例,支持服务器端全局缓存和无服务器环境下的每次新建实例。
- 导出中间件模块中的数据库相关功能。
This commit is contained in:
2026-01-18 03:03:28 +08:00
parent daaa220a47
commit f38867c548
4 changed files with 44 additions and 12 deletions

View File

@@ -6,8 +6,8 @@ import {
createUpdateSchema,
} from 'drizzle-zod'
import { z } from 'zod'
import { db } from '@/db'
import { todoTable } from '@/db/schema'
import { dbProvider } from '../middlewares'
const selectSchema = createSelectSchema(todoTable)
@@ -26,8 +26,9 @@ const updateSchema = createUpdateSchema(todoTable).omit({
export const list = os
.input(z.void())
.output(z.array(selectSchema))
.handler(async () => {
const todos = await db.query.todoTable.findMany({
.use(dbProvider)
.handler(async ({ context }) => {
const todos = await context.db.query.todoTable.findMany({
orderBy: (todos, { desc }) => [desc(todos.createdAt)],
})
return todos
@@ -36,10 +37,11 @@ export const list = os
export const create = os
.input(insertSchema)
.output(selectSchema)
.handler(async ({ input }) => {
const [newTodo] = await db
.use(dbProvider)
.handler(async ({ context, input }) => {
const [newTodo] = await context.db
.insert(todoTable)
.values({ title: input.title })
.values(input)
.returning()
if (!newTodo) {
@@ -57,8 +59,9 @@ export const update = os
}),
)
.output(selectSchema)
.handler(async ({ input }) => {
const [updatedTodo] = await db
.use(dbProvider)
.handler(async ({ context, input }) => {
const [updatedTodo] = await context.db
.update(todoTable)
.set(input.data)
.where(eq(todoTable.id, input.id))
@@ -78,6 +81,7 @@ export const remove = os
}),
)
.output(z.void())
.handler(async ({ input }) => {
await db.delete(todoTable).where(eq(todoTable.id, input.id))
.use(dbProvider)
.handler(async ({ context, input }) => {
await context.db.delete(todoTable).where(eq(todoTable.id, input.id))
})