feat: check for name conflict on file/dir move

Co-authored-by: Ona <no-reply@ona.com>
This commit is contained in:
2025-09-25 23:12:13 +00:00
parent 58775a25d9
commit 30027ae159
7 changed files with 126 additions and 30 deletions

View File

@@ -46,7 +46,8 @@ export const moveItems = authenticatedMutation({
break break
} }
} }
await Promise.all([
const [fileMoveResult, directoryMoveResult] = await Promise.all([
Files.move(ctx, { Files.move(ctx, {
targetDirectory: targetDirectoryHandle, targetDirectory: targetDirectoryHandle,
items: fileHandles, items: fileHandles,
@@ -57,6 +58,9 @@ export const moveItems = authenticatedMutation({
}), }),
]) ])
return { items, targetDirectory } return {
moved: [...directoryMoveResult.moved, ...fileMoveResult.moved],
errors: [...fileMoveResult.errors, ...directoryMoveResult.errors],
}
}, },
}) })

View File

@@ -170,7 +170,7 @@ export async function move(
targetDirectory: DirectoryHandle targetDirectory: DirectoryHandle
sourceDirectories: DirectoryHandle[] sourceDirectories: DirectoryHandle[]
}, },
): Promise<void> { ) {
const conflictCheckResults = await Promise.allSettled( const conflictCheckResults = await Promise.allSettled(
sourceDirectories.map((directory) => sourceDirectories.map((directory) =>
ctx.db.get(directory.id).then((d) => { ctx.db.get(directory.id).then((d) => {
@@ -194,25 +194,40 @@ export async function move(
), ),
) )
const errors: Err.ApplicationError[] = [] console.log(sourceDirectories)
for (const result of conflictCheckResults) {
if (result.status === "fulfilled" && result.value) { const errors: Err.ApplicationErrorData[] = []
const okDirectories: DirectoryHandle[] = []
conflictCheckResults.forEach((result, i) => {
if (result.status === "fulfilled") {
if (result.value) {
errors.push( errors.push(
Err.create( Err.createJson(
Err.Code.Conflict, Err.Code.Conflict,
`Directory ${targetDirectory.id} already contains a directory with name ${result.value.name}`, `Directory ${targetDirectory.id} already contains a directory with name ${result.value.name}`,
), ),
) )
} else {
okDirectories.push(sourceDirectories[i])
}
} else if (result.status === "rejected") { } else if (result.status === "rejected") {
errors.push(Err.create(Err.Code.Internal)) errors.push(Err.createJson(Err.Code.Internal))
}
})
const results = await Promise.allSettled(
okDirectories.map((handle) =>
ctx.db.patch(handle.id, { parentId: targetDirectory.id }),
),
)
for (const updateResult of results) {
if (updateResult.status === "rejected") {
errors.push(Err.createJson(Err.Code.Internal))
} }
} }
await Promise.all( return { moved: okDirectories, errors }
sourceDirectories.map((directory) =>
ctx.db.patch(directory.id, { parentId: targetDirectory.id }),
),
)
} }
export async function moveToTrashRecursive( export async function moveToTrashRecursive(

View File

@@ -5,11 +5,13 @@ export enum Code {
DirectoryExists = "DirectoryExists", DirectoryExists = "DirectoryExists",
DirectoryNotFound = "DirectoryNotFound", DirectoryNotFound = "DirectoryNotFound",
FileExists = "FileExists", FileExists = "FileExists",
FileNotFound = "FileNotFound",
Internal = "Internal", Internal = "Internal",
Unauthenticated = "Unauthenticated", Unauthenticated = "Unauthenticated",
} }
export type ApplicationError = ConvexError<{ code: Code; message?: string }> export type ApplicationErrorData = { code: Code; message?: string }
export type ApplicationError = ConvexError<ApplicationErrorData>
export function isApplicationError(error: unknown): error is ApplicationError { export function isApplicationError(error: unknown): error is ApplicationError {
return error instanceof ConvexError && "code" in error.data return error instanceof ConvexError && "code" in error.data
@@ -22,3 +24,11 @@ export function create(code: Code, message?: string): ApplicationError {
code === Code.Internal ? "Internal application error" : message, code === Code.Internal ? "Internal application error" : message,
}) })
} }
export function createJson(code: Code, message?: string): ApplicationErrorData {
return {
code,
message:
code === Code.Internal ? "Internal application error" : message,
}
}

View File

@@ -46,9 +46,59 @@ export async function move(
items: FileHandle[] items: FileHandle[]
}, },
) { ) {
await Promise.all( const conflictCheckResults = await Promise.allSettled(
items.map((item) => items.map((fileHandle) =>
ctx.db.patch(item.id, { directoryId: targetDirectoryHandle.id }), ctx.db.get(fileHandle.id).then((f) => {
), if (!f) {
throw Err.create(
Err.Code.FileNotFound,
`File ${fileHandle.id} not found`,
) )
} }
return ctx.db
.query("files")
.withIndex("uniqueFileInDirectory", (q) =>
q
.eq("userId", ctx.user._id)
.eq("directoryId", targetDirectoryHandle.id)
.eq("name", f.name)
.eq("deletedAt", undefined),
)
.first()
}),
),
)
const errors: Err.ApplicationErrorData[] = []
const okFiles: FileHandle[] = []
conflictCheckResults.forEach((result, i) => {
if (result.status === "fulfilled") {
if (result.value) {
errors.push(
Err.createJson(
Err.Code.Conflict,
`Directory ${targetDirectoryHandle.id} already contains a file with name ${result.value.name}`,
),
)
} else {
okFiles.push(items[i])
}
} else if (result.status === "rejected") {
errors.push(Err.createJson(Err.Code.Internal))
}
})
const results = await Promise.allSettled(
okFiles.map((handle) =>
ctx.db.patch(handle.id, { directoryId: targetDirectoryHandle.id }),
),
)
for (const updateResult of results) {
if (updateResult.status === "rejected") {
errors.push(Err.createJson(Err.Code.Internal))
}
}
return { moved: okFiles, errors }
}

