32 lines
967 B
TypeScript
32 lines
967 B
TypeScript
import { rename } from "node:fs/promises";
|
|
import { resolve } from "node:path";
|
|
import { z } from "zod";
|
|
|
|
const paramsSchema = z.object({
|
|
name: z.string().min(1).regex(/^[^/\\]+$/, "Invalid filename"),
|
|
});
|
|
|
|
const bodySchema = z.object({
|
|
name: z.string().min(1).regex(/^[^/\\]+$/, "Invalid filename"),
|
|
});
|
|
|
|
export default defineEventHandler(async (event) => {
|
|
const params = await getValidatedRouterParams(event, paramsSchema.parse);
|
|
const body = await readValidatedBody(event, bodySchema.parse);
|
|
|
|
const dir = resolve(process.cwd(), "public/files");
|
|
const oldPath = resolve(dir, params.name);
|
|
const newPath = resolve(dir, body.name);
|
|
|
|
if (!oldPath.startsWith(dir + "/") || !newPath.startsWith(dir + "/")) {
|
|
throw createError({ statusCode: 400, message: "Invalid filename" });
|
|
}
|
|
|
|
try {
|
|
await rename(oldPath, newPath);
|
|
return { name: body.name };
|
|
} catch {
|
|
throw createError({ statusCode: 404, message: "File not found" });
|
|
}
|
|
});
|