feat: implement template update functionality with file handling and validation

This commit is contained in:
2025-12-18 11:00:01 +01:00
parent 75b8bfd84f
commit 8b11dc5083
4 changed files with 338 additions and 45 deletions

View File

@@ -1,8 +1,116 @@
import { NextRequest, NextResponse } from "next/server";
import { unlink } from "fs/promises";
import fs from "fs";
import path from "path";
import db from "@/lib/db";
export async function PUT(request, { params }) {
try {
const { templateId } = params;
const formData = await request.formData();
const templateName = formData.get("templateName")?.toString().trim();
const description = formData.get("description")?.toString().trim();
const file = formData.get("file");
if (!templateName) {
return NextResponse.json(
{ error: "Template name is required" },
{ status: 400 }
);
}
// Check if template exists
const existingTemplate = db.prepare(`
SELECT * FROM docx_templates WHERE template_id = ? AND is_active = 1
`).get(templateId);
if (!existingTemplate) {
return NextResponse.json(
{ error: "Template not found" },
{ status: 404 }
);
}
let updateData = {
template_name: templateName,
description: description || null,
updated_at: new Date().toISOString()
};
// If a new file is provided, handle file replacement
if (file && file.size > 0) {
// Validate file type
if (!file.name.toLowerCase().endsWith('.docx')) {
return NextResponse.json(
{ error: "Only .docx files are allowed" },
{ status: 400 }
);
}
// Validate file size (10MB limit)
if (file.size > 10 * 1024 * 1024) {
return NextResponse.json(
{ error: "File size must be less than 10MB" },
{ status: 400 }
);
}
// Delete old file
try {
const oldFilePath = path.join(process.cwd(), "public", existingTemplate.file_path);
await unlink(oldFilePath);
} catch (fileError) {
console.warn("Could not delete old template file:", fileError);
}
// Save new file
const fileExtension = path.extname(file.name);
const fileName = `${Date.now()}-${Math.random().toString(36).substring(2)}${fileExtension}`;
const filePath = path.join(process.cwd(), "public", "templates", fileName);
// Ensure templates directory exists
const templatesDir = path.join(process.cwd(), "public", "templates");
try {
await fs.promises.access(templatesDir);
} catch {
await fs.promises.mkdir(templatesDir, { recursive: true });
}
const buffer = Buffer.from(await file.arrayBuffer());
await fs.promises.writeFile(filePath, buffer);
updateData.file_path = `/templates/${fileName}`;
updateData.original_filename = file.name;
updateData.file_size = file.size;
}
// Update database
const updateFields = Object.keys(updateData).map(key => `${key} = ?`).join(', ');
const updateValues = Object.values(updateData);
db.prepare(`
UPDATE docx_templates
SET ${updateFields}
WHERE template_id = ?
`).run([...updateValues, templateId]);
// Get updated template
const updatedTemplate = db.prepare(`
SELECT * FROM docx_templates WHERE template_id = ?
`).get(templateId);
return NextResponse.json(updatedTemplate);
} catch (error) {
console.error("Template update error:", error);
return NextResponse.json(
{ error: "Failed to update template" },
{ status: 500 }
);
}
}
export async function DELETE(request, { params }) {
try {
const { templateId } = params;