Sieht gut aus und geht (noch keine Bildeingabe)

This commit is contained in:
rxf
2025-09-22 09:41:01 +02:00
parent 6f93db4a12
commit 6d04ab93c0
79 changed files with 16233 additions and 0 deletions

BIN
.DS_Store vendored

Binary file not shown.

3
.gitignore vendored Normal file
View File

@@ -0,0 +1,3 @@
JS/node_modules/
nodejs-version/backend/node_modules
nodejs-version/frontend/node_modules

209
nodejs-version/README.md Normal file
View File

@@ -0,0 +1,209 @@
# Modern Recipe Management System
A complete modern web application built with Node.js, TypeScript, React, and MySQL - a modern alternative to the existing PHP application.
## 🚀 Architecture Overview
### Backend (Node.js + TypeScript)
- **Express.js** REST API server
- **Prisma ORM** for type-safe database access
- **TypeScript** for development safety
- **MySQL** database (shared with PHP version)
- **Security** middleware (Helmet, CORS, rate limiting)
### Frontend (React + TypeScript)
- **React 18** with functional components and hooks
- **TypeScript** for type safety
- **Vite** for fast development and building
- **React Router** for client-side routing
- **Axios** for API communication
- **Modern CSS** with responsive design
### Database
- **MySQL 8.0** (same database as PHP version)
- **Prisma** schema mapped to existing tables
- **Compatible** with current PHP application
## 🌐 Live URLs
- **React Frontend**: http://localhost:5173
- **Node.js API**: http://localhost:3001
- **PHP Application**: http://localhost:8082 (when Docker is running)
- **phpMyAdmin**: http://localhost:8083 (when Docker is running)
## <20> Quick Start
### 1. Start the Database (existing Docker setup)
```bash
# From main project directory
docker-compose up -d
```
### 2. Start the Node.js Backend
```bash
cd nodejs-version/backend
npm install
npm run build
node dist/app.js
```
### 3. Start the React Frontend
```bash
cd nodejs-version/frontend
npm install
npm run dev
```
## 📱 Features Implemented
### ✅ Backend API
- **Health Check** - Server status endpoint
- **Recipe Management** - Full CRUD operations with search/pagination
- **Ingredient Management** - CRUD operations for recipe ingredients
- **Image Serving** - Static file serving for recipe images
- **Input Validation** - Joi schema validation
- **Error Handling** - Centralized error management
- **Security** - CORS, Helmet, rate limiting, input sanitization
### ✅ Frontend Application
- **Recipe List** - Grid view with search, filtering, pagination
- **Responsive Design** - Mobile-first CSS design
- **Image Display** - Recipe images with fallback handling
- **Navigation** - Clean header with route navigation
- **Search & Filter** - Real-time search and category filtering
- **Error Handling** - User-friendly error messages
- **Loading States** - Visual feedback for API calls
## 🎯 Current Status
### ✅ **COMPLETED**
- Node.js backend with TypeScript
- Prisma ORM with existing database schema
- Complete REST API for recipes, ingredients, images
- React frontend with modern UI
- Database integration working
- Both servers running successfully
- API endpoints tested and working
- Responsive design implemented
### 🔄 **Next Steps**
1. **Recipe Detail View** - Individual recipe pages
2. **Recipe Creation/Editing** - Forms for CRUD operations
3. **Image Upload** - File upload functionality
4. **Ingredient Management** - Dedicated ingredient pages
5. **Docker Configuration** - Containerize Node.js stack
6. **Performance Optimization** - Caching, lazy loading
7. **Testing** - Unit and integration tests
## 📊 API Endpoints
### Recipes
- `GET /api/recipes` - List recipes (pagination, search, filter)
- `GET /api/recipes/:id` - Get single recipe
- `POST /api/recipes` - Create recipe
- `PUT /api/recipes/:id` - Update recipe
- `DELETE /api/recipes/:id` - Delete recipe
### Ingredients
- `GET /api/ingredients` - List ingredients
- `GET /api/ingredients/:id` - Get single ingredient
- `POST /api/ingredients` - Create ingredient
- `PUT /api/ingredients/:id` - Update ingredient
- `DELETE /api/ingredients/:id` - Delete ingredient
### Images
- `GET /api/images/recipe/:recipeId` - Get recipe images
- `GET /api/images/serve/:imagePath` - Serve image file
- `GET /api/images/:id` - Get image metadata
### Health
- `GET /api/health` - Server health check
## 🔧 Development Commands
### Backend
```bash
cd nodejs-version/backend
# Development
npm run dev # Start with hot reload (if ts-node configured)
npm run build # Build TypeScript
npm start # Start production server
node dist/app.js # Direct node execution
# Database
npm run db:generate # Generate Prisma client
npm run db:push # Push schema to database
npm run db:studio # Open Prisma Studio GUI
```
### Frontend
```bash
cd nodejs-version/frontend
# Development
npm run dev # Start Vite dev server
npm run build # Build for production
npm run preview # Preview production build
npm run lint # Run ESLint
```
## <20> Technology Benefits
### vs. PHP Version
- **Type Safety** - TypeScript eliminates runtime type errors
- **Modern Tooling** - Better developer experience with Vite, ESLint, Prettier
- **API-First** - Clean separation enables mobile apps, integrations
- **Maintainability** - Modern patterns, better error handling
- **Performance** - React SPA, optimized builds, lazy loading
- **Security** - Modern security best practices built-in
### Architecture Advantages
- **Separation of Concerns** - API backend, UI frontend
- **Scalability** - Horizontal scaling, microservices ready
- **Testing** - Unit tests, integration tests, E2E tests possible
- **Deployment** - Modern CI/CD, containerization, cloud deployment
- **Extensibility** - Add mobile apps, integrations, webhooks
## <20> Integration Options
### 1. **Parallel Operation** (Current)
- PHP app on port 8082
- Node.js API on port 3001
- React app on port 5173
- Same MySQL database
### 2. **Gradual Migration**
- Move features one by one from PHP to Node.js
- Use API versioning for compatibility
- Migrate users gradually
### 3. **Complete Replacement**
- Full React frontend + Node.js backend
- Retire PHP application
- Modern deployment stack
## <20> UI/UX Features
- **Modern Design** - Clean, professional interface
- **Responsive** - Mobile, tablet, desktop optimized
- **Fast** - React SPA with instant navigation
- **Search** - Real-time recipe search
- **Filtering** - Category-based filtering
- **Pagination** - Efficient large dataset handling
- **Images** - Recipe photo display with fallbacks
- **Navigation** - Intuitive menu structure
- **Feedback** - Loading states, error messages
- **Accessibility** - Semantic HTML, keyboard navigation
## <20> Deployment Ready
The application is ready for production deployment with:
- **Environment Configuration** - .env files for different environments
- **Build Process** - Optimized production builds
- **Static Assets** - Vite optimization for frontend
- **Security** - Production-ready security headers
- **Error Handling** - Graceful error recovery
- **Monitoring** - Health checks, logging endpoints
This modern stack provides a solid foundation for scaling the recipe management system with contemporary web technologies while maintaining compatibility with your existing data and workflows.

View File

@@ -0,0 +1,9 @@
# Database
DATABASE_URL="mysql://rezepte_user:rezepte_pass@localhost:3307/rezepte_klaus"
# Server
PORT=3001
NODE_ENV=development
# Prisma
# DATABASE_URL="file:./dev.db"

View File

@@ -0,0 +1,16 @@
# Environment variables
NODE_ENV=development
PORT=3001
# Database
DATABASE_URL="mysql://rezepte_user:rezepte_pass@localhost:3307/rezepte_klaus"
# JWT Secret (change in production!)
JWT_SECRET=your-super-secret-jwt-key-change-in-production
# Upload settings
UPLOAD_PATH=./uploads
MAX_FILE_SIZE=5242880
# CORS
CORS_ORIGIN=http://localhost:3000

3
nodejs-version/backend/dist/app.d.ts vendored Normal file
View File

@@ -0,0 +1,3 @@
declare const app: import("express-serve-static-core").Express;
export default app;
//# sourceMappingURL=app.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"app.d.ts","sourceRoot":"","sources":["../src/app.ts"],"names":[],"mappings":"AAgBA,QAAA,MAAM,GAAG,6CAAY,CAAC;AAkGtB,eAAe,GAAG,CAAC"}

86
nodejs-version/backend/dist/app.js vendored Normal file
View File

