// lib/todos.ts
import { PrismaClient } from "@prisma/client";
export type Todo = {
id: string;
title: string;
done: boolean;
due?: string | null;
createdAt: Date | string;
};
const prisma = new PrismaClient();
export async function listTodos(): Promise<Todo[]> {
const todos = await prisma.todo.findMany({
orderBy: {
createdAt: "desc"
}
});
return todos.map(t => ({
...t,
createdAt: t.createdAt.toISOString(),
due: t.due ?? undefined
}));
}
export async function addTodo(title: string, due?: string): Promise<Todo> {
const todo = await prisma.todo.create({
data: {
title,
due: due ?? null
}
});
return {
...todo,
createdAt: todo.createdAt.toISOString(),
due: todo.due ?? undefined
};
}
export async function toggleTodo(id: string, done?: boolean): Promise<Todo> {
const existing = await prisma.todo.findUnique({ where: { id } });
if (!existing) throw new Error("Not found");
const todo = await prisma.todo.update({
where: { id },
data: {
done: done ?? !existing.done
}
});
return {
...todo,
createdAt: todo.createdAt.toISOString(),
due: todo.due ?? undefined
};
}
export async function removeTodo(id: string) {
await prisma.todo.delete({ where: { id } });
return { ok: true };
}
export async function searchTodos(q: string): Promise<Todo[]> {
const todos = await prisma.todo.findMany({
where: {
title: {
contains: q
}
}
});
return todos.map(t => ({
...t,
createdAt: t.createdAt.toISOString(),
due: t.due ?? undefined
}));
}