import { implement, ORPCError } from '@orpc/server' import { eq } from 'drizzle-orm' import { todoTable } from '@/db/schema' import { dbProvider } from '@/orpc/middlewares' import { contract } from '../contracts' export const list = implement(contract.todo.list) .use(dbProvider) .handler(async ({ context }) => { const todos = await context.db.query.todoTable.findMany({ orderBy: (todos, { desc }) => [desc(todos.createdAt)], }) return todos }) export const create = implement(contract.todo.create) .use(dbProvider) .handler(async ({ context, input }) => { const [newTodo] = await context.db .insert(todoTable) .values(input) .returning() if (!newTodo) { throw new ORPCError('NOT_FOUND') } return newTodo }) export const update = implement(contract.todo.update) .use(dbProvider) .handler(async ({ context, input }) => { const [updatedTodo] = await context.db .update(todoTable) .set(input.data) .where(eq(todoTable.id, input.id)) .returning() if (!updatedTodo) { throw new ORPCError('NOT_FOUND') } return updatedTodo }) export const remove = implement(contract.todo.remove) .use(dbProvider) .handler(async ({ context, input }) => { await context.db.delete(todoTable).where(eq(todoTable.id, input.id)) })