@@ -0,0 +1,86 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const express_1 = __importDefault(require("express"));
const cors_1 = __importDefault(require("cors"));
const helmet_1 = __importDefault(require("helmet"));
const compression_1 = __importDefault(require("compression"));
const express_rate_limit_1 = __importDefault(require("express-rate-limit"));
const path_1 = __importDefault(require("path"));
const config_1 = require("./config/config");
const errorHandler_1 = require("./middleware/errorHandler");
const requestLogger_1 = require("./middleware/requestLogger");
const recipes_1 = __importDefault(require("./routes/recipes"));
const ingredients_1 = __importDefault(require("./routes/ingredients"));
const images_1 = __importDefault(require("./routes/images"));
const health_1 = __importDefault(require("./routes/health"));
const app = (0, express_1.default)();
app.use((0, helmet_1.default)({
crossOriginResourcePolicy: { policy: "cross-origin" },
}));
app.use((0, compression_1.default)());
const limiter = (0, express_rate_limit_1.default)({
windowMs: 15 * 60 * 1000,
max: 100,
message: 'Too many requests from this IP, please try again later.',
});
app.use(limiter);
app.use((0, cors_1.default)({
origin: config_1.config.cors.origin,
credentials: true,
}));
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', 'http://localhost:5173');
res.header('Access-Control-Allow-Credentials', 'true');
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
if (req.method === 'OPTIONS') {
return res.sendStatus(200);
}
next();
});
app.use(express_1.default.json({ limit: '10mb' }));
app.use(express_1.default.urlencoded({ extended: true, limit: '10mb' }));
app.use(requestLogger_1.requestLogger);
app.use('/api/health', health_1.default);
app.use('/api/recipes', recipes_1.default);
app.use('/api/ingredients', ingredients_1.default);
app.use('/api/images', images_1.default);
app.get('/serve/*', (req, res, next) => {
const imagePath = req.params[0];
const cleanPath = imagePath.replace(/^uploads\//, '');
const fullPath = path_1.default.join(process.cwd(), '../../uploads', cleanPath);
console.log(`Direct serve request: ${req.originalUrl} -> ${fullPath}`);
const fs = require('fs');
if (!fs.existsSync(fullPath)) {
return res.status(404).json({
success: false,
message: 'Image not found',
requestedPath: req.originalUrl,
resolvedPath: fullPath
});
}
res.set({
'Access-Control-Allow-Origin': 'http://localhost:5173',
'Access-Control-Allow-Credentials': 'true',
'Cache-Control': 'public, max-age=31536000',
});
res.sendFile(path_1.default.resolve(fullPath));
});
app.use('*', (req, res) => {
res.status(404).json({
success: false,
message: `Route ${req.originalUrl} not found`,
});
});
app.use(errorHandler_1.errorHandler);
const PORT = config_1.config.port;
app.listen(PORT, () => {
console.log(`🚀 Server running on port ${PORT}`);
console.log(`📱 Health check: http://localhost:${PORT}/api/health`);
console.log(`🎯 API Documentation: http://localhost:${PORT}/api`);
});
exports.default = app;
//# sourceMappingURL=app.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"app.js","sourceRoot":"","sources":["../src/app.ts"],"names":[],"mappings":";;;;;AAAA,sDAA8B;AAC9B,gDAAwB;AACxB,oDAA4B;AAC5B,8DAAsC;AACtC,4EAA2C;AAC3C,gDAAwB;AACxB,4CAAyC;AACzC,4DAAyD;AACzD,8DAA2D;AAG3D,+DAA4C;AAC5C,uEAAoD;AACpD,6DAA0C;AAC1C,6DAA2C;AAE3C,MAAM,GAAG,GAAG,IAAA,iBAA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AE,0BAA0B;KAC5C,CAAC,CAAC;IAEH,GAAG,CAAC,QAAQ,CAAC,cAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAC;AACvC,CAAC,CAAC,CAAC;AAGH,GAAG,CAAC,GAAG,CAAC,GAAG,EAAE,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE;IACxB,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC;QACnB,OAAO,EAAE,KAAK;QACd,OAAO,EAAE,SAAS,GAAG,CAAC,WAAW,YAAY;KAC9C,CAAC,CAAC;AACL,CAAC,CAAC,CAAC;AAGH,GAAG,CAAC,GAAG,CAAC,2BAAY,CAAC,CAAC;AAGtB,MAAM,IAAI,GAAG,eAAM,CAAC,IAAI,CAAC;AAEzB,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,GAAG,EAAE;IACpB,OAAO,CAAC,GAAG,CAAC,6BAA6B,IAAI,EAAE,CAAC,CAAC;IACjD,OAAO,CAAC,GAAG,CAAC,qCAAqC,IAAI,aAAa,CAAC,CAAC;IACpE,OAAO,CAAC,GAAG,CAAC,0CAA0C,IAAI,MAAM,CAAC,CAAC;AACpE,CAAC,CAAC,CAAC;AAEH,kBAAe,GAAG,CAAC"}

View File

@@ -0,0 +1,20 @@
export declare const config: {
readonly port: string | 3001;
readonly nodeEnv: string;
readonly database: {
readonly url: string;
};
readonly jwt: {
readonly secret: string;
readonly expiresIn: "24h";
};
readonly upload: {
readonly path: string;
readonly maxFileSize: number;
readonly allowedTypes: readonly ["image/jpeg", "image/jpg", "image/png", "image/webp"];
};
readonly cors: {
readonly origin: string;
};
};
//# sourceMappingURL=config.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../../src/config/config.ts"],"names":[],"mappings":"AAIA,eAAO,MAAM,MAAM;;;;;;;;;;;;;;;;;;CAsBT,CAAC"}

View File

@@ -0,0 +1,28 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.config = void 0;
const dotenv_1 = __importDefault(require("dotenv"));
dotenv_1.default.config();
exports.config = {
port: process.env.PORT || 3001,
nodeEnv: process.env.NODE_ENV || 'development',
database: {
url: process.env.DATABASE_URL || 'mysql://rezepte_user:rezepte_pass@localhost:3307/rezepte_klaus',
},
jwt: {
secret: process.env.JWT_SECRET || 'your-super-secret-jwt-key',
expiresIn: '24h',
},
upload: {
path: process.env.UPLOAD_PATH || './uploads',
maxFileSize: parseInt(process.env.MAX_FILE_SIZE || '5242880'),
allowedTypes: ['image/jpeg', 'image/jpg', 'image/png', 'image/webp'],
},
cors: {
origin: process.env.CORS_ORIGIN || 'http://localhost:5173',
},
};
//# sourceMappingURL=config.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"config.js","sourceRoot":"","sources":["../../src/config/config.ts"],"names":[],"mappings":";;;;;;AAAA,oDAA4B;AAE5B,gBAAM,CAAC,MAAM,EAAE,CAAC;AAEH,QAAA,MAAM,GAAG;IACpB,IAAI,EAAE,OAAO,CAAC,GAAG,CAAC,IAAI,IAAI,IAAI;IAC9B,OAAO,EAAE,OAAO,CAAC,GAAG,CAAC,QAAQ,IAAI,aAAa;IAE9C,QAAQ,EAAE;QACR,GAAG,EAAE,OAAO,CAAC,GAAG,CAAC,YAAY,IAAI,gEAAgE;KAClG;IAED,GAAG,EAAE;QACH,MAAM,EAAE,OAAO,CAAC,GAAG,CAAC,UAAU,IAAI,2BAA2B;QAC7D,SAAS,EAAE,KAAK;KACjB;IAED,MAAM,EAAE;QACN,IAAI,EAAE,OAAO,CAAC,GAAG,CAAC,WAAW,IAAI,WAAW;QAC5C,WAAW,EAAE,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,aAAa,IAAI,SAAS,CAAC;QAC7D,YAAY,EAAE,CAAC,YAAY,EAAE,WAAW,EAAE,WAAW,EAAE,YAAY,CAAC;KACrE;IAED,IAAI,EAAE;QACJ,MAAM,EAAE,OAAO,CAAC,GAAG,CAAC,WAAW,IAAI,uBAAuB;KAC3D;CACO,CAAC"}

View File

@@ -0,0 +1,7 @@
import { Request, Response, NextFunction } from 'express';
export interface ErrorWithStatus extends Error {
status?: number;
statusCode?: number;
}
export declare const errorHandler: (err: ErrorWithStatus, req: Request, res: Response, next: NextFunction) => void;
//# sourceMappingURL=errorHandler.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"errorHandler.d.ts","sourceRoot":"","sources":["../../src/middleware/errorHandler.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAE1D,MAAM,WAAW,eAAgB,SAAQ,KAAK;IAC5C,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB;AAED,eAAO,MAAM,YAAY,GACvB,KAAK,eAAe,EACpB,KAAK,OAAO,EACZ,KAAK,QAAQ,EACb,MAAM,YAAY,KACjB,IAoBF,CAAC"}

View File

@@ -0,0 +1,24 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.errorHandler = void 0;
const errorHandler = (err, req, res, next) => {
const status = err.status || err.statusCode || 500;
const message = err.message || 'Internal Server Error';
console.error('Error:', {
status,
message,
stack: err.stack,
url: req.url,
method: req.method,
ip: req.ip,
});
res.status(status).json({
success: false,
message: process.env.NODE_ENV === 'production'
? (status === 500 ? 'Internal Server Error' : message)
: message,
...(process.env.NODE_ENV === 'development' && { stack: err.stack }),
});
};
exports.errorHandler = errorHandler;
//# sourceMappingURL=errorHandler.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"errorHandler.js","sourceRoot":"","sources":["../../src/middleware/errorHandler.ts"],"names":[],"mappings":";;;AAOO,MAAM,YAAY,GAAG,CAC1B,GAAoB,EACpB,GAAY,EACZ,GAAa,EACb,IAAkB,EACZ,EAAE;IACR,MAAM,MAAM,GAAG,GAAG,CAAC,MAAM,IAAI,GAAG,CAAC,UAAU,IAAI,GAAG,CAAC;IACnD,MAAM,OAAO,GAAG,GAAG,CAAC,OAAO,IAAI,uBAAuB,CAAC;IAEvD,OAAO,CAAC,KAAK,CAAC,QAAQ,EAAE;QACtB,MAAM;QACN,OAAO;QACP,KAAK,EAAE,GAAG,CAAC,KAAK;QAChB,GAAG,EAAE,GAAG,CAAC,GAAG;QACZ,MAAM,EAAE,GAAG,CAAC,MAAM;QAClB,EAAE,EAAE,GAAG,CAAC,EAAE;KACX,CAAC,CAAC;IAEH,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC;QACtB,OAAO,EAAE,KAAK;QACd,OAAO,EAAE,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,YAAY;YAC5C,CAAC,CAAC,CAAC,MAAM,KAAK,GAAG,CAAC,CAAC,CAAC,uBAAuB,CAAC,CAAC,CAAC,OAAO,CAAC;YACtD,CAAC,CAAC,OAAO;QACX,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,aAAa,IAAI,EAAE,KAAK,EAAE,GAAG,CAAC,KAAK,EAAE,CAAC;KACpE,CAAC,CAAC;AACL,CAAC,CAAC;AAzBW,QAAA,YAAY,gBAyBvB"}

View File

@@ -0,0 +1,3 @@
import { Request, Response, NextFunction } from 'express';
export declare const requestLogger: (req: Request, res: Response, next: NextFunction) => void;
//# sourceMappingURL=requestLogger.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"requestLogger.d.ts","sourceRoot":"","sources":["../../src/middleware/requestLogger.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAE1D,eAAO,MAAM,aAAa,GAAI,KAAK,OAAO,EAAE,KAAK,QAAQ,EAAE,MAAM,YAAY,KAAG,IAY/E,CAAC"}

View File

@@ -0,0 +1,15 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.requestLogger = void 0;
const requestLogger = (req, res, next) => {
const start = Date.now();
res.on('finish', () => {
const duration = Date.now() - start;
const { method, url, ip } = req;
const { statusCode } = res;
console.log(`${method} ${url} - ${statusCode} - ${duration}ms - ${ip}`);
});
next();
};
exports.requestLogger = requestLogger;
//# sourceMappingURL=requestLogger.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"requestLogger.js","sourceRoot":"","sources":["../../src/middleware/requestLogger.ts"],"names":[],"mappings":";;;AAEO,MAAM,aAAa,GAAG,CAAC,GAAY,EAAE,GAAa,EAAE,IAAkB,EAAQ,EAAE;IACrF,MAAM,KAAK,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;IAEzB,GAAG,CAAC,EAAE,CAAC,QAAQ,EAAE,GAAG,EAAE;QACpB,MAAM,QAAQ,GAAG,IAAI,CAAC,GAAG,EAAE,GAAG,KAAK,CAAC;QACpC,MAAM,EAAE,MAAM,EAAE,GAAG,EAAE,EAAE,EAAE,GAAG,GAAG,CAAC;QAChC,MAAM,EAAE,UAAU,EAAE,GAAG,GAAG,CAAC;QAE3B,OAAO,CAAC,GAAG,CAAC,GAAG,MAAM,IAAI,GAAG,MAAM,UAAU,MAAM,QAAQ,QAAQ,EAAE,EAAE,CAAC,CAAC;IAC1E,CAAC,CAAC,CAAC;IAEH,IAAI,EAAE,CAAC;AACT,CAAC,CAAC;AAZW,QAAA,aAAa,iBAYxB"}

View File

@@ -0,0 +1,3 @@
declare const router: import("express-serve-static-core").Router;
export default router;
//# sourceMappingURL=health.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"health.d.ts","sourceRoot":"","sources":["../../src/routes/health.ts"],"names":[],"mappings":"AAEA,QAAA,MAAM,MAAM,4CAAW,CAAC;AA8BxB,eAAe,MAAM,CAAC"}

View File

@@ -0,0 +1,30 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const express_1 = require("express");
const router = (0, express_1.Router)();
router.get('/', (req, res) => {
res.json({
success: true,
message: 'Rezepte Klaus API is running!',
timestamp: new Date().toISOString(),
environment: process.env.NODE_ENV,
});
});
router.get('/db', async (req, res) => {
try {
res.json({
success: true,
message: 'Database connection is healthy',
timestamp: new Date().toISOString(),
});
}
catch (error) {
res.status(500).json({
success: false,
message: 'Database connection failed',
error: error instanceof Error ? error.message : 'Unknown error',
});
}
});
exports.default = router;
//# sourceMappingURL=health.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"health.js","sourceRoot":"","sources":["../../src/routes/health.ts"],"names":[],"mappings":";;AAAA,qCAAoD;AAEpD,MAAM,MAAM,GAAG,IAAA,gBAAM,GAAE,CAAC;AAGxB,MAAM,CAAC,GAAG,CAAC,GAAG,EAAE,CAAC,GAAY,EAAE,GAAa,EAAE,EAAE;IAC9C,GAAG,CAAC,IAAI,CAAC;QACP,OAAO,EAAE,IAAI;QACb,OAAO,EAAE,+BAA+B;QACxC,SAAS,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;QACnC,WAAW,EAAE,OAAO,CAAC,GAAG,CAAC,QAAQ;KAClC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC;AAGH,MAAM,CAAC,GAAG,CAAC,KAAK,EAAE,KAAK,EAAE,GAAY,EAAE,GAAa,EAAE,EAAE;IACtD,IAAI,CAAC;QAEH,GAAG,CAAC,IAAI,CAAC;YACP,OAAO,EAAE,IAAI;YACb,OAAO,EAAE,gCAAgC;YACzC,SAAS,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;SACpC,CAAC,CAAC;IACL,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC;YACnB,OAAO,EAAE,KAAK;YACd,OAAO,EAAE,4BAA4B;YACrC,KAAK,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,eAAe;SAChE,CAAC,CAAC;IACL,CAAC;AACH,CAAC,CAAC,CAAC;AAEH,kBAAe,MAAM,CAAC"}

View File

@@ -0,0 +1,3 @@
declare const router: import("express-serve-static-core").Router;
export default router;
//# sourceMappingURL=images.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"images.d.ts","sourceRoot":"","sources":["../../src/routes/images.ts"],"names":[],"mappings":"AAKA,QAAA,MAAM,MAAM,4CAAW,CAAC;AAuGxB,eAAe,MAAM,CAAC"}

View File

@@ -0,0 +1,95 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const express_1 = require("express");
const client_1 = require("@prisma/client");
const path_1 = __importDefault(require("path"));
const fs_1 = __importDefault(require("fs"));
const router = (0, express_1.Router)();
const prisma = new client_1.PrismaClient();
router.get('/recipe/:recipeId', async (req, res, next) => {
try {
const { recipeId } = req.params;
if (!recipeId) {
return res.status(400).json({
success: false,
message: 'Recipe ID is required',
});
}
const images = await prisma.recipeImage.findMany({
where: { recipeId: parseInt(recipeId) },
orderBy: { id: 'asc' }
});
return res.json({
success: true,
data: images,
});
}
catch (error) {
next(error);
}
});
router.get('/serve/:imagePath(*)', (req, res, next) => {
try {
const imagePath = req.params.imagePath;
if (!imagePath) {
return res.status(400).json({
success: false,
message: 'Image path is required',
});
}
const cleanPath = imagePath.replace(/^uploads\//, '');
const fullPath = path_1.default.join(process.cwd(), '../../uploads', cleanPath);
console.log(`Serving image: ${imagePath} -> ${fullPath}`);
if (!fs_1.default.existsSync(fullPath)) {
console.log(`Image not found: ${fullPath}`);
return res.status(404).json({
success: false,
message: 'Image not found',
requestedPath: imagePath,
resolvedPath: fullPath
});
}
res.set({
'Access-Control-Allow-Origin': 'http://localhost:5173',
'Access-Control-Allow-Credentials': 'true',
'Cache-Control': 'public, max-age=31536000',
});
return res.sendFile(path_1.default.resolve(fullPath));
}
catch (error) {
console.error('Error serving image:', error);
next(error);
}
});
router.get('/:id', async (req, res, next) => {
try {
const { id } = req.params;
if (!id) {
return res.status(400).json({
success: false,
message: 'Image ID is required',
});
}
const image = await prisma.recipeImage.findUnique({
where: { id: parseInt(id) }
});
if (!image) {
return res.status(404).json({
success: false,
message: 'Image not found',
});
}
return res.json({
success: true,
data: image,
});
}
catch (error) {
next(error);
}
});
exports.default = router;
//# sourceMappingURL=images.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"images.js","sourceRoot":"","sources":["../../src/routes/images.ts"],"names":[],"mappings":";;;;;AAAA,qCAAkE;AAClE,2CAA8C;AAC9C,gDAAwB;AACxB,4CAAoB;AAEpB,MAAM,MAAM,GAAG,IAAA,gBAAM,GAAE,CAAC;AACxB,MAAM,MAAM,GAAG,IAAI,qBAAY,EAAE,CAAC;AAGlC,MAAM,CAAC,GAAG,CAAC,mBAAmB,EAAE,KAAK,EAAE,GAAY,EAAE,GAAa,EAAE,IAAkB,EAAE,EAAE;IACxF,IAAI,CAAC;QACH,MAAM,EAAE,QAAQ,EAAE,GAAG,GAAG,CAAC,MAAM,CAAC;QAEhC,IAAI,CAAC,QAAQ,EAAE,CAAC;YACd,OAAO,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC;gBAC1B,OAAO,EAAE,KAAK;gBACd,OAAO,EAAE,uBAAuB;aACjC,CAAC,CAAC;QACL,CAAC;QAED,MAAM,MAAM,GAAG,MAAM,MAAM,CAAC,WAAW,CAAC,QAAQ,CAAC;YAC/C,KAAK,EAAE,EAAE,QAAQ,EAAE,QAAQ,CAAC,QAAQ,CAAC,EAAE;YACvC,OAAO,EAAE,EAAE,EAAE,EAAE,KAAK,EAAE;SACvB,CAAC,CAAC;QAEH,OAAO,GAAG,CAAC,IAAI,CAAC;YACd,OAAO,EAAE,IAAI;YACb,IAAI,EAAE,MAAM;SACb,CAAC,CAAC;IACL,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,CAAC,KAAK,CAAC,CAAC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,KAAK,EAAE,CAAC;QACf,OAAO,CAAC,KAAK,CAAC,sBAAsB,EAAE,KAAK,CAAC,CAAC;QAC7C,IAAI,CAAC,KAAK,CAAC,CAAC;IACd,CAAC;AACH,CAAC,CAAC,CAAC;AAGH,MAAM,CAAC,GAAG,CAAC,MAAM,EAAE,KAAK,EAAE,GAAY,EAAE,GAAa,EAAE,IAAkB,EAAE,EAAE;IAC3E,IAAI,CAAC;QACH,MAAM,EAAE,EAAE,EAAE,GAAG,GAAG,CAAC,MAAM,CAAC;QAE1B,IAAI,CAAC,EAAE,EAAE,CAAC;YACR,OAAO,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC;gBAC1B,OAAO,EAAE,KAAK;gBACd,OAAO,EAAE,sBAAsB;aAChC,CAAC,CAAC;QACL,CAAC;QAED,MAAM,KAAK,GAAG,MAAM,MAAM,CAAC,WAAW,CAAC,UAAU,CAAC;YAChD,KAAK,EAAE,EAAE,EAAE,EAAE,QAAQ,CAAC,EAAE,CAAC,EAAE;SAC5B,CAAC,CAAC;QAEH,IAAI,CAAC,KAAK,EAAE,CAAC;YACX,OAAO,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC;gBAC1B,OAAO,EAAE,KAAK;gBACd,OAAO,EAAE,iBAAiB;aAC3B,CAAC,CAAC;QACL,CAAC;QAED,OAAO,GAAG,CAAC,IAAI,CAAC;YACd,OAAO,EAAE,IAAI;YACb,IAAI,EAAE,KAAK;SACZ,CAAC,CAAC;IACL,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,CAAC,KAAK,CAAC,CAAC;IACd,CAAC;AACH,CAAC,CAAC,CAAC;AAEH,kBAAe,MAAM,CAAC"}

View File

@@ -0,0 +1,3 @@
declare const router: import("express-serve-static-core").Router;
export default router;
//# sourceMappingURL=ingredients.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"ingredients.d.ts","sourceRoot":"","sources":["../../src/routes/ingredients.ts"],"names":[],"mappings":"AAIA,QAAA,MAAM,MAAM,4CAAW,CAAC;AA0LxB,eAAe,MAAM,CAAC"}

View File

@@ -0,0 +1,159 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const express_1 = require("express");
const client_1 = require("@prisma/client");
const joi_1 = __importDefault(require("joi"));
const router = (0, express_1.Router)();
const prisma = new client_1.PrismaClient();
const ingredientSchema = joi_1.default.object({
recipeNumber: joi_1.default.string().required().max(20),
ingredients: joi_1.default.string().required(),
});
const updateIngredientSchema = ingredientSchema.fork(['recipeNumber'], (schema) => schema.optional());
router.get('/', async (req, res, next) => {
try {
const { search = '', category = '', page = '1', limit = '10', sortBy = 'recipeNumber', sortOrder = 'asc' } = req.query;
const pageNum = parseInt(page);
const limitNum = parseInt(limit);
const skip = (pageNum - 1) * limitNum;
const where = {};
if (search) {
where.OR = [
{ recipeNumber: { contains: search } },
{ ingredients: { contains: search } },
];
}
if (category) {
where.recipeNumber = { contains: category };
}
const [ingredients, total] = await Promise.all([
prisma.ingredient.findMany({
where,
orderBy: { [sortBy]: sortOrder },
skip,
take: limitNum,
}),
prisma.ingredient.count({ where })
]);
return res.json({
success: true,
data: ingredients,
pagination: {
page: pageNum,
limit: limitNum,
total,
pages: Math.ceil(total / limitNum),
},
});
}
catch (error) {
next(error);
}
});
router.get('/:id', async (req, res, next) => {
try {
const { id } = req.params;
if (!id) {
return res.status(400).json({
success: false,
message: 'Ingredient ID is required',
});
}
const ingredient = await prisma.ingredient.findUnique({
where: { id: parseInt(id) }
});
if (!ingredient) {
return res.status(404).json({
success: false,
message: 'Ingredient not found',
});
}
return res.json({
success: true,
data: ingredient,
});
}
catch (error) {
next(error);
}
});
router.post('/', async (req, res, next) => {
try {
const { error, value } = ingredientSchema.validate(req.body);
if (error) {
return res.status(400).json({
success: false,
message: 'Validation error',
details: error.details,
});
}
const ingredient = await prisma.ingredient.create({
data: value
});
return res.status(201).json({
success: true,
data: ingredient,
message: 'Ingredient created successfully',
});
}
catch (error) {
next(error);
}
});
router.put('/:id', async (req, res, next) => {
try {
const { id } = req.params;
if (!id) {
return res.status(400).json({
success: false,
message: 'Ingredient ID is required',
});
}
const { error, value } = updateIngredientSchema.validate(req.body);
if (error) {
return res.status(400).json({
success: false,
message: 'Validation error',
details: error.details,
});
}
const ingredient = await prisma.ingredient.update({
where: { id: parseInt(id) },
data: value
});
return res.json({
success: true,
data: ingredient,
message: 'Ingredient updated successfully',
});
}
catch (error) {
next(error);
}
});
router.delete('/:id', async (req, res, next) => {
try {
const { id } = req.params;
if (!id) {
return res.status(400).json({
success: false,
message: 'Ingredient ID is required',
});
}
await prisma.ingredient.delete({
where: { id: parseInt(id) }
});
return res.json({
success: true,
message: 'Ingredient deleted successfully',
});
}
catch (error) {
next(error);
}
});
exports.default = router;
//# sourceMappingURL=ingredients.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"ingredients.js","sourceRoot":"","sources":["../../src/routes/ingredients.ts"],"names":[],"mappings":";;;;;AAAA,qCAAkE;AAClE,2CAA8C;AAC9C,8CAAsB;AAEtB,MAAM,MAAM,GAAG,IAAA,gBAAM,GAAE,CAAC;AACxB,MAAM,MAAM,GAAG,IAAI,qBAAY,EAAE,CAAC;AAGlC,MAAM,gBAAgB,GAAG,aAAG,CAAC,MAAM,CAAC;IAClC,YAAY,EAAE,aAAG,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC;IAC7C,WAAW,EAAE,aAAG,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;CACrC,CAAC,CAAC;AAEH,MAAM,sBAAsB,GAAG,gBAAgB,CAAC,IAAI,CAAC,CAAC,cAAc,CAAC,EAAE,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,QAAQ,EAAE,CAAC,CAAC;AAGtG,MAAM,CAAC,GAAG,CAAC,GAAG,EA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,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,CAAC,KAAK,CAAC,CAAC;IACd,CAAC;AACH,CAAC,CAAC,CAAC;AAEH,kBAAe,MAAM,CAAC"}

View File

@@ -0,0 +1,3 @@
declare const router: import("express-serve-static-core").Router;
export default router;
//# sourceMappingURL=recipes.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"recipes.d.ts","sourceRoot":"","sources":["../../src/routes/recipes.ts"],"names":[],"mappings":"AAIA,QAAA,MAAM,MAAM,4CAAW,CAAC;AA4PxB,eAAe,MAAM,CAAC"}

View File

@@ -0,0 +1,212 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const express_1 = require("express");
const client_1 = require("@prisma/client");
const joi_1 = __importDefault(require("joi"));
const router = (0, express_1.Router)();
const prisma = new client_1.PrismaClient();
const recipeSchema = joi_1.default.object({
recipeNumber: joi_1.default.string().optional().allow(''),
title: joi_1.default.string().required().min(1).max(255),
description: joi_1.default.string().optional().allow(''),
category: joi_1.default.string().optional().allow(''),
preparation: joi_1.default.string().optional().allow(''),
servings: joi_1.default.number().integer().min(1).default(1),
ingredients: joi_1.default.string().optional().allow(''),
instructions: joi_1.default.string().optional().allow(''),
comment: joi_1.default.string().optional().allow(''),
});
const updateRecipeSchema = recipeSchema;
router.get('/', async (req, res, next) => {
try {
const { search = '', category = '', page = '1', limit = '10', sortBy = 'title', sortOrder = 'asc' } = req.query;
const pageNum = parseInt(page);
const limitNum = parseInt(limit);
const skip = (pageNum - 1) * limitNum;
const where = {};
if (search) {
where.OR = [
{ title: { contains: search } },
{ description: { contains: search } },
{ ingredients: { contains: search } },
];
}
if (category) {
where.category = { contains: category };
}
const [recipes, total] = await Promise.all([
prisma.recipe.findMany({
where,
include: {
images: true,
ingredientsList: true,
},
orderBy: { [sortBy]: sortOrder },
skip,
take: limitNum,
}),
prisma.recipe.count({ where })
]);
return res.json({
success: true,
data: recipes,
pagination: {
page: pageNum,
limit: limitNum,
total,
pages: Math.ceil(total / limitNum),
},
});
}
catch (error) {
next(error);
}
});
router.get('/:id', async (req, res, next) => {
try {
const { id } = req.params;
if (!id) {
return res.status(400).json({
success: false,
message: 'Recipe ID is required',
});
}
const recipe = await prisma.recipe.findUnique({
where: { id: parseInt(id) },
include: {
images: true,
ingredientsList: true,
}
});
if (!recipe) {
return res.status(404).json({
success: false,
message: 'Recipe not found',
});
}
if ((!recipe.ingredients || recipe.ingredients.trim() === '' || recipe.ingredients.length < 10) && recipe.recipeNumber) {
try {
const paddedNumber = recipe.recipeNumber.padStart(3, '0');
const recipeNumberWithR = `R${paddedNumber}`;
const separateIngredients = await prisma.ingredient.findFirst({
where: { recipeNumber: recipeNumberWithR }
});
if (separateIngredients && separateIngredients.ingredients) {
recipe.ingredients = separateIngredients.ingredients;
}
}
catch (ingredientError) {
console.log(`Could not load separate ingredients for recipe ${recipe.recipeNumber}:`, ingredientError);
}
}
return res.json({
success: true,
data: recipe,
});
}
catch (error) {
next(error);
}
});
router.post('/', async (req, res, next) => {
try {
const { error, value } = recipeSchema.validate(req.body);
if (error) {
return res.status(400).json({
success: false,
message: 'Validation error',
details: error.details,
});
}
if (!value.recipeNumber || value.recipeNumber.trim() === '') {
const lastRecipe = await prisma.recipe.findFirst({
orderBy: { id: 'desc' },
select: { recipeNumber: true }
});
let nextNumber = 1;
if (lastRecipe?.recipeNumber) {
const match = lastRecipe.recipeNumber.match(/\d+/);
if (match) {
nextNumber = parseInt(match[0]) + 1;
}
}
value.recipeNumber = `R${nextNumber.toString().padStart(3, '0')}`;
}
const recipe = await prisma.recipe.create({
data: value,
include: {
images: true,
ingredientsList: true,
}
});
return res.status(201).json({
success: true,
data: recipe,
message: 'Recipe created successfully',
});
}
catch (error) {
next(error);
}
});
router.put('/:id', async (req, res, next) => {
try {
const { id } = req.params;
if (!id) {
return res.status(400).json({
success: false,
message: 'Recipe ID is required',
});
}
const { error, value } = updateRecipeSchema.validate(req.body);
if (error) {
return res.status(400).json({
success: false,
message: 'Validation error',
details: error.details,
});
}
const recipe = await prisma.recipe.update({
where: { id: parseInt(id) },
data: value,
include: {
images: true,
ingredientsList: true,
}
});
return res.json({
success: true,
data: recipe,
message: 'Recipe updated successfully',
});
}
catch (error) {
next(error);
}
});
router.delete('/:id', async (req, res, next) => {
try {
const { id } = req.params;
if (!id) {
return res.status(400).json({
success: false,
message: 'Recipe ID is required',
});
}
await prisma.recipe.delete({
where: { id: parseInt(id) }
});
return res.json({
success: true,
message: 'Recipe deleted successfully',
});
}
catch (error) {
next(error);
}
});
exports.default = router;
//# sourceMappingURL=recipes.js.map

File diff suppressed because one or more lines are too long

7362
nodejs-version/backend/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,58 @@
{
"name": "rezepte-backend",
"version": "1.0.0",
"description": "Rezepte Klaus - Node.js Backend",
"main": "dist/app.js",
"scripts": {
"dev": "tsx watch src/app.ts",
"build": "tsc",
"start": "node dist/app.js",
"db:generate": "prisma generate",
"db:push": "prisma db push",
"db:migrate": "prisma migrate dev",
"db:studio": "prisma studio",
"lint": "eslint src/**/*.ts",
"test": "jest"
},
"dependencies": {
"@prisma/client": "^5.6.0",
"bcryptjs": "^2.4.3",
"compression": "^1.7.4",
"cors": "^2.8.5",
"dotenv": "^16.3.1",
"express": "^4.18.2",
"express-rate-limit": "^7.1.5",
"helmet": "^7.1.0",
"joi": "^17.11.0",
"jsonwebtoken": "^9.0.2",
"multer": "^1.4.5-lts.1"
},
"devDependencies": {
"@types/bcryptjs": "^2.4.6",
"@types/compression": "^1.7.5",
"@types/cors": "^2.8.17",
"@types/express": "^4.17.21",
"@types/jest": "^29.5.8",
"@types/jsonwebtoken": "^9.0.5",
"@types/multer": "^1.4.11",
"@types/node": "^20.8.10",
"@typescript-eslint/eslint-plugin": "^6.9.1",
"@typescript-eslint/parser": "^6.9.1",
"eslint": "^8.53.0",
"jest": "^29.7.0",
"prisma": "^5.6.0",
"ts-jest": "^29.1.1",
"ts-node": "^10.9.2",
"tsx": "^4.1.4",
"typescript": "^5.2.2"
},
"keywords": [
"recipes",
"cooking",
"node.js",
"typescript",
"express"
],
"author": "Klaus",
"license": "MIT"
}

View File

@@ -0,0 +1,53 @@
// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "mysql"
url = env("DATABASE_URL")
}
model Recipe {
id Int @id @default(autoincrement())
recipeNumber String @unique @map("Rezeptnummer") @db.VarChar(50)
title String @map("Bezeichnung") @db.Text
description String? @map("Beschreibung") @db.Text
category String? @map("Kategorie") @db.VarChar(100)
filePath String? @map("datei_pfad") @db.VarChar(255)
preparation String? @map("Vorbereitung") @db.Text
servings Int @map("Anzahl") @default(1)
ingredients String? @map("Zutaten") @db.Text
instructions String? @map("Zubereitung") @db.Text
comment String? @map("Kommentar") @db.Text
// Relations
images RecipeImage[]
ingredientsList Ingredient[]
@@map("Rezepte")
}
model Ingredient {
id Int @id @default(autoincrement())
recipeNumber String @map("rezeptnr") @db.VarChar(20)
ingredients String @map("ingr") @db.Text
// Relations
recipe Recipe? @relation(fields: [recipeNumber], references: [recipeNumber])
@@map("ingredients")
}
model RecipeImage {
id Int @id @default(autoincrement())
recipeId Int @map("rezepte_id")
filePath String @map("datei_pfad") @db.VarChar(255)
// Relations
recipe Recipe? @relation(fields: [recipeId], references: [id])
@@map("rezepte_bilder")
}

View File

@@ -0,0 +1,26 @@
node:events:497
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE: address already in use :::3001
at Server.setupListenHandle [as _listen2] (node:net:1908:16)
at listenInCluster (node:net:1965:12)
at Server.listen (node:net:2067:7)
at Function.listen (/Users/rxf/Projekte/Rezepte_Klaus/nodejs-version/backend/node_modules/express/lib/application.js:635:24)
at Object.<anonymous> (/Users/rxf/Projekte/Rezepte_Klaus/nodejs-version/backend/dist/app.js:70:5)
at Module._compile (node:internal/modules/cjs/loader:1546:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1691:10)
at Module.load (node:internal/modules/cjs/loader:1317:32)
at Module._load (node:internal/modules/cjs/loader:1127:12)
at TracingChannel.traceSync (node:diagnostics_channel:315:14)
Emitted 'error' event on Server instance at:
at emitErrorNT (node:net:1944:8)
at process.processTicksAndRejections (node:internal/process/task_queues:90:21) {
code: 'EADDRINUSE',
errno: -48,
syscall: 'listen',
address: '::',
port: 3001
}
Node.js v22.9.0

View File

@@ -0,0 +1,115 @@
import express from 'express';
import cors from 'cors';
import helmet from 'helmet';
import compression from 'compression';
import rateLimit from 'express-rate-limit';
import path from 'path';
import { config } from './config/config';
import { errorHandler } from './middleware/errorHandler';
import { requestLogger } from './middleware/requestLogger';
// Route imports
import recipeRoutes from './routes/recipes';
import ingredientRoutes from './routes/ingredients';
import imageRoutes from './routes/images';
import healthRoutes from './routes/health';
const app = express();
// Security middleware
app.use(helmet({
crossOriginResourcePolicy: { policy: "cross-origin" },
}));
app.use(compression());
// Rate limiting
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // limit each IP to 100 requests per windowMs
message: 'Too many requests from this IP, please try again later.',
});
app.use(limiter);
// CORS configuration
app.use(cors({
origin: config.cors.origin,
credentials: true,
}));
// Additional CORS headers for all requests
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', 'http://localhost:5173');
res.header('Access-Control-Allow-Credentials', 'true');
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
if (req.method === 'OPTIONS') {
return res.sendStatus(200);
}
next();
});
// Body parsing middleware
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true, limit: '10mb' }));
// Request logging
app.use(requestLogger);
// API routes
app.use('/api/health', healthRoutes);
app.use('/api/recipes', recipeRoutes);
app.use('/api/ingredients', ingredientRoutes);
app.use('/api/images', imageRoutes);
// Direct image serving (for convenience)
app.get('/serve/*', (req, res, next) => {
const imagePath = (req.params as any)[0]; // Get everything after /serve/
// Remove leading 'uploads/' if present to avoid duplication
const cleanPath = imagePath.replace(/^uploads\//, '');
const fullPath = path.join(process.cwd(), '../../uploads', cleanPath);
console.log(`Direct serve request: ${req.originalUrl} -> ${fullPath}`);
// Check if file exists
const fs = require('fs');
if (!fs.existsSync(fullPath)) {
return res.status(404).json({
success: false,
message: 'Image not found',
requestedPath: req.originalUrl,
resolvedPath: fullPath
});
}
// Set headers for images
res.set({
'Access-Control-Allow-Origin': 'http://localhost:5173',
'Access-Control-Allow-Credentials': 'true',
'Cache-Control': 'public, max-age=31536000',
});
res.sendFile(path.resolve(fullPath));
});
// 404 handler
app.use('*', (req, res) => {
res.status(404).json({
success: false,
message: `Route ${req.originalUrl} not found`,
});
});
// Global error handler
app.use(errorHandler);
// Start server
const PORT = config.port;
app.listen(PORT, () => {
console.log(`🚀 Server running on port ${PORT}`);
console.log(`📱 Health check: http://localhost:${PORT}/api/health`);
console.log(`🎯 API Documentation: http://localhost:${PORT}/api`);
});
export default app;

View File

@@ -0,0 +1,27 @@
import dotenv from 'dotenv';
dotenv.config();
export const config = {
port: process.env.PORT || 3001,
nodeEnv: process.env.NODE_ENV || 'development',
database: {
url: process.env.DATABASE_URL || 'mysql://rezepte_user:rezepte_pass@localhost:3307/rezepte_klaus',
},
jwt: {
secret: process.env.JWT_SECRET || 'your-super-secret-jwt-key',
expiresIn: '24h',
},
upload: {
path: process.env.UPLOAD_PATH || './uploads',
maxFileSize: parseInt(process.env.MAX_FILE_SIZE || '5242880'), // 5MB default
allowedTypes: ['image/jpeg', 'image/jpg', 'image/png', 'image/webp'],
},
cors: {
origin: process.env.CORS_ORIGIN || 'http://localhost:5173',
},
} as const;

View File

@@ -0,0 +1,33 @@
import { Request, Response, NextFunction } from 'express';
export interface ErrorWithStatus extends Error {
status?: number;
statusCode?: number;
}
export const errorHandler = (
err: ErrorWithStatus,
req: Request,
res: Response,
next: NextFunction
): void => {
const status = err.status || err.statusCode || 500;
const message = err.message || 'Internal Server Error';
console.error('Error:', {
status,
message,
stack: err.stack,
url: req.url,
method: req.method,
ip: req.ip,
});
res.status(status).json({
success: false,
message: process.env.NODE_ENV === 'production'
? (status === 500 ? 'Internal Server Error' : message)
: message,
...(process.env.NODE_ENV === 'development' && { stack: err.stack }),
});
};

View File

@@ -0,0 +1,15 @@
import { Request, Response, NextFunction } from 'express';
export const requestLogger = (req: Request, res: Response, next: NextFunction): void => {
const start = Date.now();
res.on('finish', () => {
const duration = Date.now() - start;
const { method, url, ip } = req;
const { statusCode } = res;
console.log(`${method} ${url} - ${statusCode} - ${duration}ms - ${ip}`);
});
next();
};

View File

@@ -0,0 +1,33 @@
import { Router, Request, Response } from 'express';
const router = Router();
// Health check endpoint
router.get('/', (req: Request, res: Response) => {
res.json({
success: true,
message: 'Rezepte Klaus API is running!',
timestamp: new Date().toISOString(),
environment: process.env.NODE_ENV,
});
});
// Database health check
router.get('/db', async (req: Request, res: Response) => {
try {
// TODO: Add database connectivity check with Prisma
res.json({
success: true,
message: 'Database connection is healthy',
timestamp: new Date().toISOString(),
});
} catch (error) {
res.status(500).json({
success: false,
message: 'Database connection failed',
error: error instanceof Error ? error.message : 'Unknown error',
});
}
});
export default router;

View File

@@ -0,0 +1,109 @@
import { Router, Request, Response, NextFunction } from 'express';
import { PrismaClient } from '@prisma/client';
import path from 'path';
import fs from 'fs';
const router = Router();
const prisma = new PrismaClient();
// Get all images for a recipe by recipe ID
router.get('/recipe/:recipeId', async (req: Request, res: Response, next: NextFunction) => {
try {
const { recipeId } = req.params;
if (!recipeId) {
return res.status(400).json({
success: false,
message: 'Recipe ID is required',
});
}
const images = await prisma.recipeImage.findMany({
where: { recipeId: parseInt(recipeId) },
orderBy: { id: 'asc' }
});
return res.json({
success: true,
data: images,
});
} catch (error) {
next(error);
}
});
// Serve image file
router.get('/serve/:imagePath(*)', (req: Request, res: Response, next: NextFunction) => {
try {
const imagePath = req.params.imagePath;
if (!imagePath) {
return res.status(400).json({
success: false,
message: 'Image path is required',
});
}
// Remove leading 'uploads/' if present to avoid duplication
const cleanPath = imagePath.replace(/^uploads\//, '');
const fullPath = path.join(process.cwd(), '../../uploads', cleanPath);
console.log(`Serving image: ${imagePath} -> ${fullPath}`);
if (!fs.existsSync(fullPath)) {
console.log(`Image not found: ${fullPath}`);
return res.status(404).json({
success: false,
message: 'Image not found',
requestedPath: imagePath,
resolvedPath: fullPath
});
}
// Set CORS headers for images
res.set({
'Access-Control-Allow-Origin': 'http://localhost:5173',
'Access-Control-Allow-Credentials': 'true',
'Cache-Control': 'public, max-age=31536000', // Cache for 1 year
});
return res.sendFile(path.resolve(fullPath));
} catch (error) {
console.error('Error serving image:', error);
next(error);
}
});
// Get image metadata
router.get('/:id', async (req: Request, res: Response, next: NextFunction) => {
try {
const { id } = req.params;
if (!id) {
return res.status(400).json({
success: false,
message: 'Image ID is required',
});
}
const image = await prisma.recipeImage.findUnique({
where: { id: parseInt(id) }
});
if (!image) {
return res.status(404).json({
success: false,
message: 'Image not found',
});
}
return res.json({
success: true,
data: image,
});
} catch (error) {
next(error);
}
});
export default router;

View File

@@ -0,0 +1,191 @@
import { Router, Request, Response, NextFunction } from 'express';
import { PrismaClient } from '@prisma/client';
import Joi from 'joi';
const router = Router();
const prisma = new PrismaClient();
// Validation schemas
const ingredientSchema = Joi.object({
recipeNumber: Joi.string().required().max(20),
ingredients: Joi.string().required(),
});
const updateIngredientSchema = ingredientSchema.fork(['recipeNumber'], (schema) => schema.optional());
// Get all ingredients with search and pagination
router.get('/', async (req: Request, res: Response, next: NextFunction) => {
try {
const {
search = '',
category = '',
page = '1',
limit = '10',
sortBy = 'recipeNumber',
sortOrder = 'asc'
} = req.query;
const pageNum = parseInt(page as string);
const limitNum = parseInt(limit as string);
const skip = (pageNum - 1) * limitNum;
const where: any = {};
if (search) {
where.OR = [
{ recipeNumber: { contains: search as string } },
{ ingredients: { contains: search as string } },
];
}
if (category) {
where.recipeNumber = { contains: category as string };
}
const [ingredients, total] = await Promise.all([
prisma.ingredient.findMany({
where,
orderBy: { [sortBy as string]: sortOrder as 'asc' | 'desc' },
skip,
take: limitNum,
}),
prisma.ingredient.count({ where })
]);
return res.json({
success: true,
data: ingredients,
pagination: {
page: pageNum,
limit: limitNum,
total,
pages: Math.ceil(total / limitNum),
},
});
} catch (error) {
next(error);
}
});
// Get single ingredient by ID
router.get('/:id', async (req: Request, res: Response, next: NextFunction) => {
try {
const { id } = req.params;
if (!id) {
return res.status(400).json({
success: false,
message: 'Ingredient ID is required',
});
}
const ingredient = await prisma.ingredient.findUnique({
where: { id: parseInt(id) }
});
if (!ingredient) {
return res.status(404).json({
success: false,
message: 'Ingredient not found',
});
}
return res.json({
success: true,
data: ingredient,
});
} catch (error) {
next(error);
}
});
// Create new ingredient
router.post('/', async (req: Request, res: Response, next: NextFunction) => {
try {
const { error, value } = ingredientSchema.validate(req.body);
if (error) {
return res.status(400).json({
success: false,
message: 'Validation error',
details: error.details,
});
}
const ingredient = await prisma.ingredient.create({
data: value
});
return res.status(201).json({
success: true,
data: ingredient,
message: 'Ingredient created successfully',
});
} catch (error) {
next(error);
}
});
// Update ingredient
router.put('/:id', async (req: Request, res: Response, next: NextFunction) => {
try {
const { id } = req.params;
if (!id) {
return res.status(400).json({
success: false,
message: 'Ingredient ID is required',
});
}
const { error, value } = updateIngredientSchema.validate(req.body);
if (error) {
return res.status(400).json({
success: false,
message: 'Validation error',
details: error.details,
});
}
const ingredient = await prisma.ingredient.update({
where: { id: parseInt(id) },
data: value
});
return res.json({
success: true,
data: ingredient,
message: 'Ingredient updated successfully',
});
} catch (error) {
next(error);
}
});
// Delete ingredient
router.delete('/:id', async (req: Request, res: Response, next: NextFunction) => {
try {
const { id } = req.params;
if (!id) {
return res.status(400).json({
success: false,
message: 'Ingredient ID is required',
});
}
await prisma.ingredient.delete({
where: { id: parseInt(id) }
});
return res.json({
success: true,
message: 'Ingredient deleted successfully',
});
} catch (error) {
next(error);
}
});
export default router;

View File

@@ -0,0 +1,257 @@
import { Router, Request, Response, NextFunction } from 'express';
import { PrismaClient } from '@prisma/client';
import Joi from 'joi';
const router = Router();
const prisma = new PrismaClient();
// Validation schemas
const recipeSchema = Joi.object({
recipeNumber: Joi.string().optional().allow(''),
title: Joi.string().required().min(1).max(255),
description: Joi.string().optional().allow(''),
category: Joi.string().optional().allow(''),
preparation: Joi.string().optional().allow(''),
servings: Joi.number().integer().min(1).default(1),
ingredients: Joi.string().optional().allow(''),
instructions: Joi.string().optional().allow(''),
comment: Joi.string().optional().allow(''),
});
const updateRecipeSchema = recipeSchema;
// Get all recipes with search and pagination
router.get('/', async (req: Request, res: Response, next: NextFunction) => {
try {
const {
search = '',
category = '',
page = '1',
limit = '10',
sortBy = 'title',
sortOrder = 'asc'
} = req.query;
const pageNum = parseInt(page as string);
const limitNum = parseInt(limit as string);
const skip = (pageNum - 1) * limitNum;
const where: any = {};
if (search) {
where.OR = [
{ title: { contains: search as string } },
{ description: { contains: search as string } },
{ ingredients: { contains: search as string } },
];
}
if (category) {
where.category = { contains: category as string };
}
const [recipes, total] = await Promise.all([
prisma.recipe.findMany({
where,
include: {
images: true,
ingredientsList: true,
},
orderBy: { [sortBy as string]: sortOrder as 'asc' | 'desc' },
skip,
take: limitNum,
}),
prisma.recipe.count({ where })
]);
return res.json({
success: true,
data: recipes,
pagination: {
page: pageNum,
limit: limitNum,
total,
pages: Math.ceil(total / limitNum),
},
});
} catch (error) {
next(error);
}
});
// Get single recipe by ID
// Get recipe by ID
router.get('/:id', async (req: Request, res: Response, next: NextFunction) => {
try {
const { id } = req.params;
if (!id) {
return res.status(400).json({
success: false,
message: 'Recipe ID is required',
});
}
const recipe = await prisma.recipe.findUnique({
where: { id: parseInt(id) },
include: {
images: true,
ingredientsList: true,
}
});
if (!recipe) {
return res.status(404).json({
success: false,
message: 'Recipe not found',
});
}
// Try to load ingredients from separate ingredients table if not already loaded
if ((!recipe.ingredients || recipe.ingredients.trim() === '' || recipe.ingredients.length < 10) && recipe.recipeNumber) {
try {
// Try with "R" prefix (e.g., "30" -> "R030")
const paddedNumber = recipe.recipeNumber.padStart(3, '0');
const recipeNumberWithR = `R${paddedNumber}`;
const separateIngredients = await prisma.ingredient.findFirst({
where: { recipeNumber: recipeNumberWithR }
});
if (separateIngredients && separateIngredients.ingredients) {
// Update the recipe object with the found ingredients
(recipe as any).ingredients = separateIngredients.ingredients;
}
} catch (ingredientError) {
console.log(`Could not load separate ingredients for recipe ${recipe.recipeNumber}:`, ingredientError);
}
}
return res.json({
success: true,
data: recipe,
});
} catch (error) {
next(error);
}
});
// Create new recipe
router.post('/', async (req: Request, res: Response, next: NextFunction) => {
try {
const { error, value } = recipeSchema.validate(req.body);
if (error) {
return res.status(400).json({
success: false,
message: 'Validation error',
details: error.details,
});
}
// Generate recipeNumber if not provided
if (!value.recipeNumber || value.recipeNumber.trim() === '') {
// Find the highest existing recipe number
const lastRecipe = await prisma.recipe.findFirst({
orderBy: { id: 'desc' },
select: { recipeNumber: true }
});
let nextNumber = 1;
if (lastRecipe?.recipeNumber) {
// Extract number from recipeNumber like "R030" -> 30
const match = lastRecipe.recipeNumber.match(/\d+/);
if (match) {
nextNumber = parseInt(match[0]) + 1;
}
}
// Format as R### (e.g., R001, R032)
value.recipeNumber = `R${nextNumber.toString().padStart(3, '0')}`;
}
const recipe = await prisma.recipe.create({
data: value,
include: {
images: true,
ingredientsList: true,
}
});
return res.status(201).json({
success: true,
data: recipe,
message: 'Recipe created successfully',
});
} catch (error) {
next(error);
}
});
// Update recipe
router.put('/:id', async (req: Request, res: Response, next: NextFunction) => {
try {
const { id } = req.params;
if (!id) {
return res.status(400).json({
success: false,
message: 'Recipe ID is required',
});
}
const { error, value } = updateRecipeSchema.validate(req.body);
if (error) {
return res.status(400).json({
success: false,
message: 'Validation error',
details: error.details,
});
}
const recipe = await prisma.recipe.update({
where: { id: parseInt(id) },
data: value,
include: {
images: true,
ingredientsList: true,
}
});
return res.json({
success: true,
data: recipe,
message: 'Recipe updated successfully',
});
} catch (error) {
next(error);
}
});
// Delete recipe
router.delete('/:id', async (req: Request, res: Response, next: NextFunction) => {
try {
const { id } = req.params;
if (!id) {
return res.status(400).json({
success: false,
message: 'Recipe ID is required',
});
}
await prisma.recipe.delete({
where: { id: parseInt(id) }
});
return res.json({
success: true,
message: 'Recipe deleted successfully',
});
} catch (error) {
next(error);
}
});
export default router;

View File

@@ -0,0 +1,25 @@
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"lib": ["ES2020"],
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"declaration": true,
"declarationMap": true,
"sourceMap": true,
"removeComments": true,
"noImplicitAny": true,
"noImplicitReturns": false,
"noFallthroughCasesInSwitch": true,
"noUncheckedIndexedAccess": true,
"exactOptionalPropertyTypes": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist", "**/*.test.ts"]
}

24
nodejs-version/frontend/.gitignore vendored Normal file
View File

@@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

View File

@@ -0,0 +1,69 @@
# React + TypeScript + Vite
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
Currently, two official plugins are available:
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Babel](https://babeljs.io/) for Fast Refresh
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
## Expanding the ESLint configuration
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
```js
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Remove tseslint.configs.recommended and replace with this
tseslint.configs.recommendedTypeChecked,
// Alternatively, use this for stricter rules
tseslint.configs.strictTypeChecked,
// Optionally, add this for stylistic rules
tseslint.configs.stylisticTypeChecked,
// Other configs...
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```
You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
```js
// eslint.config.js
import reactX from 'eslint-plugin-react-x'
import reactDom from 'eslint-plugin-react-dom'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Enable lint rules for React
reactX.configs['recommended-typescript'],
// Enable lint rules for React DOM
reactDom.configs.recommended,
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```

View File

@@ -0,0 +1,23 @@
import js from '@eslint/js'
import globals from 'globals'
import reactHooks from 'eslint-plugin-react-hooks'
import reactRefresh from 'eslint-plugin-react-refresh'
import tseslint from 'typescript-eslint'
import { defineConfig, globalIgnores } from 'eslint/config'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
js.configs.recommended,
tseslint.configs.recommended,
reactHooks.configs['recommended-latest'],
reactRefresh.configs.vite,
],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
},
},
])

View File

@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + React + TS</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

3765
nodejs-version/frontend/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,32 @@
{
"name": "frontend",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "eslint .",
"preview": "vite preview"
},
"dependencies": {
"@types/react-router-dom": "^5.3.3",
"axios": "^1.12.2",
"react": "^19.1.1",
"react-dom": "^19.1.1",
"react-router-dom": "^7.9.1"
},
"devDependencies": {
"@eslint/js": "^9.35.0",
"@types/react": "^19.1.13",
"@types/react-dom": "^19.1.9",
"@vitejs/plugin-react": "^5.0.2",
"eslint": "^9.35.0",
"eslint-plugin-react-hooks": "^5.2.0",
"eslint-plugin-react-refresh": "^0.4.20",
"globals": "^16.4.0",
"typescript": "~5.8.3",
"typescript-eslint": "^8.43.0",
"vite": "^7.1.6"
}
}

View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

View File

@@ -0,0 +1,76 @@
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
line-height: 1.6;
color: #333;
background-color: #f8f9fa;
}
.App {
min-height: 100vh;
display: flex;
flex-direction: column;
}
.main-content {
flex: 1;
padding-top: 0;
}
/* Global button styles */
button {
font-family: inherit;
cursor: pointer;
border: none;
outline: none;
}
/* Global input styles */
input, select, textarea {
font-family: inherit;
outline: none;
}
/* Global link styles */
a {
color: inherit;
text-decoration: none;
}
/* Utility classes */
.container {
max-width: 1200px;
margin: 0 auto;
padding: 0 1rem;
}
.text-center {
text-align: center;
}
.mb-1 { margin-bottom: 0.5rem; }
.mb-2 { margin-bottom: 1rem; }
.mb-3 { margin-bottom: 1.5rem; }
.mb-4 { margin-bottom: 2rem; }
.mt-1 { margin-top: 0.5rem; }
.mt-2 { margin-top: 1rem; }
.mt-3 { margin-top: 1.5rem; }
.mt-4 { margin-top: 2rem; }
.p-1 { padding: 0.5rem; }
.p-2 { padding: 1rem; }
.p-3 { padding: 1.5rem; }
.p-4 { padding: 2rem; }
/* Responsive utilities */
@media (max-width: 768px) {
.container {
padding: 0 0.5rem;
}
}

View File

@@ -0,0 +1,29 @@
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import Header from './components/Header';
import RecipeList from './components/RecipeList';
import RecipeDetail from './components/RecipeDetail';
import RecipeEdit from './components/RecipeEdit';
import RecipeCreate from './components/RecipeCreate';
import './App.css';
function App() {
return (
<Router>
<div className="App">
<Header />
<main className="main-content">
<Routes>
<Route path="/" element={<RecipeList />} />
<Route path="/recipes" element={<RecipeList />} />
<Route path="/recipes/new" element={<RecipeCreate />} />
<Route path="/recipes/:id" element={<RecipeDetail />} />
<Route path="/recipes/:id/edit" element={<RecipeEdit />} />
{/* More routes will be added here */}
</Routes>
</main>
</div>
</Router>
);
}
export default App;

View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>

After

Width:  |  Height:  |  Size: 4.0 KiB

View File

@@ -0,0 +1,74 @@
.header {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
padding: 1rem 0;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
position: sticky;
top: 0;
z-index: 1000;
}
.container {
max-width: 1200px;
margin: 0 auto;
padding: 0 1rem;
display: flex;
justify-content: space-between;
align-items: center;
}
.nav-brand {
flex: 1;
}
.brand-link {
text-decoration: none;
color: white;
}
.brand-link h1 {
margin: 0;
font-size: 1.8rem;
font-weight: 600;
color: white;
}
.nav-menu {
display: flex;
gap: 2rem;
align-items: center;
}
.nav-link {
color: white;
text-decoration: none;
font-weight: 500;
font-size: 1rem;
padding: 0.5rem 1rem;
border-radius: 6px;
transition: all 0.3s ease;
}
.nav-link:hover {
background-color: rgba(255, 255, 255, 0.1);
transform: translateY(-1px);
}
@media (max-width: 768px) {
.container {
flex-direction: column;
gap: 1rem;
}
.nav-menu {
gap: 1rem;
}
.brand-link h1 {
font-size: 1.5rem;
}
.nav-link {
font-size: 0.9rem;
padding: 0.4rem 0.8rem;
}
}

View File

@@ -0,0 +1,24 @@
import React from 'react';
import { Link } from 'react-router-dom';
import './Header.css';
const Header: React.FC = () => {
return (
<header className="header">
<div className="container">
<div className="nav-brand">
<Link to="/" className="brand-link">
<h1>🍳 Rezepte Klaus</h1>
</Link>
</div>
<nav className="nav-menu">
<Link to="/" className="nav-link">Alle Rezepte</Link>
<Link to="/recipes/new" className="nav-link">Neues Rezept</Link>
<Link to="/ingredients" className="nav-link">Zutaten</Link>
</nav>
</div>
</header>
);
};
export default Header;

View File

@@ -0,0 +1,259 @@
import React, { useState } from 'react';
import { useNavigate, Link } from 'react-router-dom';
import { recipeApi } from '../services/api';
import './RecipeEdit.css'; // Reuse the same styles
const RecipeCreate: React.FC = () => {
const navigate = useNavigate();
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [success, setSuccess] = useState(false);
// Form state
const [formData, setFormData] = useState({
title: '',
description: '',
category: '',
servings: 4,
ingredients: '',
preparation: '',
instructions: '',
comment: '',
recipeNumber: ''
});
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
const { name, value } = e.target;
setFormData(prev => ({
...prev,
[name]: name === 'servings' ? parseInt(value) || 1 : value
}));
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setLoading(true);
setError(null);
try {
// Validation
if (!formData.title.trim()) {
throw new Error('Titel ist erforderlich');
}
const response = await recipeApi.createRecipe(formData);
if (response.success) {
setSuccess(true);
// Redirect to the new recipe detail page after a short delay
setTimeout(() => {
navigate(`/recipes/${response.data.id}`);
}, 1500);
} else {
setError('Fehler beim Erstellen des Rezepts');
}
} catch (err) {
setError(err instanceof Error ? err.message : 'Unbekannter Fehler');
console.error('Error creating recipe:', err);
} finally {
setLoading(false);
}
};
if (success) {
return (
<div className="recipe-edit">
<div className="success-message">
<h2> Rezept erfolgreich erstellt!</h2>
<p>Sie werden zur Rezept-Detailseite weitergeleitet...</p>
</div>
</div>
);
}
return (
<div className="recipe-edit">
{/* Header */}
<div className="recipe-header">
<div className="breadcrumb">
<Link to="/" className="breadcrumb-link">Alle Rezepte</Link>
<span className="breadcrumb-separator"></span>
<span className="breadcrumb-current">Neues Rezept</span>
</div>
<div className="recipe-actions">
<button onClick={() => navigate(-1)} className="back-button">
Zurück
</button>
</div>
</div>
{/* Form */}
<div className="recipe-form-container">
<form onSubmit={handleSubmit} className="recipe-form">
<h1>Neues Rezept erstellen</h1>
{error && (
<div className="error-message">
<span className="error-icon"></span>
{error}
</div>
)}
<div className="form-row">
{/* Left Column */}
<div className="form-column">
<div className="form-group">
<label htmlFor="title">Titel *</label>
<input
type="text"
id="title"
name="title"
value={formData.title}
onChange={handleInputChange}
placeholder="Name des Rezepts..."
required
/>
</div>
<div className="form-group">
<label htmlFor="recipeNumber">Rezeptnummer</label>
<input
type="text"
id="recipeNumber"
name="recipeNumber"
value={formData.recipeNumber}
onChange={handleInputChange}
placeholder="z.B. R031"
/>
</div>
<div className="form-group">
<label htmlFor="category">Kategorie</label>
<select
id="category"
name="category"
value={formData.category}
onChange={handleInputChange}
>
<option value="">Kategorie wählen...</option>
<option value="Vorspeise">Vorspeise</option>
<option value="Hauptgericht">Hauptgericht</option>
<option value="Nachspeise">Nachspeise</option>
<option value="Beilage">Beilage</option>
<option value="Suppe">Suppe</option>
<option value="Salat">Salat</option>
<option value="Fleisch">Fleisch</option>
<option value="Fisch">Fisch</option>
<option value="Vegetarisch">Vegetarisch</option>
<option value="Vegan">Vegan</option>
<option value="Dessert">Dessert</option>
<option value="Getränk">Getränk</option>
</select>
</div>
<div className="form-group">
<label htmlFor="servings">Portionen</label>
<input
type="number"
id="servings"
name="servings"
value={formData.servings}
onChange={handleInputChange}
min="1"
max="50"
/>
</div>
<div className="form-group">
<label htmlFor="description">Beschreibung</label>
<textarea
id="description"
name="description"
value={formData.description}
onChange={handleInputChange}
rows={4}
placeholder="Kurze Beschreibung des Rezepts..."
/>
</div>
<div className="form-group">
<label htmlFor="ingredients">Zutaten</label>
<textarea
id="ingredients"
name="ingredients"
value={formData.ingredients}
onChange={handleInputChange}
rows={8}
placeholder="Eine Zutat pro Zeile...&#10;z.B.:&#10;500g Mehl&#10;2 Eier&#10;250ml Milch"
/>
</div>
</div>
{/* Right Column - now empty or for other content */}
<div className="form-column">
{/* Right column is now available for other fields if needed */}
</div>
</div>
{/* Full Width Sections */}
<div className="form-group">
<label htmlFor="preparation">Vorbereitung</label>
<textarea
id="preparation"
name="preparation"
value={formData.preparation}
onChange={handleInputChange}
rows={4}
placeholder="Vorbereitungsschritte..."
/>
</div>
<div className="form-group">
<label htmlFor="instructions">Zubereitung</label>
<textarea
id="instructions"
name="instructions"
value={formData.instructions}
onChange={handleInputChange}
rows={8}
placeholder="Detaillierte Zubereitungsschritte...&#10;Ein Schritt pro Zeile für optimale Darstellung mit Bildern."
/>
</div>
<div className="form-group">
<label htmlFor="comment">Tipps & Kommentare</label>
<textarea
id="comment"
name="comment"
value={formData.comment}
onChange={handleInputChange}
rows={3}
placeholder="Zusätzliche Tipps oder Anmerkungen..."
/>
</div>
{/* Form Actions */}
<div className="form-actions">
<button
type="button"
onClick={() => navigate('/')}
className="cancel-button"
>
Abbrechen
</button>
<button
type="submit"
disabled={loading}
className="save-button"
>
{loading ? 'Wird erstellt...' : 'Rezept erstellen'}
</button>
</div>
</form>
</div>
</div>
);
};
export default RecipeCreate;

View File

@@ -0,0 +1,561 @@
/* Recipe Detail Layout */
.recipe-detail {
max-width: 1400px; /* Increased from 1200px */
margin: 0 auto;
padding: 20px;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
/* Main Content */
.recipe-content {
max-width: 1200px; /* Increased from 900px */
margin: 0 auto;
width: 100%;
}
/* Recipe Info Section */
.recipe-info {
background: white;
border-radius: 12px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
padding: 30px;
}
/* Two Column Layout for Desktop */
.recipe-columns {
display: flex;
gap: 40px; /* Increased from 30px */
margin-top: 30px;
}
.recipe-sidebar {
flex: 0 0 400px; /* Increased from 350px */
background: #f8f9fa;
border-radius: 8px;
padding: 25px; /* Increased from 20px */
}
.recipe-main-content {
flex: 1;
}
/* Header */
.recipe-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 30px;
padding-bottom: 20px;
border-bottom: 2px solid #e0e0e0;
}
.breadcrumb {
display: flex;
align-items: center;
gap: 8px;
color: #666;
font-size: 14px;
}
.breadcrumb-link {
color: #007bff;
text-decoration: none;
transition: color 0.3s ease;
}
.breadcrumb-link:hover {
color: #0056b3;
text-decoration: underline;
}
.breadcrumb-separator {
color: #999;
font-weight: bold;
}
.breadcrumb-current {
color: #333;
font-weight: 500;
}
.recipe-actions {
display: flex;
gap: 10px;
}
.edit-button, .back-button {
padding: 8px 16px;
border: none;
border-radius: 6px;
text-decoration: none;
font-size: 14px;
font-weight: 500;
cursor: pointer;
transition: all 0.3s ease;
display: inline-flex;
align-items: center;
gap: 5px;
}
.edit-button {
background: #28a745;
color: white;
}
.edit-button:hover {
background: #218838;
transform: translateY(-1px);
}
.back-button {
background: #6c757d;
color: white;
}
.back-button:hover {
background: #545b62;
transform: translateY(-1px);
}
/* Main Content */
.recipe-content {
max-width: 900px;
margin: 0 auto;
width: 100%;
display: block; /* Ensure block layout */
}
/* Recipe Info Section */
.recipe-info {
background: white;
border-radius: 12px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
padding: 30px;
display: block; /* Force block layout instead of flex */
width: 100%;
}
/* Force single column layout for all children */
.recipe-info > * {
width: 100%;
display: block; /* Force all children to be block elements */
margin-bottom: 20px;
}
/* Ensure no grid or multi-column layouts */
.recipe-info .recipe-description,
.recipe-info .recipe-meta,
.recipe-info .recipe-section {
width: 100% !important;
display: block !important;
float: none !important;
position: relative !important;
}
.recipe-title-section {
display: flex;
align-items: center;
gap: 15px;
margin-bottom: 20px;
padding-bottom: 20px;
border-bottom: 1px solid #e0e0e0;
}
.recipe-title {
margin: 0;
font-size: 2.2em;
font-weight: 700;
color: #333;
line-height: 1.2;
}
.recipe-number {
background: #007bff;
color: white;
padding: 4px 12px;
border-radius: 20px;
font-size: 0.9em;
font-weight: 600;
flex-shrink: 0;
}
/* Main Recipe Image */
.main-recipe-image {
margin: 25px 0;
border-radius: 12px;
overflow: hidden;
box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
background: #f8f9fa;
max-height: 400px;
}
.main-recipe-image img {
width: 100%;
height: auto;
max-height: 400px;
object-fit: cover;
display: block;
transition: transform 0.3s ease;
}
.main-recipe-image:hover img {
transform: scale(1.02);
}
.recipe-description {
margin-bottom: 25px;
padding: 20px;
background: #f8f9fa;
border-radius: 8px;
border-left: 4px solid #007bff;
}
.recipe-description p {
margin: 0;
font-size: 1.1em;
line-height: 1.6;
color: #555;
}
/* Recipe Links */
.recipe-link {
color: #007bff;
text-decoration: none;
border-bottom: 1px dotted #007bff;
transition: all 0.3s ease;
}
.recipe-link:hover {
color: #0056b3;
text-decoration: none;
border-bottom: 1px solid #0056b3;
background-color: rgba(0, 123, 255, 0.1);
padding: 1px 2px;
border-radius: 3px;
}
.recipe-meta {
display: block !important; /* Force block layout instead of flex */
gap: 0 !important;
margin-bottom: 30px !important;
padding: 20px !important;
background: #f8f9fa !important;
border-radius: 8px !important;
width: 100% !important;
grid-template-columns: none !important;
flex-direction: column !important;
}
.meta-item {
display: block !important; /* Force block layout */
margin-bottom: 15px !important;
width: 100% !important;
float: none !important;
flex: none !important;
}
.meta-label {
font-size: 0.9em;
color: #666;
font-weight: 500;
text-transform: uppercase;
letter-spacing: 0.5px;
}
.meta-value {
font-size: 1.1em;
font-weight: 600;
color: #333;
}
/* Recipe Sections */
.recipe-section {
margin-bottom: 30px;
}
.recipe-section h3 {
margin: 0 0 15px 0;
font-size: 1.4em;
font-weight: 600;
color: #333;
padding-bottom: 8px;
border-bottom: 2px solid #007bff;
display: inline-block;
}
/* Ingredients */
.ingredients-content {
background: #f8f9fa;
border-radius: 8px;
padding: 20px;
}
.ingredient-item {
padding: 8px 0;
position: relative;
padding-left: 20px;
}
.ingredient-item:last-child {
border-bottom: none;
}
.ingredient-item::before {
content: "•";
position: absolute;
left: 0;
color: #007bff;
font-weight: bold;
font-size: 1.2em;
}
/* Preparation */
.preparation-content {
background: #fff3cd;
border-radius: 8px;
padding: 20px;
border-left: 4px solid #ffc107;
}
.preparation-step {
margin: 0 0 5px 0;
line-height: 1.4;
}
.preparation-step:last-child {
margin-bottom: 0;
}
/* Instructions */
.instructions-content {
display: flex;
flex-direction: column;
gap: 20px;
}
.instruction-step-with-image {
display: flex;
gap: 20px;
padding: 20px;
background: #f8f9fa;
border-radius: 8px;
border-left: 4px solid #28a745;
align-items: flex-start;
}
.step-image {
flex-shrink: 0;
width: 200px;
height: 150px;
border-radius: 8px;
overflow: hidden;
background: #e9ecef;
display: flex;
align-items: center;
justify-content: center;
}
.step-image img {
width: 100%;
height: 100%;
object-fit: cover;
transition: transform 0.3s ease;
}
.step-image img:hover {
transform: scale(1.05);
}
.instruction-step {
display: flex;
gap: 15px;
flex: 1;
align-items: flex-start;
}
.step-number {
background: #28a745;
color: white;
width: 30px;
height: 30px;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
font-weight: bold;
font-size: 14px;
flex-shrink: 0;
margin-top: 2px;
}
.step-text {
margin: 0;
line-height: 1.6;
color: #333;
flex: 1;
}
/* Comment */
.comment-content {
background: #d1ecf1;
border-radius: 8px;
padding: 20px;
border-left: 4px solid #17a2b8;
}
.recipe-comment {
margin: 0;
font-style: italic;
line-height: 1.6;
color: #333;
}
/* Error States */
.error, .not-found {
text-align: center;
padding: 60px 20px;
background: white;
border-radius: 12px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}
.error h3, .not-found h3 {
color: #dc3545;
margin-bottom: 15px;
}
.error-actions {
margin-top: 20px;
display: flex;
justify-content: center;
gap: 15px;
}
.retry-button {
background: #007bff;
color: white;
border: none;
padding: 10px 20px;
border-radius: 6px;
cursor: pointer;
font-weight: 500;
transition: all 0.3s ease;
}
.retry-button:hover {
background: #0056b3;
transform: translateY(-1px);
}
/* Loading */
.loading {
text-align: center;
padding: 60px 20px;
font-size: 1.2em;
color: #666;
}
/* Responsive Design */
/* Large screens - extra wide layout */
@media (min-width: 1400px) {
.recipe-detail {
max-width: 1600px;
padding: 30px;
}
.recipe-content {
max-width: 1400px;
}
.recipe-columns {
gap: 50px;
}
.recipe-sidebar {
flex: 0 0 450px;
padding: 30px;
}
.recipe-info {
padding: 40px;
}
}
@media (max-width: 768px) {
.recipe-detail {
padding: 15px;
}
.recipe-header {
flex-direction: column;
gap: 15px;
align-items: flex-start;
}
.recipe-content {
max-width: 100%;
}
.recipe-info {
padding: 20px;
}
.recipe-title {
font-size: 1.8em;
}
.recipe-meta {
flex-direction: column;
gap: 15px;
}
/* Stack columns on mobile */
.recipe-columns {
flex-direction: column;
gap: 20px;
}
.recipe-sidebar {
flex: none;
}
.instruction-step-with-image {
flex-direction: column;
gap: 15px;
}
.step-image {
width: 100%;
height: 200px;
align-self: center;
}
.instruction-step {
flex-direction: column;
gap: 10px;
}
.step-number {
align-self: flex-start;
}
}
@media (max-width: 480px) {
.recipe-actions {
flex-direction: column;
width: 100%;
}
.edit-button, .back-button {
justify-content: center;
}
.breadcrumb {
flex-wrap: wrap;
}
.thumbnail {
width: 50px;
height: 50px;
}
}/* Force reload */

View File

@@ -0,0 +1,287 @@
import React, { useState, useEffect } from 'react';
import { useParams, Link, useNavigate } from 'react-router-dom';
import type { Recipe } from '../services/api';
import { recipeApi, imageApi } from '../services/api';
import './RecipeDetail.css';
// Helper function to convert URLs in text to clickable links
const linkifyText = (text: string): React.ReactNode => {
const urlRegex = /(https?:\/\/[^\s]+)/g;
const parts = text.split(urlRegex);
return parts.map((part, index) => {
if (urlRegex.test(part)) {
return (
<a
key={index}
href={part}
target="_blank"
rel="noopener noreferrer"
className="recipe-link"
>
{part}
</a>
);
}
return part;
});
};
const RecipeDetail: React.FC = () => {
const { id } = useParams<{ id: string }>();
const navigate = useNavigate();
const [recipe, setRecipe] = useState<Recipe | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
const loadRecipe = async () => {
if (!id) {
setError('Keine Rezept-ID angegeben');
setLoading(false);
return;
}
try {
setError(null);
const response = await recipeApi.getRecipe(parseInt(id));
if (response.success) {
setRecipe(response.data);
} else {
setError('Rezept konnte nicht geladen werden');
}
} catch (err) {
setError('Verbindungsfehler - Ist der Server gestartet?');
console.error('Error loading recipe:', err);
} finally {
setLoading(false);
}
};
loadRecipe();
}, [id]);
if (loading) {
return (
<div className="recipe-detail">
<div className="loading">Lade Rezept...</div>
</div>
);
}
if (error) {
return (
<div className="recipe-detail">
<div className="error">
<h3>Fehler</h3>
<p>{error}</p>
<div className="error-actions">
<button onClick={() => window.location.reload()} className="retry-button">
Erneut versuchen
</button>
<Link to="/" className="back-button">
Zurück zur Liste
</Link>
</div>
</div>
</div>
);
}
if (!recipe) {
return (
<div className="recipe-detail">
<div className="not-found">
<h3>Rezept nicht gefunden</h3>
<p>Das angeforderte Rezept existiert nicht.</p>
<Link to="/" className="back-button">
Zurück zur Liste
</Link>
</div>
</div>
);
}
return (
<div className="recipe-detail">
{/* Header */}
<div className="recipe-header">
<div className="breadcrumb">
<Link to="/" className="breadcrumb-link">Alle Rezepte</Link>
<span className="breadcrumb-separator"></span>
<span className="breadcrumb-current">{recipe.title}</span>
</div>
<div className="recipe-actions">
<Link to={`/recipes/${recipe.id}/edit`} className="edit-button">
Bearbeiten
</Link>
<button onClick={() => navigate(-1)} className="back-button">
Zurück
</button>
</div>
</div>
{/* Main Content */}
<div className="recipe-content">
{/* Recipe Info - Full Width */}
<div className="recipe-info">
<div className="recipe-title-section">
<h1 className="recipe-title">{recipe.title}</h1>
{recipe.recipeNumber && (
<span className="recipe-number">#{recipe.recipeNumber}</span>
)}
</div>
{/* Hauptbild (xxx_0.jpg) */}
{recipe.images && recipe.images.length > 0 && (
<div className="main-recipe-image">
{(() => {
// Find the main image (xxx_0.jpg)
const mainImage = recipe.images.find(image => {
const fileName = image.filePath.split('/').pop() || '';
return fileName.includes('_0.jpg');
});
if (mainImage) {
return (
<img
src={imageApi.getImageUrl(mainImage.filePath)}
alt={`${recipe.title} - Hauptbild`}
onError={(e) => {
e.currentTarget.style.display = 'none';
}}
/>
);
}
return null;
})()}
</div>
)}
<div className="recipe-meta">
{recipe.category && (
<div className="meta-item">
<span className="meta-label">Kategorie:</span>
<span className="meta-value">{recipe.category}</span>
</div>
)}
<div className="meta-item">
<span className="meta-label">Portionen:</span>
<span className="meta-value">👥 {recipe.servings}</span>
</div>
</div>
</div>
{/* Two Column Layout for Description/Ingredients and Preparation */}
<div className="recipe-columns">
{/* Left Column - Description and Ingredients */}
<div className="recipe-sidebar">
{recipe.description && (
<div className="recipe-description">
<h3>Beschreibung</h3>
<p>{linkifyText(recipe.description)}</p>
</div>
)}
{/* Zutaten */}
{recipe.ingredients && (
<div className="recipe-section">
<h3>Zutaten</h3>
<div className="ingredients-content">
{recipe.ingredients.split('\n').map((ingredient, index) => (
<div key={index} className="ingredient-item">
{ingredient.trim()}
</div>
))}
</div>
</div>
)}
</div>
{/* Right Column - Preparation and Instructions */}
<div className="recipe-main-content">
{/* Vorbereitung */}
{recipe.preparation && (
<div className="recipe-section">
<h3>Vorbereitung</h3>
<div className="preparation-content">
{recipe.preparation.split('\n').map((step, index) => (
<p key={index} className="preparation-step">
{step.trim()}
</p>
))}
</div>
</div>
)}
{/* Anweisungen */}
{recipe.instructions && (
<div className="recipe-section">
<h3>Zubereitung</h3>
<div className="instructions-content">
{(() => {
// Get all preparation images (exclude main image _0.jpg)
const preparationImages = recipe.images
?.filter(image => {
const fileName = image.filePath.split('/').pop() || '';
// Match pattern like R005_1.jpg, R005_2.jpg, etc. but not R005_0.jpg
return fileName.match(/_[1-9]\d*\.jpg$/);
})
.sort((a, b) => {
// Sort by the number in the filename
const getNumber = (path: string) => {
const match = path.match(/_(\d+)\.jpg$/);
return match ? parseInt(match[1]) : 0;
};
return getNumber(a.filePath) - getNumber(b.filePath);
}) || [];
return recipe.instructions.split('\n').map((instruction, index) => {
// Get the corresponding image for this step
const stepImage = preparationImages[index];
return (
<div key={index} className="instruction-step-with-image">
{stepImage && (
<div className="step-image">
<img
src={imageApi.getImageUrl(stepImage.filePath)}
alt={`${recipe.title} - Schritt ${index + 1}`}
onError={(e) => {
e.currentTarget.style.display = 'none';
}}
/>
</div>
)}
<div className="instruction-step">
<span className="step-number">{index + 1}</span>
<p className="step-text">{instruction.trim()}</p>
</div>
</div>
);
});
})()}
</div>
</div>
)}
{/* Kommentar */}
{recipe.comment && (
<div className="recipe-section">
<h3>Tipp</h3>
<div className="comment-content">
<p className="recipe-comment">{recipe.comment}</p>
</div>
</div>
)}
</div>
</div>
</div>
</div>
);
};
export default RecipeDetail;

