51 lines
1.8 KiB
TypeScript
51 lines
1.8 KiB
TypeScript
import { NextResponse } from 'next/server';
|
|
import fs from 'fs-extra';
|
|
import path from 'path';
|
|
import { BatchRenameResponse, RenameOperation, RenameResult } from '@/types';
|
|
|
|
export async function POST(request: Request) {
|
|
try {
|
|
const { albumPath, renames } = await request.json();
|
|
|
|
if (!albumPath || !(await fs.pathExists(albumPath))) {
|
|
return NextResponse.json({ error: 'Invalid album path' }, { status: 400 });
|
|
}
|
|
|
|
if (!renames || !Array.isArray(renames)) {
|
|
return NextResponse.json({ error: 'Invalid renames list' }, { status: 400 });
|
|
}
|
|
|
|
const results: RenameResult[] = [];
|
|
const errors: string[] = [];
|
|
|
|
for (const { original, newName } of renames as RenameOperation[]) {
|
|
try {
|
|
const oldPath = path.join(albumPath, original);
|
|
const newPath = path.join(albumPath, newName);
|
|
|
|
if (await fs.pathExists(oldPath)) {
|
|
await fs.rename(oldPath, newPath);
|
|
results.push({ original, newName, success: true });
|
|
} else {
|
|
errors.push(`File not found: ${original}`);
|
|
}
|
|
} catch (e) {
|
|
const errorMessage = e instanceof Error ? e.message : String(e);
|
|
errors.push(`Failed to rename ${original}: ${errorMessage}`);
|
|
}
|
|
}
|
|
|
|
const response: BatchRenameResponse = {
|
|
success: errors.length === 0,
|
|
results,
|
|
errors: errors.length > 0 ? errors : undefined
|
|
};
|
|
|
|
return NextResponse.json(response);
|
|
|
|
} catch (error) {
|
|
console.error('Error executing renames:', error);
|
|
return NextResponse.json({ error: 'Failed to execute renames' }, { status: 500 });
|
|
}
|
|
}
|