Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions prisma/migrations/20260405073828_add_folder_model/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
-- AlterTable
ALTER TABLE "Document" ADD COLUMN "folderId" INTEGER;

-- AlterTable
ALTER TABLE "Media" ADD COLUMN "folderId" INTEGER;

-- CreateTable
CREATE TABLE "Folder" (
"id" SERIAL NOT NULL,
"name" TEXT NOT NULL,
"parentId" INTEGER,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,

CONSTRAINT "Folder_pkey" PRIMARY KEY ("id")
);

-- AddForeignKey
ALTER TABLE "Document" ADD CONSTRAINT "Document_folderId_fkey" FOREIGN KEY ("folderId") REFERENCES "Folder"("id") ON DELETE SET NULL ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "Media" ADD CONSTRAINT "Media_folderId_fkey" FOREIGN KEY ("folderId") REFERENCES "Folder"("id") ON DELETE SET NULL ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "Folder" ADD CONSTRAINT "Folder_parentId_fkey" FOREIGN KEY ("parentId") REFERENCES "Folder"("id") ON DELETE SET NULL ON UPDATE CASCADE;
16 changes: 16 additions & 0 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ model Document {
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
archivedAt DateTime?
folderId Int?
folder Folder? @relation("FolderDocuments", fields: [folderId], references: [id])
}

model Version {
Expand All @@ -35,6 +37,8 @@ model Media {
size Int
contentType String?
createdAt DateTime @default(now())
folderId Int?
folder Folder? @relation("FolderMedia", fields: [folderId], references: [id])
}

model Route {
Expand All @@ -44,4 +48,16 @@ model Route {
document Document @relation(fields: [documentId], references: [id], onDelete: Cascade)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}

model Folder {
id Int @id @default(autoincrement())
name String
parentId Int?
parent Folder? @relation("FolderNesting", fields: [parentId], references: [id])
children Folder[] @relation("FolderNesting")
documents Document[] @relation("FolderDocuments")
media Media[] @relation("FolderMedia")
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
108 changes: 108 additions & 0 deletions src/lib/folders/actions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
"use server";

import { prisma } from "../prisma";
import { validateName } from "../utils";
import { wrapAction } from "../utils";
import type {
ActionResult,
CreateFolderInput,
RenameFolderInput,
MoveFolderInput,
DeleteFolderInput,
} from "../types";

export async function createFolderAction(
input: CreateFolderInput
): Promise<ActionResult<{ folderId: number }>> {
return wrapAction(async () => {
const name = validateName(input.name);
const folder = await prisma.folder.create({
data: {
name,
parentId: input.parentId ?? null,
},
});
return { folderId: folder.id };
});
}

export async function renameFolderAction(
input: RenameFolderInput
): Promise<ActionResult<void>> {
return wrapAction(async () => {
const name = validateName(input.name);
await prisma.folder.update({
where: { id: input.id },
data: { name },
});
});
}

export async function moveFolderAction(
input: MoveFolderInput
): Promise<ActionResult<void>> {
return wrapAction(async () => {
if (input.parentId === input.id) {
throw new Error("A folder cannot be moved into itself");
}

if (input.parentId !== null) {
const isDescendant = await checkIsDescendant(input.parentId, input.id);
if (isDescendant) {
throw new Error("A folder cannot be moved into one of its descendants");
}
}

await prisma.folder.update({
where: { id: input.id },
data: { parentId: input.parentId },
});
});
}

export async function deleteFolderAction(
input: DeleteFolderInput
): Promise<ActionResult<void>> {
return wrapAction(async () => {
const folder = await prisma.folder.findUniqueOrThrow({
where: { id: input.id },
select: { parentId: true },
});

// Move all contents to the parent folder (or root)
await prisma.$transaction([
prisma.document.updateMany({
where: { folderId: input.id },
data: { folderId: folder.parentId },
}),
prisma.media.updateMany({
where: { folderId: input.id },
data: { folderId: folder.parentId },
}),
prisma.folder.updateMany({
where: { parentId: input.id },
data: { parentId: folder.parentId },
}),
prisma.folder.delete({
where: { id: input.id },
}),
]);
});
}

async function checkIsDescendant(
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One query per level is expensive. This is a good subject for a recursive CTE expression, although I'm not sure how Prisma handles / abstracts those. If nothing less verbose can be done, this will be okay as its not that hot of a path

candidateId: number,
ancestorId: number
): Promise<boolean> {
const result = await prisma.$queryRaw<{ id: number }[]>`
WITH RECURSIVE ancestors AS (
SELECT "id", "parentId" FROM "Folder" WHERE "id" = ${candidateId}
UNION ALL
SELECT f."id", f."parentId"
FROM "Folder" f
INNER JOIN ancestors a ON a."parentId" = f."id"
)
SELECT "id" FROM ancestors WHERE "id" = ${ancestorId} LIMIT 1
`;
return result.length > 0;
}
19 changes: 19 additions & 0 deletions src/lib/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,3 +57,22 @@ export type DuplicateDocumentInput = {
id: number;
name: string;
};

export type CreateFolderInput = {
name: string;
parentId?: number | null;
};

export type RenameFolderInput = {
id: number;
name: string;
};

export type MoveFolderInput = {
id: number;
parentId: number | null;
};

export type DeleteFolderInput = {
id: number;
};
Loading