View File

@@ -0,0 +1,64 @@
/* ULTIMATE OVERRIDE - This will force single column no matter what */
html body div#root div.App main.main-content div.recipe-detail,
html body div#root div.App main.main-content div.recipe-detail *,
.recipe-detail,
.recipe-detail * {
display: block !important;
width: 100% !important;
max-width: 100% !important;
float: none !important;
position: relative !important;
left: auto !important;
right: auto !important;
top: auto !important;
bottom: auto !important;
grid-template-columns: none !important;
grid-template-areas: none !important;
grid-column: auto !important;
grid-row: auto !important;
columns: none !important;
column-count: 1 !important;
column-width: auto !important;
flex-direction: column !important;
flex-wrap: nowrap !important;
flex-basis: auto !important;
flex-grow: 0 !important;
flex-shrink: 0 !important;
align-items: stretch !important;
justify-content: flex-start !important;
margin-left: 0 !important;
margin-right: 0 !important;
box-sizing: border-box !important;
}
/* Even more specific - target the exact structure */
.recipe-detail .recipe-content .recipe-info {
background: white !important;
border-radius: 12px !important;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1) !important;
padding: 30px !important;
border: 5px solid lime !important; /* DEBUGGING: Bright green border */
}
.recipe-detail .recipe-content .recipe-info > * {
width: 100% !important;
display: block !important;
margin-bottom: 20px !important;
border: 2px solid orange !important; /* DEBUGGING: Orange border for each section */
}
/* Force specific elements to be single column */
.recipe-detail .recipe-meta {
display: block !important;
width: 100% !important;
}
.recipe-detail .recipe-description {
display: block !important;
width: 100% !important;
}
.recipe-detail .recipe-section {
display: block !important;
width: 100% !important;
}

