diff --git a/src/db/index.ts b/src/db/index.ts index 34e985c..4da3faa 100644 --- a/src/db/index.ts +++ b/src/db/index.ts @@ -11,5 +11,3 @@ export function createDb() { schema, }) } - -export const db = createDb() diff --git a/src/orpc/handlers/todo.ts b/src/orpc/handlers/todo.ts index 2f7a92d..fc12752 100644 --- a/src/orpc/handlers/todo.ts +++ b/src/orpc/handlers/todo.ts @@ -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)) }) diff --git a/src/orpc/middlewares/db.ts b/src/orpc/middlewares/db.ts new file mode 100644 index 0000000..01d55ce --- /dev/null +++ b/src/orpc/middlewares/db.ts @@ -0,0 +1,29 @@ +import { os } from '@orpc/server' +import { createDb } from '@/db' + +const IS_SERVERLESS = false // TODO: 这里需要优化 + +let globalDb: ReturnType | null = null + +function getDb() { + if (IS_SERVERLESS) { + return createDb() + } + + if (!globalDb) { + globalDb = createDb() + } + + return globalDb +} + +export const dbProvider = os.middleware(async ({ context, next }) => { + const db = getDb() + + return next({ + context: { + ...context, + db, + }, + }) +}) diff --git a/src/orpc/middlewares/index.ts b/src/orpc/middlewares/index.ts new file mode 100644 index 0000000..1beb455 --- /dev/null +++ b/src/orpc/middlewares/index.ts @@ -0,0 +1 @@ +export * from './db'