74 lines
1.8 KiB
TypeScript
74 lines
1.8 KiB
TypeScript
import express, { Request, Response } from "express";
|
|
import cors from "cors";
|
|
import fs from "fs";
|
|
import path from "path";
|
|
|
|
const app = express();
|
|
const PORT = 3000;
|
|
const RECIPES_DIR = path.join(__dirname, "recipes");
|
|
|
|
app.use(cors());
|
|
app.use(express.json());
|
|
|
|
app.post("/addRecipe", (req: Request, res: Response) => {
|
|
const { title, recipe } = req.body;
|
|
|
|
if (!title || !recipe) {
|
|
return res.status(400).json({ error: "Title and recipe text are required" });
|
|
}
|
|
|
|
const filename = `${title.replace(/\s+/g, "_")}.md`;
|
|
const filepath = path.join(RECIPES_DIR, filename);
|
|
|
|
fs.writeFile(filepath, recipe, (err) => {
|
|
if (err) {
|
|
return res.status(500).json({ error: "Failed to save recipe" });
|
|
}
|
|
res.status(200).json({ message: "Recipe saved successfully" });
|
|
});
|
|
});
|
|
|
|
app.get("/loadRecipes", (req, res) => {
|
|
fs.readdir(RECIPES_DIR, (err, files) => {
|
|
if (err) {
|
|
console.error("Error reading directory:", err);
|
|
return res.status(500).json({ message: "Failed to read recipes" });
|
|
}
|
|
|
|
const recipes: object[] = [];
|
|
|
|
let filesRead = 0;
|
|
if (files.length === 0) return res.json([]);
|
|
|
|
files.forEach((file) => {
|
|
const filePath = path.join(RECIPES_DIR, file);
|
|
|
|
fs.readFile(filePath, "utf8", (err, data) => {
|
|
filesRead++;
|
|
if (!err) {
|
|
try {
|
|
const parsed = JSON.parse(data);
|
|
recipes.push(parsed);
|
|
} catch (e) {
|
|
console.warn("Invalid JSON in file:", file);
|
|
}
|
|
}
|
|
|
|
if (filesRead === files.length) {
|
|
res.json(recipes);
|
|
}
|
|
});
|
|
});
|
|
});
|
|
});
|
|
|
|
// Nur starten, wenn die Datei direkt ausgeführt wird (nicht importiert wird)
|
|
if (require.main === module) {
|
|
app.listen(PORT, () => {
|
|
console.log(`Server is running on http://localhost:${PORT}`);
|
|
});
|
|
}
|
|
|
|
// Export für andere Dateien
|
|
export default app;
|