View File

@@ -0,0 +1,403 @@
/* Recipe Edit Styles */
.recipe-edit {
max-width: 1200px;
margin: 0 auto;
padding: 20px;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
/* Header */
.recipe-edit-header {
margin-bottom: 30px;
padding-bottom: 20px;
border-bottom: 2px solid #e0e0e0;
}
.recipe-edit-header h1 {
margin: 15px 0 0 0;
font-size: 2.2em;
font-weight: 700;
color: #333;
}
.breadcrumb {
display: flex;
align-items: center;
gap: 8px;
color: #666;
font-size: 14px;
margin-bottom: 10px;
}
.breadcrumb-link {
color: #007bff;
text-decoration: none;
transition: color 0.3s ease;
}
.breadcrumb-link:hover {
color: #0056b3;
text-decoration: underline;
}
.breadcrumb-separator {
color: #999;
font-weight: bold;
}
.breadcrumb-current {
color: #333;
font-weight: 500;
}
/* Messages */
.message {
display: flex;
align-items: center;
gap: 12px;
padding: 15px 20px;
margin-bottom: 20px;
border-radius: 8px;
font-weight: 500;
}
.message-icon {
font-size: 18px;
}
.error-message {
background: #f8d7da;
border: 1px solid #f5c6cb;
color: #721c24;
}
.success-message {
background: #d4edda;
border: 1px solid #c3e6cb;
color: #155724;
}
/* Form Layout */
.recipe-form {
background: white;
border-radius: 12px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
padding: 30px;
}
.form-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 40px;
margin-bottom: 30px;
}
.form-section h3 {
margin: 0 0 25px 0;
font-size: 1.4em;
font-weight: 600;
color: #333;
padding-bottom: 10px;
border-bottom: 2px solid #007bff;
display: inline-block;
}
/* Form Groups */
.form-group {
margin-bottom: 20px;
}
.form-row {
display: grid;
grid-template-columns: 1fr 120px;
gap: 20px;
margin-bottom: 20px;
}
.form-group label {
display: block;
margin-bottom: 8px;
font-weight: 600;
color: #333;
font-size: 14px;
}
.form-group label.required::after {
content: " *";
color: #dc3545;
font-weight: bold;
}
/* Form Inputs */
.form-group input,
.form-group textarea,
.form-group select {
width: 100%;
padding: 12px 16px;
border: 2px solid #e0e0e0;
border-radius: 8px;
font-size: 14px;
font-family: inherit;
transition: all 0.3s ease;
background: white;
}
.form-group input:focus,
.form-group textarea:focus,
.form-group select:focus {
outline: none;
border-color: #007bff;
box-shadow: 0 0 0 3px rgba(0, 123, 255, 0.1);
}
.form-group input:invalid,
.form-group textarea:invalid {
border-color: #dc3545;
}
.form-group textarea {
resize: vertical;
min-height: 80px;
line-height: 1.5;
}
.form-group select {
cursor: pointer;
background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 20 20'%3e%3cpath stroke='%236b7280' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='m6 8 4 4 4-4'/%3e%3c/svg%3e");
background-position: right 12px center;
background-repeat: no-repeat;
background-size: 16px;
padding-right: 40px;
appearance: none;
}
.form-hint {
margin-top: 5px;
font-size: 12px;
color: #666;
font-style: italic;
}
/* Form Actions */
.form-actions {
display: flex;
justify-content: flex-end;
gap: 15px;
padding-top: 20px;
border-top: 1px solid #e0e0e0;
}
.cancel-button,
.save-button {
padding: 12px 24px;
border: none;
border-radius: 8px;
font-size: 16px;
font-weight: 600;
cursor: pointer;
transition: all 0.3s ease;
display: flex;
align-items: center;
gap: 8px;
min-width: 120px;
justify-content: center;
}
.cancel-button {
background: #6c757d;
color: white;
}
.cancel-button:hover:not(:disabled) {
background: #545b62;
transform: translateY(-1px);
}
.save-button {
background: #28a745;
color: white;
}
.save-button:hover:not(:disabled) {
background: #218838;
transform: translateY(-1px);
}
.cancel-button:disabled,
.save-button:disabled {
opacity: 0.6;
cursor: not-allowed;
transform: none;
}
/* Loading Spinner */
.loading-spinner {
width: 16px;
height: 16px;
border: 2px solid rgba(255, 255, 255, 0.3);
border-radius: 50%;
border-top-color: white;
animation: spin 1s ease-in-out infinite;
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}
/* Error States */
.error {
text-align: center;
padding: 60px 20px;
background: white;
border-radius: 12px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}
.error h3 {
color: #dc3545;
margin-bottom: 15px;
}
.error-actions {
margin-top: 20px;
display: flex;
justify-content: center;
gap: 15px;
}
.retry-button {
background: #007bff;
color: white;
border: none;
padding: 10px 20px;
border-radius: 6px;
cursor: pointer;
font-weight: 500;
transition: all 0.3s ease;
}
.retry-button:hover {
background: #0056b3;
transform: translateY(-1px);
}
.back-button {
background: #6c757d;
color: white;
text-decoration: none;
padding: 10px 20px;
border-radius: 6px;
font-weight: 500;
transition: all 0.3s ease;
display: inline-block;
}
.back-button:hover {
background: #545b62;
transform: translateY(-1px);
}
/* Loading */
.loading {
text-align: center;
padding: 60px 20px;
font-size: 1.2em;
color: #666;
}
/* Character Counter */
.form-group[data-maxlength]::after {
content: attr(data-current) "/" attr(data-maxlength);
font-size: 12px;
color: #666;
float: right;
margin-top: 5px;
}
/* Responsive Design */
@media (max-width: 768px) {
.recipe-edit {
padding: 15px;
}
.form-grid {
grid-template-columns: 1fr;
gap: 30px;
}
.form-row {
grid-template-columns: 1fr;
gap: 15px;
}
.recipe-form {
padding: 20px;
}
.form-actions {
flex-direction: column-reverse;
}
.cancel-button,
.save-button {
width: 100%;
}
.recipe-edit-header h1 {
font-size: 1.8em;
}
}
@media (max-width: 480px) {
.breadcrumb {
flex-wrap: wrap;
}
.form-section h3 {
font-size: 1.2em;
}
.message {
padding: 12px 15px;
}
.form-group input,
.form-group textarea,
.form-group select {
padding: 10px 14px;
font-size: 16px; /* Prevents zoom on iOS */
}
}
/* High Contrast Mode */
@media (prefers-contrast: high) {
.form-group input,
.form-group textarea,
.form-group select {
border-width: 3px;
}
.form-group input:focus,
.form-group textarea:focus,
.form-group select:focus {
border-color: #000;
}
}
/* Reduced Motion */
@media (prefers-reduced-motion: reduce) {
.form-group input,
.form-group textarea,
.form-group select,
.cancel-button,
.save-button,
.breadcrumb-link {
transition: none;
}
.loading-spinner {
animation: none;
}
}

