"use server"; import { revalidatePath } from "next/cache"; import { redirect } from "next/navigation"; import { desc, eq, and } from "drizzle-orm"; import { blocksTable, INote, notesTable, usersTable } from "@/lib/db/schema"; import { requireAuth } from "./auth"; import { db } from "@/lib/db"; export async function assertNoteOwner(noteId: string): Promise { const user = await requireAuth(); const note = await db.query.notesTable.findFirst({ where: eq(notesTable.id, noteId), }); if (!note) { return false; } return note.authorId === user.id; } export async function createNote() { const user = await requireAuth(); const result = await db .insert(notesTable) .values({ authorId: user.id }) .returning({ id: usersTable.id }); const noteId = result[0].id; await db.insert(blocksTable).values({ noteId, order: 1 }); redirect(`/notes/${noteId}`); } export async function getNote(noteId: string): Promise { const user = await requireAuth(); const note = await db .select() .from(notesTable) .where(and(eq(notesTable.id, noteId), eq(notesTable.authorId, user.id))); return note.length > 0 ? note[0] : null; } export async function getNotes(): Promise { const user = await requireAuth(); return db .select() .from(notesTable) .where(eq(notesTable.authorId, user.id)) .orderBy(desc(notesTable.lastEdited)); } export async function deleteNote(formData: FormData) { const user = await requireAuth(); const noteId = formData.get("noteId") as string; await db .delete(notesTable) .where(and(eq(notesTable.id, noteId), eq(notesTable.authorId, user.id))); revalidatePath("/notes"); } export async function setTitle(noteId: string, title: string) { if (title === "") return; await db .update(notesTable) .set({ title }) .where(eq(notesTable.id, noteId)); revalidatePath("/notes/[id]", "page"); }