View File

@@ -485,6 +485,7 @@ function FileItemRow({
return newDirectoryHandle(row.original.doc._id) return newDirectoryHandle(row.original.doc._id)
} }
}) })
draggedItems.push(source)
setDragInfo({ setDragInfo({
source, source,

View File

@@ -1,5 +1,6 @@
import { api } from "@fileone/convex/_generated/api" import { api } from "@fileone/convex/_generated/api"
import type { Doc, Id } from "@fileone/convex/_generated/dataModel" import type { Doc, Id } from "@fileone/convex/_generated/dataModel"
import * as Err from "@fileone/convex/model/error"
import type { import type {
DirectoryHandle, DirectoryHandle,
FileSystemHandle, FileSystemHandle,
@@ -44,20 +45,31 @@ export function useFileDrop({
const { mutate: moveDroppedItems } = useMutation({ const { mutate: moveDroppedItems } = useMutation({
mutationFn: useContextMutation(api.filesystem.moveItems), mutationFn: useContextMutation(api.filesystem.moveItems),
onSuccess: ({ onSuccess: ({
items, moved,
targetDirectory, errors,
}: { }: {
items: FileSystemHandle[] moved: FileSystemHandle[]
targetDirectory: Doc<"directories"> errors: Err.ApplicationErrorData[]
}) => { }) => {
toast.success( const conflictCount = errors.reduce((acc, error) => {
`${items.length} items moved to ${targetDirectory.name}`, if (error.code === Err.Code.Conflict) {
return acc + 1
}
return acc
}, 0)
if (conflictCount > 0) {
toast.warning(
`${moved.length} items moved${conflictCount > 0 ? `, ${conflictCount} conflicts` : ""}`,
) )
} else {
toast.success(`${moved.length} items moved!`)
}
}, },
}) })
const handleDrop = (_e: React.DragEvent) => { const handleDrop = (_e: React.DragEvent) => {
const dragInfo = store.get(dragInfoAtom) const dragInfo = store.get(dragInfoAtom)
console.log("dragInfo", dragInfo)
if (dragInfo && item) { if (dragInfo && item) {
moveDroppedItems({ moveDroppedItems({
targetDirectory: item, targetDirectory: item,

View File

@@ -8,6 +8,10 @@ const ERROR_MESSAGE = {
[ErrorCode.DirectoryExists]: "Directory already exists", [ErrorCode.DirectoryExists]: "Directory already exists",
[ErrorCode.FileExists]: "File already exists", [ErrorCode.FileExists]: "File already exists",
[ErrorCode.Internal]: "Internal application error", [ErrorCode.Internal]: "Internal application error",
[ErrorCode.Conflict]: "Conflict",
[ErrorCode.DirectoryNotFound]: "Directory not found",
[ErrorCode.FileNotFound]: "File not found",
[ErrorCode.Unauthenticated]: "Unauthenticated",
} as const } as const
export function formatError(error: unknown): string { export function formatError(error: unknown): string {