View File

@@ -0,0 +1,379 @@
import React, { useState, useEffect } from 'react';
import { useParams, useNavigate, Link } from 'react-router-dom';
import type { Recipe } from '../services/api';
import { recipeApi } from '../services/api';
import './RecipeEdit.css';
interface FormData {
title: string;
description: string;
category: string;
servings: number;
ingredients: string;
preparation: string;
instructions: string;
comment: string;
}
const RecipeEdit: React.FC = () => {
const { id } = useParams<{ id: string }>();
const navigate = useNavigate();
const [recipe, setRecipe] = useState<Recipe | null>(null);
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
const [successMessage, setSuccessMessage] = useState<string | null>(null);
const [formData, setFormData] = useState<FormData>({
title: '',
description: '',
category: '',
servings: 1,
ingredients: '',
preparation: '',
instructions: '',
comment: '',
});
// Load recipe data
useEffect(() => {
const loadRecipe = async () => {
if (!id) {
setError('Keine Rezept-ID angegeben');
setLoading(false);
return;
}
try {
setError(null);
const response = await recipeApi.getRecipe(parseInt(id));
if (response.success) {
const recipeData = response.data;
setRecipe(recipeData);
setFormData({
title: recipeData.title || '',
description: recipeData.description || '',
category: recipeData.category || '',
servings: recipeData.servings || 1,
ingredients: recipeData.ingredients || '',
preparation: recipeData.preparation || '',
instructions: recipeData.instructions || '',
comment: recipeData.comment || '',
});
} else {
setError('Rezept konnte nicht geladen werden');
}
} catch (err) {
setError('Verbindungsfehler - Ist der Server gestartet?');
console.error('Error loading recipe:', err);
} finally {
setLoading(false);
}
};
loadRecipe();
}, [id]);
// Handle form field changes
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
const { name, value } = e.target;
setFormData(prev => ({
...prev,
[name]: name === 'servings' ? parseInt(value) || 1 : value
}));
// Clear messages when user starts typing
if (error) setError(null);
if (successMessage) setSuccessMessage(null);
};
// Handle form submission
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!id || !recipe) {
setError('Rezept nicht gefunden');
return;
}
// Basic validation
if (!formData.title.trim()) {
setError('Titel ist erforderlich');
return;
}
if (formData.servings < 1 || formData.servings > 50) {
setError('Portionen müssen zwischen 1 und 50 liegen');
return;
}
setSaving(true);
setError(null);
setSuccessMessage(null);
try {
const updateData = {
...formData,
title: formData.title.trim(),
description: formData.description.trim() || undefined,
category: formData.category.trim() || undefined,
ingredients: formData.ingredients.trim() || undefined,
preparation: formData.preparation.trim() || undefined,
instructions: formData.instructions.trim() || undefined,
comment: formData.comment.trim() || undefined,
};
const response = await recipeApi.updateRecipe(parseInt(id), updateData);
if (response.success) {
setSuccessMessage('Rezept erfolgreich gespeichert!');
setRecipe(response.data);
// Redirect after successful save
setTimeout(() => {
navigate(`/recipes/${id}`);
}, 1500);
} else {
setError(response.message || 'Fehler beim Speichern des Rezepts');
}
} catch (err) {
setError('Verbindungsfehler beim Speichern');
console.error('Error updating recipe:', err);
} finally {
setSaving(false);
}
};
// Handle cancel
const handleCancel = () => {
navigate(`/recipes/${id}`);
};
if (loading) {
return (
<div className="recipe-edit">
<div className="loading">Lade Rezept...</div>
</div>
);
}
if (error && !recipe) {
return (
<div className="recipe-edit">
<div className="error">
<h3>Fehler</h3>
<p>{error}</p>
<div className="error-actions">
<button onClick={() => window.location.reload()} className="retry-button">
Erneut versuchen
</button>
<Link to="/" className="back-button">
Zurück zur Liste
</Link>
</div>
</div>
</div>
);
}
return (
<div className="recipe-edit">
{/* Header */}
<div className="recipe-edit-header">
<div className="breadcrumb">
<Link to="/" className="breadcrumb-link">Alle Rezepte</Link>
<span className="breadcrumb-separator"></span>
<Link to={`/recipes/${id}`} className="breadcrumb-link">{recipe?.title}</Link>
<span className="breadcrumb-separator"></span>
<span className="breadcrumb-current">Bearbeiten</span>
</div>
<h1>Rezept bearbeiten</h1>
</div>
{/* Messages */}
{error && (
<div className="message error-message">
<span className="message-icon"></span>
<span className="message-text">{error}</span>
</div>
)}
{successMessage && (
<div className="message success-message">
<span className="message-icon"></span>
<span className="message-text">{successMessage}</span>
</div>
)}
{/* Form */}
<form onSubmit={handleSubmit} className="recipe-form">
<div className="form-grid">
{/* Left Column - Basic Info */}
<div className="form-section">
<h3>Grundinformationen</h3>
<div className="form-group">
<label htmlFor="title" className="required">Titel</label>
<input
type="text"
id="title"
name="title"
value={formData.title}
onChange={handleInputChange}
placeholder="z.B. Pasta Gamberoni"
maxLength={200}
required
/>
</div>
<div className="form-row">
<div className="form-group">
<label htmlFor="category">Kategorie</label>
<select
id="category"
name="category"
value={formData.category}
onChange={handleInputChange}
>
<option value="">Kategorie wählen</option>
<option value="Vegan">Vegan</option>
<option value="Vegetarisch">Vegetarisch</option>
<option value="Fleisch">Fleisch</option>
<option value="Fisch">Fisch</option>
<option value="Fisch, Garnelen">Fisch, Garnelen</option>
<option value="Dessert">Dessert</option>
<option value="Suppe">Suppe</option>
<option value="Salat">Salat</option>
<option value="Beilage">Beilage</option>
</select>
</div>
<div className="form-group">
<label htmlFor="servings" className="required">Portionen</label>
<input
type="number"
id="servings"
name="servings"
value={formData.servings}
onChange={handleInputChange}
min="1"
max="50"
required
/>
</div>
</div>
<div className="form-group">
<label htmlFor="description">Beschreibung</label>
<textarea
id="description"
name="description"
value={formData.description}
onChange={handleInputChange}
placeholder="Kurze Beschreibung des Rezepts..."
rows={4}
maxLength={1000}
/>
</div>
</div>
{/* Right Column - Recipe Content */}
<div className="form-section">
<h3>Rezeptinhalt</h3>
<div className="form-group">
<label htmlFor="ingredients">Zutaten</label>
<textarea
id="ingredients"
name="ingredients"
value={formData.ingredients}
onChange={handleInputChange}
placeholder="Eine Zutat pro Zeile, z.B.&#10;200g Pasta&#10;400g Garnelen&#10;2 Knoblauchzehen"
rows={8}
maxLength={5000}
/>
<div className="form-hint">
Eine Zutat pro Zeile eingeben
</div>
</div>
<div className="form-group">
<label htmlFor="preparation">Vorbereitung</label>
<textarea
id="preparation"
name="preparation"
value={formData.preparation}
onChange={handleInputChange}
placeholder="Vorbereitungsschritte, z.B.&#10;Garnelen putzen&#10;Knoblauch schneiden"
rows={6}
maxLength={3000}
/>
</div>
<div className="form-group">
<label htmlFor="instructions">Zubereitung</label>
<textarea
id="instructions"
name="instructions"
value={formData.instructions}
onChange={handleInputChange}
placeholder="Detaillierte Zubereitungsschritte..."
rows={10}
maxLength={10000}
/>
<div className="form-hint">
Jeden Schritt in einer neuen Zeile beschreiben
</div>
</div>
<div className="form-group">
<label htmlFor="comment">Tipps & Hinweise</label>
<textarea
id="comment"
name="comment"
value={formData.comment}
onChange={handleInputChange}
placeholder="Zusätzliche Tipps oder Hinweise..."
rows={4}
maxLength={2000}
/>
</div>
</div>
</div>
{/* Form Actions */}
<div className="form-actions">
<button
type="button"
onClick={handleCancel}
className="cancel-button"
disabled={saving}
>
Abbrechen
</button>
<button
type="submit"
className="save-button"
disabled={saving}
>
{saving ? (
<>
<span className="loading-spinner"></span>
Speichert...
</>
) : (
<>
💾 Speichern
</>
)}
</button>
</div>
</form>
</div>
);
};
export default RecipeEdit;

