add automatic image renaming when recipe short_name changes
All checks were successful
CI / update (push) Successful in 1m11s
All checks were successful
CI / update (push) Successful in 1m11s
This commit is contained in:
@@ -3,6 +3,10 @@ import { Recipe } from '../../../../models/Recipe';
|
||||
import { dbConnect } from '../../../../utils/db';
|
||||
import type {RecipeModelType} from '../../../../types/types';
|
||||
import { error } from '@sveltejs/kit';
|
||||
import { rename } from 'fs/promises';
|
||||
import { join } from 'path';
|
||||
import { existsSync } from 'fs';
|
||||
|
||||
// header: use for bearer token for now
|
||||
// recipe json in body
|
||||
export const POST: RequestHandler = async ({request, locals}) => {
|
||||
@@ -14,6 +18,33 @@ export const POST: RequestHandler = async ({request, locals}) => {
|
||||
}
|
||||
else{
|
||||
await dbConnect();
|
||||
|
||||
// Check if short_name has changed
|
||||
const oldShortName = message.old_short_name;
|
||||
const newShortName = recipe_json.short_name;
|
||||
|
||||
if (oldShortName !== newShortName) {
|
||||
// Rename image files in all three directories
|
||||
const imageDirectories = ['full', 'thumb', 'placeholder'];
|
||||
const staticPath = join(process.cwd(), 'static', 'rezepte');
|
||||
|
||||
for (const dir of imageDirectories) {
|
||||
const oldPath = join(staticPath, dir, `${oldShortName}.webp`);
|
||||
const newPath = join(staticPath, dir, `${newShortName}.webp`);
|
||||
|
||||
// Only rename if the old file exists
|
||||
if (existsSync(oldPath)) {
|
||||
try {
|
||||
await rename(oldPath, newPath);
|
||||
console.log(`Renamed ${dir}/${oldShortName}.webp -> ${dir}/${newShortName}.webp`);
|
||||
} catch (err) {
|
||||
console.error(`Failed to rename ${dir}/${oldShortName}.webp:`, err);
|
||||
// Continue with other files even if one fails
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await Recipe.findOneAndUpdate({short_name: message.old_short_name }, recipe_json);
|
||||
return new Response(JSON.stringify({msg: "Edited recipe successfully"}),{
|
||||
status: 200,
|
||||
|
||||
Reference in New Issue
Block a user