View File

@@ -0,0 +1,362 @@
.recipe-list {
max-width: 1200px;
margin: 0 auto;
padding: 2rem 1rem;
}
.recipe-list-header {
margin-bottom: 2rem;
}
.recipe-list-header h2 {
color: #333;
margin-bottom: 1rem;
font-size: 2rem;
font-weight: 600;
display: flex;
align-items: center;
gap: 0.5rem;
}
.searching-indicator {
font-size: 1.2rem;
animation: pulse 1.5s ease-in-out infinite;
}
@keyframes pulse {
0%, 100% { opacity: 0.6; }
50% { opacity: 1; }
}
.filters {
display: flex;
gap: 1rem;
align-items: center;
flex-wrap: wrap;
}
.search-form {
display: flex;
gap: 0.5rem;
flex: 1;
min-width: 300px;
}
.search-input {
flex: 1;
padding: 0.75rem;
border: 2px solid #e1e5e9;
border-radius: 8px;
font-size: 1rem;
transition: border-color 0.3s ease;
}
.search-input:focus {
outline: none;
border-color: #667eea;
}
.search-button {
padding: 0.75rem 1rem;
background: #667eea;
color: white;
border: none;
border-radius: 8px;
cursor: pointer;
font-size: 1rem;
transition: background-color 0.3s ease;
}
.search-button:hover {
background: #5a6fd8;
}
.category-select {
padding: 0.75rem;
border: 2px solid #e1e5e9;
border-radius: 8px;
font-size: 1rem;
background: white;
cursor: pointer;
min-width: 180px;
}
.category-select:focus {
outline: none;
border-color: #667eea;
}
.recipes-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
gap: 2rem;
margin-bottom: 2rem;
}
.recipe-card {
background: white;
border-radius: 12px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
overflow: hidden;
transition: transform 0.3s ease, box-shadow 0.3s ease;
min-height: 450px; /* Stabile Mindesthöhe */
display: flex;
flex-direction: column;
}
.recipe-card:hover {
transform: translateY(-4px);
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
}
.recipe-image {
height: 200px;
overflow: hidden;
position: relative;
}
.recipe-image img {
width: 100%;
height: 100%;
object-fit: cover;
transition: transform 0.3s ease;
}
.recipe-card:hover .recipe-image img {
transform: scale(1.05);
}
.no-image {
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
font-size: 3rem;
color: #999;
}
.recipe-content {
padding: 1.5rem;
flex: 1; /* Nimmt verfügbaren Platz ein */
display: flex;
flex-direction: column;
}
.recipe-title {
color: #333;
margin: 0 0 0.5rem 0;
font-size: 1.3rem;
font-weight: 600;
line-height: 1.3;
min-height: 1.6em; /* Verhindert Layout-Sprünge */
display: -webkit-box;
-webkit-line-clamp: 2; /* Begrenzt auf 2 Zeilen */
line-clamp: 2; /* Standard property für Kompatibilität */
-webkit-box-orient: vertical;
overflow: hidden;
text-overflow: ellipsis;
word-break: break-word;
}
.recipe-description {
color: #666;
margin: 0 0 1rem 0;
line-height: 1.5;
font-size: 0.95rem;
min-height: 3em; /* Verhindert Layout-Sprünge */
display: -webkit-box;
-webkit-line-clamp: 3; /* Begrenzt auf 3 Zeilen */
line-clamp: 3; /* Standard property für Kompatibilität */
-webkit-box-orient: vertical;
overflow: hidden;
text-overflow: ellipsis;
}
.recipe-meta {
display: flex;
gap: 1rem;
margin-bottom: 1rem;
flex-wrap: wrap;
}
.recipe-category {
background: #667eea;
color: white;
padding: 0.25rem 0.75rem;
border-radius: 20px;
font-size: 0.8rem;
font-weight: 500;
}
.recipe-servings {
color: #666;
font-size: 0.9rem;
display: flex;
align-items: center;
gap: 0.25rem;
}
.recipe-actions {
display: flex;
gap: 0.75rem;
}
.view-button, .edit-button {
flex: 1;
text-align: center;
padding: 0.75rem;
border-radius: 8px;
text-decoration: none;
font-weight: 500;
font-size: 0.9rem;
transition: all 0.3s ease;
}
.view-button {
background: #667eea;
color: white;
}
.view-button:hover {
background: #5a6fd8;
transform: translateY(-1px);
}
.edit-button {
background: #f8f9fa;
color: #667eea;
border: 2px solid #667eea;
}
.edit-button:hover {
background: #667eea;
color: white;
transform: translateY(-1px);
}
.no-recipes {
text-align: center;
padding: 4rem 2rem;
color: #666;
}
.no-recipes h3 {
color: #333;
margin-bottom: 1rem;
font-size: 1.5rem;
}
.create-button {
display: inline-block;
margin-top: 1rem;
padding: 0.75rem 1.5rem;
background: #667eea;
color: white;
text-decoration: none;
border-radius: 8px;
font-weight: 500;
transition: background-color 0.3s ease;
}
.create-button:hover {
background: #5a6fd8;
}
.pagination {
display: flex;
justify-content: center;
align-items: center;
gap: 1rem;
margin-top: 2rem;
}
.pagination-button {
padding: 0.75rem 1.5rem;
background: #667eea;
color: white;
border: none;
border-radius: 8px;
cursor: pointer;
font-weight: 500;
transition: background-color 0.3s ease;
}
.pagination-button:hover:not(:disabled) {
background: #5a6fd8;
}
.pagination-button:disabled {
background: #ccc;
cursor: not-allowed;
}
.pagination-info {
color: #666;
font-weight: 500;
}
.loading, .error {
text-align: center;
padding: 4rem 2rem;
}
.loading {
color: #666;
font-size: 1.2rem;
}
.error {
color: #e74c3c;
}
.error h3 {
color: #e74c3c;
margin-bottom: 1rem;
}
.retry-button {
margin-top: 1rem;
padding: 0.75rem 1.5rem;
background: #e74c3c;
color: white;
border: none;
border-radius: 8px;
cursor: pointer;
font-weight: 500;
transition: background-color 0.3s ease;
}
.retry-button:hover {
background: #c0392b;
}
@media (max-width: 768px) {
.recipe-list {
padding: 1rem 0.5rem;
}
.filters {
flex-direction: column;
align-items: stretch;
}
.search-form {
min-width: auto;
}
.recipes-grid {
grid-template-columns: 1fr;
gap: 1rem;
}
.recipe-actions {
flex-direction: column;
}
.pagination {
flex-direction: column;
gap: 0.5rem;
}
}

View File

@@ -0,0 +1,243 @@
import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import type { Recipe } from '../services/api';
import { recipeApi, imageApi } from '../services/api';
import './RecipeList.css';
// Debounce hook
const useDebounce = (value: string, delay: number) => {
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(() => {
const handler = setTimeout(() => {
setDebouncedValue(value);
}, delay);
return () => {
clearTimeout(handler);
};
}, [value, delay]);
return debouncedValue;
};
const RecipeList: React.FC = () => {
const [recipes, setRecipes] = useState<Recipe[]>([]);
const [loading, setLoading] = useState(true);
const [isSearching, setIsSearching] = useState(false);
const [error, setError] = useState<string | null>(null);
const [search, setSearch] = useState('');
const [category, setCategory] = useState('');
const [page, setPage] = useState(1);
const [pagination, setPagination] = useState({
page: 1,
limit: 10,
total: 0,
pages: 0,
});
// Debounce search to prevent too many API calls
const debouncedSearch = useDebounce(search, 300);
const loadRecipes = async () => {
try {
if (recipes.length > 0) {
setIsSearching(true); // Show subtle loading for subsequent searches
}
setError(null); // Clear previous errors
const response = await recipeApi.getRecipes({
search: debouncedSearch || undefined,
category: category || undefined,
page,
limit: 12,
sortBy: 'title',
sortOrder: 'asc',
});
if (response.success) {
setRecipes(response.data);
setPagination(response.pagination);
} else {
setError('Fehler beim Laden der Rezepte');
}
} catch (err) {
setError('Verbindungsfehler - Ist der Server gestartet?');
console.error('Error loading recipes:', err);
} finally {
setLoading(false);
setIsSearching(false);
}
};
useEffect(() => {
loadRecipes();
}, [debouncedSearch, category, page]);
const handleSearchSubmit = (e: React.FormEvent) => {
e.preventDefault();
setPage(1);
loadRecipes();
};
const handleCategoryChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
setCategory(e.target.value);
setPage(1);
};
if (loading) {
return (
<div className="recipe-list">
<div className="loading">Lade Rezepte...</div>
</div>
);
}
if (error) {
return (
<div className="recipe-list">
<div className="error">
<h3>Fehler</h3>
<p>{error}</p>
<button onClick={loadRecipes} className="retry-button">
Erneut versuchen
</button>
</div>
</div>
);
}
return (
<div className="recipe-list">
<div className="recipe-list-header">
<h2>
Alle Rezepte ({pagination.total})
{isSearching && <span className="searching-indicator"> 🔍</span>}
</h2>
<div className="filters">
<form onSubmit={handleSearchSubmit} className="search-form">
<input
type="text"
placeholder="Rezepte durchsuchen..."
value={search}
onChange={(e) => setSearch(e.target.value)}
className="search-input"
/>
<button type="submit" className="search-button">
🔍
</button>
</form>
<select
value={category}
onChange={handleCategoryChange}
className="category-select"
>
<option value="">Alle Kategorien</option>
<option value="Vegan">Vegan</option>
<option value="Vegetarisch">Vegetarisch</option>
<option value="Fleisch">Fleisch</option>
<option value="Fisch">Fisch</option>
<option value="Dessert">Dessert</option>
</select>
</div>
</div>
<div className="recipes-grid">
{recipes.map((recipe) => (
<div key={recipe.id} className="recipe-card">
<div className="recipe-image">
{recipe.images && recipe.images.length > 0 ? (
<img
src={imageApi.getImageUrl(recipe.images[0].filePath)}
alt={recipe.title}
loading="lazy"
style={{
width: '100%',
height: '100%',
objectFit: 'cover',
display: 'block'
}}
onError={(e) => {
const imgSrc = recipe.images?.[0]?.filePath
? imageApi.getImageUrl(recipe.images[0].filePath)
: 'unknown';
console.error('Failed to load image:', imgSrc);
e.currentTarget.style.display = 'none';
e.currentTarget.parentElement!.innerHTML = '<div class="no-image">📸</div>';
}}
/>
) : (
<div className="no-image">📸</div>
)}
</div>
<div className="recipe-content">
<h3 className="recipe-title">{recipe.title}</h3>
<p className="recipe-description">
{recipe.description ?
recipe.description.length > 100 ?
recipe.description.substring(0, 100) + '...' :
recipe.description
: 'Keine Beschreibung verfügbar'
}
</p>
<div className="recipe-meta">
{recipe.category && (
<span className="recipe-category">{recipe.category}</span>
)}
<span className="recipe-servings">👥 {recipe.servings} Portionen</span>
</div>
<div className="recipe-actions">
<Link to={`/recipes/${recipe.id}`} className="view-button">
Ansehen
</Link>
<Link to={`/recipes/${recipe.id}/edit`} className="edit-button">
Bearbeiten
</Link>
</div>
</div>
</div>
))}
</div>
{recipes.length === 0 && (
<div className="no-recipes">
<h3>Keine Rezepte gefunden</h3>
<p>Versuche es mit anderen Suchbegriffen oder erstelle ein neues Rezept.</p>
<Link to="/recipes/new" className="create-button">
Neues Rezept erstellen
</Link>
</div>
)}
{pagination.pages > 1 && (
<div className="pagination">
<button
onClick={() => setPage(page - 1)}
disabled={page <= 1}
className="pagination-button"
>
Vorherige
</button>
<span className="pagination-info">
Seite {page} von {pagination.pages}
</span>
<button
onClick={() => setPage(page + 1)}
disabled={page >= pagination.pages}
className="pagination-button"
>
Nächste
</button>
</div>
)}
</div>
);
};
export default RecipeList;

View File

@@ -0,0 +1,68 @@
:root {
font-family: system-ui, Avenir, Helvetica, Arial, sans-serif;
line-height: 1.5;
font-weight: 400;
color-scheme: light dark;
color: rgba(255, 255, 255, 0.87);
background-color: #242424;
font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
a {
font-weight: 500;
color: #646cff;
text-decoration: inherit;
}
a:hover {
color: #535bf2;
}
body {
margin: 0;
display: flex;
place-items: center;
min-width: 320px;
min-height: 100vh;
}
h1 {
font-size: 3.2em;
line-height: 1.1;
}
button {
border-radius: 8px;
border: 1px solid transparent;
padding: 0.6em 1.2em;
font-size: 1em;
font-weight: 500;
font-family: inherit;
background-color: #1a1a1a;
cursor: pointer;
transition: border-color 0.25s;
}
button:hover {
border-color: #646cff;
}
button:focus,
button:focus-visible {
outline: 4px auto -webkit-focus-ring-color;
}
@media (prefers-color-scheme: light) {
:root {
color: #213547;
background-color: #ffffff;
}
a:hover {
color: #747bff;
}
button {
background-color: #f9f9f9;
}
}

View File

@@ -0,0 +1,10 @@
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App.tsx'
createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
</StrictMode>,
)

View File

@@ -0,0 +1,148 @@
import axios from 'axios';
const API_BASE_URL = 'http://localhost:3001/api';
const api = axios.create({
baseURL: API_BASE_URL,
headers: {
'Content-Type': 'application/json',
},
});
// Recipe interfaces
export interface Recipe {
id: number;
recipeNumber: string;
title: string;
description?: string;
category?: string;
filePath?: string;
preparation?: string;
servings: number;
ingredients?: string;
instructions?: string;
comment?: string;
images?: RecipeImage[];
ingredientsList?: Ingredient[];
}
export interface Ingredient {
id: number;
recipeNumber: string;
ingredients: string;
}
export interface RecipeImage {
id: number;
recipeId: number;
filePath: string;
}
export interface ApiResponse<T> {
success: boolean;
data: T;
message?: string;
}
export interface PaginatedResponse<T> extends ApiResponse<T[]> {
pagination: {
page: number;
limit: number;
total: number;
pages: number;
};
}
// Recipe API methods
export const recipeApi = {
// Get all recipes with pagination and search
getRecipes: async (params?: {
search?: string;
category?: string;
page?: number;
limit?: number;
sortBy?: string;
sortOrder?: 'asc' | 'desc';
}): Promise<PaginatedResponse<Recipe>> => {
const response = await api.get('/recipes', { params });
return response.data;
},
// Get single recipe by ID
getRecipe: async (id: number): Promise<ApiResponse<Recipe>> => {
const response = await api.get(`/recipes/${id}`);
return response.data;
},
// Create new recipe
createRecipe: async (recipe: Omit<Recipe, 'id'>): Promise<ApiResponse<Recipe>> => {
const response = await api.post('/recipes', recipe);
return response.data;
},
// Update recipe
updateRecipe: async (id: number, recipe: Partial<Recipe>): Promise<ApiResponse<Recipe>> => {
const response = await api.put(`/recipes/${id}`, recipe);
return response.data;
},
// Delete recipe
deleteRecipe: async (id: number): Promise<ApiResponse<null>> => {
const response = await api.delete(`/recipes/${id}`);
return response.data;
},
};
// Ingredient API methods
export const ingredientApi = {
getIngredients: async (params?: {
search?: string;
page?: number;
limit?: number;
}): Promise<PaginatedResponse<Ingredient>> => {
const response = await api.get('/ingredients', { params });
return response.data;
},
getIngredient: async (id: number): Promise<ApiResponse<Ingredient>> => {
const response = await api.get(`/ingredients/${id}`);
return response.data;
},
createIngredient: async (ingredient: Omit<Ingredient, 'id'>): Promise<ApiResponse<Ingredient>> => {
const response = await api.post('/ingredients', ingredient);
return response.data;
},
updateIngredient: async (id: number, ingredient: Partial<Ingredient>): Promise<ApiResponse<Ingredient>> => {
const response = await api.put(`/ingredients/${id}`, ingredient);
return response.data;
},
deleteIngredient: async (id: number): Promise<ApiResponse<null>> => {
const response = await api.delete(`/ingredients/${id}`);
return response.data;
},
};
// Image API methods
export const imageApi = {
getRecipeImages: async (recipeId: number): Promise<ApiResponse<RecipeImage[]>> => {
const response = await api.get(`/images/recipe/${recipeId}`);
return response.data;
},
getImageUrl: (imagePath: string): string => {
return `${API_BASE_URL}/images/serve/${imagePath}`;
},
};
// Health check
export const healthApi = {
check: async (): Promise<ApiResponse<{ status: string; timestamp: string }>> => {
const response = await api.get('/health');
return response.data;
},
};
export default api;

View File

@@ -0,0 +1 @@
/// <reference types="vite/client" />

View File

@@ -0,0 +1,27 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "ES2022",
"useDefineForClassFields": true,
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["src"]
}

View File

@@ -0,0 +1,7 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}

View File

@@ -0,0 +1,25 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"target": "ES2023",
"lib": ["ES2023"],
"module": "ESNext",
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["vite.config.ts"]
}

View File

@@ -0,0 +1,7 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
// https://vite.dev/config/
export default defineConfig({
plugins: [react()],
})

BIN
uploads/.DS_Store vendored Normal file

Binary file not shown.