Docker mit traefik und portainer

This commit is contained in:
rxf
2025-09-22 16:35:59 +02:00
parent 6d04ab93c0
commit a255543da6
64 changed files with 5421 additions and 25 deletions

View File

@@ -0,0 +1,89 @@
# Backend Dockerfile
FROM node:18-alpine AS builder
# Install OpenSSL for Prisma compatibility
RUN apk add --no-cache openssl openssl-dev
# Set working directory
WORKDIR /app
# Copy package files
COPY package*.json ./
# Install dependencies
RUN npm ci --only=production
# Copy source code
COPY . .
# Build the application
RUN npm run build
# Production stage
FROM node:18-alpine AS production
# Install required system dependencies for Prisma and health checks
RUN apk add --no-cache \
curl \
openssl \
openssl-dev \
libc6-compat \
&& rm -rf /var/cache/apk/*
# Install curl for healthcheck
RUN apk add --no-cache curl
# Create app user
RUN addgroup -g 1001 -S nodejs
RUN adduser -S backend -u 1001
# Set working directory
WORKDIR /app
# Copy package files
COPY package*.json ./
# Install only production dependencies
RUN npm ci --only=production && npm cache clean --force
# Copy built application from builder stage
COPY --from=builder /app/dist ./dist
# Copy prisma schema for runtime
COPY --from=builder /app/prisma ./prisma
# Create uploads directory
RUN mkdir -p uploads legacy-uploads && chown -R backend:nodejs uploads legacy-uploads
# Create migration script for legacy uploads (via volumes)
COPY <<EOF ./migrate-uploads.sh
#!/bin/sh
# This will be handled via volume mounts in docker-compose
# The legacy upload/ directory will be mounted to /app/legacy-uploads
if [ -d "/app/legacy-uploads" ] && [ "$(ls -A /app/legacy-uploads)" ]; then
echo "Migrating legacy uploads from volume..."
cp -r /app/legacy-uploads/* /app/uploads/ 2>/dev/null || true
chown -R backend:nodejs /app/uploads
echo "Upload migration completed."
else
echo "No legacy uploads found to migrate."
fi
EOF
RUN chmod +x ./migrate-uploads.sh
# Generate Prisma client
RUN npx prisma generate
# Switch to non-root user
USER backend
# Expose port
EXPOSE 3001
# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
CMD curl -f http://localhost:3001/api/health || exit 1
# Start the application
CMD ["sh", "-c", "./migrate-uploads.sh && node dist/app.js"]

View File

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

View File

@@ -27,12 +27,20 @@ const limiter = (0, express_rate_limit_1.default)({
message: 'Too many requests from this IP, please try again later.',
});
app.use(limiter);
const allowedOrigins = [
'http://localhost:5173',
'http://localhost:3000',
config_1.config.cors.origin
].filter(Boolean);
app.use((0, cors_1.default)({
origin: config_1.config.cors.origin,
origin: allowedOrigins,
credentials: true,
}));
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', 'http://localhost:5173');
const origin = req.headers.origin;
if (origin && allowedOrigins.includes(origin)) {
res.header('Access-Control-Allow-Origin', origin);
}
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');

View File

@@ -1 +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,iBAAO,GAAE,CAAC;AAGtB,GAAG,CAAC,GAAG,CAAC,IAAA,gBAAM,EAAC;IACb,yBAAyB,EAAE,EAAE,MAAM,EAAE,cAAc,EAAE;CACtD,CAAC,CAAC,CAAC;AACJ,GAAG,CAAC,GAAG,CAAC,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O,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

@@ -1 +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"}
{"version":3,"file":"images.d.ts","sourceRoot":"","sources":["../../src/routes/images.ts"],"names":[],"mappings":"AAOA,QAAA,MAAM,MAAM,4CAAW,CAAC;AAqQxB,eAAe,MAAM,CAAC"}

View File

@@ -5,10 +5,140 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
Object.defineProperty(exports, "__esModule", { value: true });
const express_1 = require("express");
const client_1 = require("@prisma/client");
const multer_1 = __importDefault(require("multer"));
const path_1 = __importDefault(require("path"));
const fs_1 = __importDefault(require("fs"));
const config_1 = require("../config/config");
const router = (0, express_1.Router)();
const prisma = new client_1.PrismaClient();
const storage = multer_1.default.diskStorage({
destination: (req, file, cb) => {
const recipeNumber = req.body.recipeNumber || req.params.recipeNumber;
if (!recipeNumber) {
return cb(new Error('Recipe number is required'), '');
}
const uploadDir = path_1.default.join(process.cwd(), '../../uploads', recipeNumber);
if (!fs_1.default.existsSync(uploadDir)) {
fs_1.default.mkdirSync(uploadDir, { recursive: true });
}
cb(null, uploadDir);
},
filename: (req, file, cb) => {
const recipeNumber = req.body.recipeNumber || req.params.recipeNumber;
if (!recipeNumber) {
return cb(new Error('Recipe number is required'), '');
}
const uploadDir = path_1.default.join(process.cwd(), '../../uploads', recipeNumber);
const existingFiles = fs_1.default.existsSync(uploadDir)
? fs_1.default.readdirSync(uploadDir).filter(f => f.match(new RegExp(`^${recipeNumber}_\\d+\\.jpg$`)))
: [];
const nextIndex = existingFiles.length;
const filename = `${recipeNumber}_${nextIndex}.jpg`;
cb(null, filename);
}
});
const upload = (0, multer_1.default)({
storage,
limits: {
fileSize: config_1.config.upload.maxFileSize,
},
fileFilter: (req, file, cb) => {
const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/webp'];
if (allowedTypes.includes(file.mimetype)) {
cb(null, true);
}
else {
cb(new Error('Invalid file type. Only JPEG, PNG and WebP are allowed.'));
}
},
});
router.post('/upload/:recipeId', upload.array('images', 10), async (req, res, next) => {
try {
const { recipeId } = req.params;
const files = req.files;
if (!recipeId) {
return res.status(400).json({
success: false,
message: 'Recipe ID is required',
});
}
if (!files || files.length === 0) {
return res.status(400).json({
success: false,
message: 'No files uploaded',
});
}
const recipe = await prisma.recipe.findUnique({
where: { id: parseInt(recipeId) }
});
if (!recipe) {
return res.status(404).json({
success: false,
message: 'Recipe not found',
});
}
const imagePromises = files.map(file => {
const relativePath = `uploads/${recipe.recipeNumber}/${file.filename}`;
return prisma.recipeImage.create({
data: {
recipeId: parseInt(recipeId),
filePath: relativePath,
}
});
});
const images = await Promise.all(imagePromises);
return res.status(201).json({
success: true,
data: images,
message: `${files.length} images uploaded successfully`,
});
}
catch (error) {
if (req.files) {
const files = req.files;
files.forEach(file => {
if (fs_1.default.existsSync(file.path)) {
fs_1.default.unlinkSync(file.path);
}
});
}
next(error);
}
});
router.delete('/: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',
});
}
const fullPath = path_1.default.join(process.cwd(), '../..', image.filePath);
if (fs_1.default.existsSync(fullPath)) {
fs_1.default.unlinkSync(fullPath);
}
await prisma.recipeImage.delete({
where: { id: parseInt(id) }
});
return res.json({
success: true,
message: 'Image deleted successfully',
});
}
catch (error) {
next(error);
}
});
router.get('/recipe/:recipeId', async (req, res, next) => {
try {
const { recipeId } = req.params;

File diff suppressed because one or more lines are too long

View File

@@ -1 +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"}
{"version":3,"file":"recipes.d.ts","sourceRoot":"","sources":["../../src/routes/recipes.ts"],"names":[],"mappings":"AAIA,QAAA,MAAM,MAAM,4CAAW,CAAC;AAoQxB,eAAe,MAAM,CAAC"}

View File

@@ -74,8 +74,15 @@ router.get('/:id', async (req, res, next) => {
message: 'Recipe ID is required',
});
}
const recipeId = parseInt(id);
if (isNaN(recipeId)) {
return res.status(400).json({
success: false,
message: 'Invalid recipe ID format',
});
}
const recipe = await prisma.recipe.findUnique({
where: { id: parseInt(id) },
where: { id: recipeId },
include: {
images: true,
ingredientsList: true,

File diff suppressed because one or more lines are too long

View File

@@ -28,7 +28,7 @@
"@types/express": "^4.17.21",
"@types/jest": "^29.5.8",
"@types/jsonwebtoken": "^9.0.5",
"@types/multer": "^1.4.11",
"@types/multer": "^1.4.13",
"@types/node": "^20.8.10",
"@typescript-eslint/eslint-plugin": "^6.9.1",
"@typescript-eslint/parser": "^6.9.1",

View File

@@ -34,7 +34,7 @@
"@types/express": "^4.17.21",
"@types/jest": "^29.5.8",
"@types/jsonwebtoken": "^9.0.5",
"@types/multer": "^1.4.11",
"@types/multer": "^1.4.13",
"@types/node": "^20.8.10",
"@typescript-eslint/eslint-plugin": "^6.9.1",
"@typescript-eslint/parser": "^6.9.1",

View File

@@ -30,15 +30,36 @@ const limiter = rateLimit({
});
app.use(limiter);
// CORS configuration
app.use(cors({
origin: config.cors.origin,
credentials: true,
}));
// CORS configuration - Allow both development and production origins
const allowedOrigins = [
'http://localhost:5173', // Vite dev server
'http://localhost:3000', // Docker frontend
config.cors.origin // Environment configured origin
].filter(Boolean);
// Add local network origins if CORS_ORIGIN is "*" (for local network access)
const corsConfig = config.cors.origin === '*'
? {
origin: true, // Allow all origins for local network
credentials: true,
}
: {
origin: allowedOrigins,
credentials: true,
};
app.use(cors(corsConfig));
// Additional CORS headers for all requests
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', 'http://localhost:5173');
const origin = req.headers.origin;
if (config.cors.origin === '*') {
// Allow all origins for local network access
res.header('Access-Control-Allow-Origin', origin || '*');
} else if (origin && allowedOrigins.includes(origin)) {
res.header('Access-Control-Allow-Origin', origin);
}
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');
@@ -56,6 +77,9 @@ app.use(express.urlencoded({ extended: true, limit: '10mb' }));
// Request logging
app.use(requestLogger);
// Static file serving for uploads
app.use('/uploads', express.static(path.join(process.cwd(), 'uploads')));
// API routes
app.use('/api/health', healthRoutes);
app.use('/api/recipes', recipeRoutes);

View File

@@ -1,11 +1,180 @@
import { Router, Request, Response, NextFunction } from 'express';
import { PrismaClient } from '@prisma/client';
import multer from 'multer';
import path from 'path';
import fs from 'fs';
import { config } from '../config/config';
const router = Router();
const prisma = new PrismaClient();
// Utility function to get correct uploads directory path
const getUploadsDir = (subPath?: string): string => {
const baseDir = process.env.NODE_ENV === 'production'
? path.join(process.cwd(), 'uploads')
: path.join(process.cwd(), '../../uploads');
return subPath ? path.join(baseDir, subPath) : baseDir;
};
// Configure multer for file uploads
const storage = multer.diskStorage({
destination: (req, file, cb) => {
const recipeNumber = req.body.recipeNumber || req.params.recipeNumber;
if (!recipeNumber) {
return cb(new Error('Recipe number is required'), '');
}
const uploadDir = getUploadsDir(recipeNumber);
// Create directory if it doesn't exist
if (!fs.existsSync(uploadDir)) {
fs.mkdirSync(uploadDir, { recursive: true });
}
cb(null, uploadDir);
},
filename: (req, file, cb) => {
const recipeNumber = req.body.recipeNumber || req.params.recipeNumber;
if (!recipeNumber) {
return cb(new Error('Recipe number is required'), '');
}
// Get existing files count to determine next index
const uploadDir = getUploadsDir(recipeNumber);
const existingFiles = fs.existsSync(uploadDir)
? fs.readdirSync(uploadDir).filter(f => f.match(new RegExp(`^${recipeNumber}_\\d+\\.jpg$`)))
: [];
const nextIndex = existingFiles.length;
const filename = `${recipeNumber}_${nextIndex}.jpg`;
cb(null, filename);
}
});
const upload = multer({
storage,
limits: {
fileSize: config.upload.maxFileSize, // 5MB
},
fileFilter: (req, file, cb) => {
const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/webp'];
if (allowedTypes.includes(file.mimetype)) {
cb(null, true);
} else {
cb(new Error('Invalid file type. Only JPEG, PNG and WebP are allowed.'));
}
},
});
// Upload images for a recipe
router.post('/upload/:recipeId', upload.array('images', 10), async (req: Request, res: Response, next: NextFunction) => {
try {
const { recipeId } = req.params;
const files = req.files as Express.Multer.File[];
if (!recipeId) {
return res.status(400).json({
success: false,
message: 'Recipe ID is required',
});
}
if (!files || files.length === 0) {
return res.status(400).json({
success: false,
message: 'No files uploaded',
});
}
// Get recipe to validate it exists and get recipe number
const recipe = await prisma.recipe.findUnique({
where: { id: parseInt(recipeId) }
});
if (!recipe) {
return res.status(404).json({
success: false,
message: 'Recipe not found',
});
}
// Create database entries for uploaded images
const imagePromises = files.map(file => {
const relativePath = `uploads/${recipe.recipeNumber}/${file.filename}`;
return prisma.recipeImage.create({
data: {
recipeId: parseInt(recipeId),
filePath: relativePath,
}
});
});
const images = await Promise.all(imagePromises);
return res.status(201).json({
success: true,
data: images,
message: `${files.length} images uploaded successfully`,
});
} catch (error) {
// Clean up uploaded files if database operation fails
if (req.files) {
const files = req.files as Express.Multer.File[];
files.forEach(file => {
if (fs.existsSync(file.path)) {
fs.unlinkSync(file.path);
}
});
}
next(error);
}
});
// Delete an image
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: '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',
});
}
// Delete file from filesystem
const fullPath = path.join(process.cwd(), '../..', image.filePath);
if (fs.existsSync(fullPath)) {
fs.unlinkSync(fullPath);
}
// Delete from database
await prisma.recipeImage.delete({
where: { id: parseInt(id) }
});
return res.json({
success: true,
message: 'Image deleted successfully',
});
} catch (error) {
next(error);
}
});
// Get all images for a recipe by recipe ID
router.get('/recipe/:recipeId', async (req: Request, res: Response, next: NextFunction) => {
try {
@@ -46,7 +215,7 @@ router.get('/serve/:imagePath(*)', (req: Request, res: Response, next: NextFunct
// Remove leading 'uploads/' if present to avoid duplication
const cleanPath = imagePath.replace(/^uploads\//, '');
const fullPath = path.join(process.cwd(), '../../uploads', cleanPath);
const fullPath = path.join(getUploadsDir(), cleanPath);
console.log(`Serving image: ${imagePath} -> ${fullPath}`);
@@ -60,9 +229,17 @@ router.get('/serve/:imagePath(*)', (req: Request, res: Response, next: NextFunct
});
}
// Set CORS headers for images
// Set CORS headers for images - support multiple origins including local network
const allowedOrigins = ['http://localhost:5173', 'http://localhost:3000'];
const origin = req.headers.origin;
// Check if CORS_ORIGIN is set to "*" for local network access
const corsOrigin = process.env.CORS_ORIGIN === '*'
? (origin || '*')
: (origin && allowedOrigins.includes(origin)) ? origin : 'http://localhost:3000';
res.set({
'Access-Control-Allow-Origin': 'http://localhost:5173',
'Access-Control-Allow-Origin': corsOrigin,
'Access-Control-Allow-Credentials': 'true',
'Cache-Control': 'public, max-age=31536000', // Cache for 1 year
});

View File

@@ -91,9 +91,17 @@ router.get('/:id', async (req: Request, res: Response, next: NextFunction) => {
message: 'Recipe ID is required',
});
}
const recipeId = parseInt(id);
if (isNaN(recipeId)) {
return res.status(400).json({
success: false,
message: 'Invalid recipe ID format',
});
}
const recipe = await prisma.recipe.findUnique({
where: { id: parseInt(id) },
where: { id: recipeId },
include: {
images: true,
ingredientsList: true,

View File

@@ -0,0 +1,138 @@
# Frontend Dockerfile
FROM node:18-alpine AS builder
# Set working directory
WORKDIR /app
# Copy package files
COPY package*.json ./
# Install dependencies
RUN npm ci
# Copy source code
COPY . .
# Build arguments for environment variables
# For local network: VITE_API_URL will be set dynamically by the container hostname
ARG VITE_API_URL
ENV VITE_API_URL=$VITE_API_URL
# Build the application
RUN npm run build
# Production stage with Nginx
FROM nginx:alpine AS production
# Install curl for healthcheck
RUN apk add --no-cache curl
# Copy custom nginx configuration
COPY <<EOF /etc/nginx/nginx.conf
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main '\$remote_addr - \$remote_user [\$time_local] "\$request" '
'\$status \$body_bytes_sent "\$http_referer" '
'"\$http_user_agent" "\$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
# Gzip compression
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_types
text/plain
text/css
text/xml
text/javascript
application/javascript
application/xml+rss
application/json;
# Security headers
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "no-referrer-when-downgrade" always;
add_header Content-Security-Policy "default-src 'self' http: https: data: blob: 'unsafe-inline'" always;
server {
listen 80;
server_name localhost;
root /usr/share/nginx/html;
index index.html;
# Handle client-side routing
location / {
try_files \$uri \$uri/ /index.html;
}
# Cache static assets
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
expires 1y;
add_header Cache-Control "public, immutable";
}
# Security headers for HTML files
location ~* \.html$ {
expires epoch;
add_header Cache-Control "no-cache, no-store, must-revalidate";
}
# Health check endpoint
location /health {
access_log off;
return 200 "healthy\n";
add_header Content-Type text/plain;
}
}
}
EOF
# Copy built application from builder stage
COPY --from=builder /app/dist /usr/share/nginx/html
# Create non-root user
RUN addgroup -g 1001 -S nginx_user && \
adduser -S nginx_user -u 1001 -G nginx_user
# Set proper permissions
RUN chown -R nginx_user:nginx_user /usr/share/nginx/html && \
chown -R nginx_user:nginx_user /var/cache/nginx && \
chown -R nginx_user:nginx_user /var/log/nginx && \
chown -R nginx_user:nginx_user /etc/nginx/conf.d
# Create nginx runtime directories
RUN touch /var/run/nginx.pid && \
chown -R nginx_user:nginx_user /var/run/nginx.pid
# Switch to non-root user
USER nginx_user
# Expose port
EXPOSE 80
# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
CMD curl -f http://localhost:80/health || exit 1
# Start nginx
CMD ["nginx", "-g", "daemon off;"]

View File

@@ -0,0 +1,296 @@
/* FileUpload Component Styles */
.file-upload {
width: 100%;
margin: 20px 0;
}
/* Drop Zone */
.drop-zone {
border: 2px dashed #007bff;
border-radius: 12px;
padding: 40px 20px;
text-align: center;
cursor: pointer;
transition: all 0.3s ease;
background: #f8f9fa;
position: relative;
min-height: 150px;
display: flex;
align-items: center;
justify-content: center;
}
.drop-zone:hover {
border-color: #0056b3;
background: #e3f2fd;
transform: translateY(-2px);
}
.drop-zone.drag-over {
border-color: #28a745;
background: #d4edda;
border-style: solid;
}
.drop-zone.disabled {
opacity: 0.6;
cursor: not-allowed;
background: #e9ecef;
border-color: #ced4da;
}
.drop-zone.disabled:hover {
transform: none;
border-color: #ced4da;
background: #e9ecef;
}
.drop-zone-content {
pointer-events: none;
}
.upload-icon {
font-size: 3em;
margin-bottom: 15px;
opacity: 0.7;
}
.upload-text {
font-size: 1.1em;
font-weight: 600;
color: #333;
margin: 0 0 8px 0;
}
.upload-hint {
font-size: 0.9em;
color: #666;
margin: 0;
}
/* Error Messages */
.upload-errors {
margin-top: 15px;
}
.error-message {
background: #f8d7da;
color: #721c24;
border: 1px solid #f5c6cb;
border-radius: 6px;
padding: 8px 12px;
margin-bottom: 8px;
font-size: 0.9em;
}
/* File Previews */
.file-previews {
margin-top: 20px;
border-top: 1px solid #e0e0e0;
padding-top: 20px;
}
.preview-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 15px;
}
.preview-header h4 {
margin: 0;
color: #333;
font-size: 1.1em;
}
.clear-all-btn {
background: #dc3545;
color: white;
border: none;
padding: 6px 12px;
border-radius: 6px;
font-size: 0.9em;
cursor: pointer;
transition: all 0.3s ease;
}
.clear-all-btn:hover:not(:disabled) {
background: #c82333;
transform: translateY(-1px);
}
.clear-all-btn:disabled {
opacity: 0.6;
cursor: not-allowed;
transform: none;
}
/* Preview Grid */
.preview-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
gap: 15px;
}
.file-preview {
background: white;
border: 1px solid #e0e0e0;
border-radius: 8px;
overflow: hidden;
transition: all 0.3s ease;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
.file-preview:hover {
transform: translateY(-2px);
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}
.preview-image {
position: relative;
width: 100%;
height: 150px;
background: #f8f9fa;
display: flex;
align-items: center;
justify-content: center;
overflow: hidden;
}
.preview-image img {
width: 100%;
height: 100%;
object-fit: cover;
transition: transform 0.3s ease;
}
.preview-image:hover img {
transform: scale(1.05);
}
.remove-file-btn {
position: absolute;
top: 8px;
right: 8px;
background: rgba(220, 53, 69, 0.9);
color: white;
border: none;
width: 24px;
height: 24px;
border-radius: 50%;
font-size: 12px;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
transition: all 0.3s ease;
opacity: 0;
}
.file-preview:hover .remove-file-btn {
opacity: 1;
}
.remove-file-btn:hover:not(:disabled) {
background: rgba(200, 35, 51, 0.9);
transform: scale(1.1);
}
.remove-file-btn:disabled {
opacity: 0.4;
cursor: not-allowed;
transform: none;
}
.file-info {
padding: 12px;
text-align: left;
}
.file-name {
font-weight: 600;
color: #333;
font-size: 0.9em;
margin-bottom: 4px;
word-break: break-word;
}
.file-size {
color: #666;
font-size: 0.8em;
}
/* Progress Bar (for future use) */
.upload-progress {
margin-top: 15px;
background: #e9ecef;
border-radius: 10px;
overflow: hidden;
height: 8px;
}
.upload-progress-bar {
height: 100%;
background: linear-gradient(90deg, #007bff, #0056b3);
transition: width 0.3s ease;
border-radius: 10px;
}
/* Responsive Design */
@media (max-width: 768px) {
.drop-zone {
padding: 30px 15px;
min-height: 120px;
}
.upload-icon {
font-size: 2.5em;
margin-bottom: 10px;
}
.upload-text {
font-size: 1em;
}
.upload-hint {
font-size: 0.8em;
}
.preview-grid {
grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
gap: 10px;
}
.preview-image {
height: 120px;
}
.preview-header {
flex-direction: column;
gap: 10px;
align-items: stretch;
}
.clear-all-btn {
align-self: center;
width: fit-content;
}
}
@media (max-width: 480px) {
.preview-grid {
grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
}
.file-info {
padding: 8px;
}
.file-name {
font-size: 0.8em;
}
.file-size {
font-size: 0.75em;
}
}

View File

@@ -0,0 +1,233 @@
import React, { useState, useRef } from 'react';
import type { DragEvent, ChangeEvent } from 'react';
import './FileUpload.css';
interface FileUploadProps {
onFilesSelected: (files: File[]) => void;
accept?: string;
multiple?: boolean;
maxFiles?: number;
maxFileSize?: number; // in MB
disabled?: boolean;
className?: string;
}
interface FileWithPreview extends File {
preview?: string;
}
const FileUpload: React.FC<FileUploadProps> = ({
onFilesSelected,
accept = 'image/*',
multiple = true,
maxFiles = 10,
maxFileSize = 5, // 5MB default
disabled = false,
className = '',
}) => {
const [selectedFiles, setSelectedFiles] = useState<FileWithPreview[]>([]);
const [dragOver, setDragOver] = useState(false);
const [errors, setErrors] = useState<string[]>([]);
const fileInputRef = useRef<HTMLInputElement>(null);
const validateFile = (file: File): string | null => {
// Check file size
if (file.size > maxFileSize * 1024 * 1024) {
return `Datei "${file.name}" ist zu groß. Maximum: ${maxFileSize}MB`;
}
// Check file type
if (!file.type.startsWith('image/')) {
return `Datei "${file.name}" ist kein gültiges Bild`;
}
return null;
};
const processFiles = (files: FileList | File[]) => {
const fileArray = Array.from(files);
const newErrors: string[] = [];
const validFiles: FileWithPreview[] = [];
// Check total file count
if (selectedFiles.length + fileArray.length > maxFiles) {
newErrors.push(`Maximal ${maxFiles} Dateien erlaubt`);
setErrors(newErrors);
return;
}
fileArray.forEach((file) => {
const error = validateFile(file);
if (error) {
newErrors.push(error);
} else {
// Create preview URL
const fileWithPreview = file as FileWithPreview;
fileWithPreview.preview = URL.createObjectURL(file);
validFiles.push(fileWithPreview);
}
});
if (newErrors.length > 0) {
setErrors(newErrors);
} else {
setErrors([]);
const updatedFiles = [...selectedFiles, ...validFiles];
setSelectedFiles(updatedFiles);
onFilesSelected(updatedFiles);
}
};
const handleFileSelect = (e: ChangeEvent<HTMLInputElement>) => {
if (e.target.files && e.target.files.length > 0) {
processFiles(e.target.files);
}
};
const handleDrop = (e: DragEvent<HTMLDivElement>) => {
e.preventDefault();
setDragOver(false);
if (disabled) return;
const files = e.dataTransfer.files;
if (files.length > 0) {
processFiles(files);
}
};
const handleDragOver = (e: DragEvent<HTMLDivElement>) => {
e.preventDefault();
if (!disabled) {
setDragOver(true);
}
};
const handleDragLeave = (e: DragEvent<HTMLDivElement>) => {
e.preventDefault();
setDragOver(false);
};
const removeFile = (index: number) => {
const fileToRemove = selectedFiles[index];
if (fileToRemove.preview) {
URL.revokeObjectURL(fileToRemove.preview);
}
const updatedFiles = selectedFiles.filter((_, i) => i !== index);
setSelectedFiles(updatedFiles);
onFilesSelected(updatedFiles);
};
const clearAll = () => {
selectedFiles.forEach(file => {
if (file.preview) {
URL.revokeObjectURL(file.preview);
}
});
setSelectedFiles([]);
setErrors([]);
onFilesSelected([]);
};
return (
<div className={`file-upload ${className}`}>
{/* Drop Zone */}
<div
className={`drop-zone ${dragOver ? 'drag-over' : ''} ${disabled ? 'disabled' : ''}`}
onDrop={handleDrop}
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
onClick={() => !disabled && fileInputRef.current?.click()}
>
<div className="drop-zone-content">
<div className="upload-icon">📁</div>
<p className="upload-text">
{selectedFiles.length > 0
? `${selectedFiles.length} Datei${selectedFiles.length > 1 ? 'en' : ''} ausgewählt`
: 'Bilder hier ablegen oder klicken zum Auswählen'
}
</p>
<p className="upload-hint">
Maximal {maxFiles} Dateien, je max. {maxFileSize}MB
</p>
</div>
<input
ref={fileInputRef}
type="file"
accept={accept}
multiple={multiple}
onChange={handleFileSelect}
disabled={disabled}
style={{ display: 'none' }}
/>
</div>
{/* Error Messages */}
{errors.length > 0 && (
<div className="upload-errors">
{errors.map((error, index) => (
<div key={index} className="error-message">
{error}
</div>
))}
</div>
)}
{/* File Previews */}
{selectedFiles.length > 0 && (
<div className="file-previews">
<div className="preview-header">
<h4>Ausgewählte Bilder ({selectedFiles.length})</h4>
<button
type="button"
onClick={clearAll}
className="clear-all-btn"
disabled={disabled}
>
Alle entfernen
</button>
</div>
<div className="preview-grid">
{selectedFiles.map((file, index) => (
<div key={index} className="file-preview">
<div className="preview-image">
<img
src={file.preview}
alt={file.name}
onLoad={() => {
// Clean up object URL after image loads
if (file.preview) {
URL.revokeObjectURL(file.preview);
}
}}
/>
<button
type="button"
className="remove-file-btn"
onClick={() => removeFile(index)}
disabled={disabled}
>
</button>
</div>
<div className="file-info">
<div className="file-name" title={file.name}>
{file.name.length > 20 ? `${file.name.substring(0, 17)}...` : file.name}
</div>
<div className="file-size">
{(file.size / 1024 / 1024).toFixed(2)} MB
</div>
</div>
</div>
))}
</div>
</div>
)}
</div>
);
};
export default FileUpload;

View File

@@ -1,13 +1,16 @@
import React, { useState } from 'react';
import { useNavigate, Link } from 'react-router-dom';
import { recipeApi } from '../services/api';
import { recipeApi, imageApi } from '../services/api';
import FileUpload from './FileUpload';
import './RecipeEdit.css'; // Reuse the same styles
const RecipeCreate: React.FC = () => {
const navigate = useNavigate();
const [loading, setLoading] = useState(false);
const [uploadProgress, setUploadProgress] = useState(0);
const [error, setError] = useState<string | null>(null);
const [success, setSuccess] = useState(false);
const [selectedFiles, setSelectedFiles] = useState<File[]>([]);
// Form state
const [formData, setFormData] = useState({
@@ -41,13 +44,26 @@ const RecipeCreate: React.FC = () => {
throw new Error('Titel ist erforderlich');
}
// First create the recipe
const response = await recipeApi.createRecipe(formData);
if (response.success) {
const recipeId = response.data.id;
// Upload images if any were selected
if (selectedFiles.length > 0) {
try {
await imageApi.uploadImages(recipeId, selectedFiles, setUploadProgress);
} catch (uploadError) {
console.warn('Image upload failed:', uploadError);
// Don't fail the entire process if image upload fails
}
}
setSuccess(true);
// Redirect to the new recipe detail page after a short delay
setTimeout(() => {
navigate(`/recipes/${response.data.id}`);
navigate(`/recipes/${recipeId}`);
}, 1500);
} else {
setError('Fehler beim Erstellen des Rezepts');
@@ -60,6 +76,10 @@ const RecipeCreate: React.FC = () => {
}
};
const handleFilesSelected = (files: File[]) => {
setSelectedFiles(files);
};
if (success) {
return (
<div className="recipe-edit">
@@ -233,6 +253,27 @@ const RecipeCreate: React.FC = () => {
/>
</div>
{/* Image Upload Section */}
<div className="form-group">
<label>Bilder hochladen</label>
<p className="form-hint">
Laden Sie Bilder für Ihr Rezept hoch. Das erste Bild wird als Hauptbild verwendet,
weitere Bilder werden den Zubereitungsschritten zugeordnet.
</p>
<FileUpload
onFilesSelected={handleFilesSelected}
maxFiles={10}
maxFileSize={5}
disabled={loading}
/>
{uploadProgress > 0 && uploadProgress < 100 && (
<div className="upload-progress">
<div className="upload-progress-bar" style={{ width: `${uploadProgress}%` }}></div>
<span className="upload-progress-text">{uploadProgress}% hochgeladen</span>
</div>
)}
</div>
{/* Form Actions */}
<div className="form-actions">
<button

View File

@@ -410,6 +410,156 @@
color: #333;
}
/* Image Management */
.image-management {
background: #f8f9fa;
border-radius: 12px;
padding: 25px;
margin: 30px 0;
border: 1px solid #e0e0e0;
}
.image-management h3 {
margin: 0 0 20px 0;
color: #333;
font-size: 1.3em;
display: flex;
align-items: center;
gap: 8px;
}
.image-management h3::before {
content: "📸";
font-size: 1.2em;
}
.upload-section {
margin-bottom: 30px;
padding-bottom: 25px;
border-bottom: 1px solid #e0e0e0;
}
.upload-section h4,
.existing-images h4 {
margin: 0 0 15px 0;
color: #555;
font-size: 1.1em;
}
.existing-images {
margin-top: 20px;
}
.images-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
gap: 20px;
margin-top: 15px;
}
.image-item {
background: white;
border-radius: 8px;
overflow: hidden;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
transition: all 0.3s ease;
}
.image-item:hover {
transform: translateY(-2px);
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}
.image-preview {
position: relative;
width: 100%;
height: 150px;
overflow: hidden;
}
.image-preview img {
width: 100%;
height: 100%;
object-fit: cover;
transition: transform 0.3s ease;
}
.image-preview:hover img {
transform: scale(1.05);
}
.delete-image-btn {
position: absolute;
top: 8px;
right: 8px;
background: rgba(220, 53, 69, 0.9);
color: white;
border: none;
width: 32px;
height: 32px;
border-radius: 50%;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
font-size: 14px;
transition: all 0.3s ease;
opacity: 0;
}
.image-item:hover .delete-image-btn {
opacity: 1;
}
.delete-image-btn:hover {
background: rgba(200, 35, 51, 0.9);
transform: scale(1.1);
}
.image-info {
padding: 12px;
text-align: center;
}
.image-name {
display: block;
font-size: 0.9em;
color: #666;
margin-bottom: 5px;
word-break: break-word;
}
.main-image-badge {
background: #007bff;
color: white;
padding: 2px 8px;
border-radius: 12px;
font-size: 0.8em;
font-weight: 500;
}
.upload-progress {
margin-top: 15px;
background: #e9ecef;
border-radius: 10px;
overflow: hidden;
height: 8px;
}
.upload-progress-bar {
height: 100%;
background: linear-gradient(90deg, #007bff, #0056b3);
transition: width 0.3s ease;
}
.upload-progress-text {
font-size: 0.9em;
color: #666;
margin-top: 8px;
text-align: center;
display: block;
}
/* Error States */
.error, .not-found {
text-align: center;

View File

@@ -2,6 +2,7 @@ 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 FileUpload from './FileUpload';
import './RecipeDetail.css';
// Helper function to convert URLs in text to clickable links
@@ -33,6 +34,8 @@ const RecipeDetail: React.FC = () => {
const [recipe, setRecipe] = useState<Recipe | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [editingImages, setEditingImages] = useState(false);
const [uploadProgress, setUploadProgress] = useState(0);
useEffect(() => {
const loadRecipe = async () => {
@@ -62,6 +65,43 @@ const RecipeDetail: React.FC = () => {
loadRecipe();
}, [id]);
const handleImageUpload = async (files: File[]) => {
if (!recipe || !id) return;
try {
setUploadProgress(0);
await imageApi.uploadImages(parseInt(id), files, setUploadProgress);
// Reload recipe to get updated images
const response = await recipeApi.getRecipe(parseInt(id));
if (response.success) {
setRecipe(response.data);
}
setUploadProgress(0);
} catch (error) {
console.error('Error uploading images:', error);
setError('Fehler beim Hochladen der Bilder');
}
};
const handleImageDelete = async (imageId: number) => {
if (!recipe || !id) return;
try {
await imageApi.deleteImage(imageId);
// Reload recipe to get updated images
const response = await recipeApi.getRecipe(parseInt(id));
if (response.success) {
setRecipe(response.data);
}
} catch (error) {
console.error('Error deleting image:', error);
setError('Fehler beim Löschen des Bildes');
}
};
if (loading) {
return (
<div className="recipe-detail">
@@ -114,6 +154,13 @@ const RecipeDetail: React.FC = () => {
</div>
<div className="recipe-actions">
<button
onClick={() => setEditingImages(!editingImages)}
className="edit-button"
style={{ marginRight: '8px' }}
>
📸 {editingImages ? 'Fertig' : 'Bilder verwalten'}
</button>
<Link to={`/recipes/${recipe.id}/edit`} className="edit-button">
Bearbeiten
</Link>
@@ -174,6 +221,64 @@ const RecipeDetail: React.FC = () => {
</div>
</div>
{/* Image Management Section */}
{editingImages && (
<div className="image-management">
<h3>Bilder verwalten</h3>
{/* Upload new images */}
<div className="upload-section">
<h4>Neue Bilder hochladen</h4>
<FileUpload
onFilesSelected={handleImageUpload}
maxFiles={5}
maxFileSize={5}
disabled={uploadProgress > 0}
/>
{uploadProgress > 0 && uploadProgress < 100 && (
<div className="upload-progress">
<div className="upload-progress-bar" style={{ width: `${uploadProgress}%` }}></div>
<span className="upload-progress-text">{uploadProgress}% hochgeladen</span>
</div>
)}
</div>
{/* Existing images */}
{recipe.images && recipe.images.length > 0 && (
<div className="existing-images">
<h4>Vorhandene Bilder ({recipe.images.length})</h4>
<div className="images-grid">
{recipe.images.map((image, index) => (
<div key={image.id} className="image-item">
<div className="image-preview">
<img
src={imageApi.getImageUrl(image.filePath)}
alt={`Bild ${index + 1}`}
/>
<button
className="delete-image-btn"
onClick={() => handleImageDelete(image.id)}
title="Bild löschen"
>
🗑
</button>
</div>
<div className="image-info">
<span className="image-name">
{image.filePath.split('/').pop()}
</span>
{image.filePath.includes('_0.jpg') && (
<span className="main-image-badge">Hauptbild</span>
)}
</div>
</div>
))}
</div>
</div>
)}
</div>
)}
{/* Two Column Layout for Description/Ingredients and Preparation */}
<div className="recipe-columns">
{/* Left Column - Description and Ingredients */}

View File

@@ -371,6 +371,37 @@
}
}
/* Upload Progress in Forms */
.form-group .upload-progress {
margin-top: 10px;
background: #e9ecef;
border-radius: 10px;
overflow: hidden;
height: 6px;
position: relative;
}
.form-group .upload-progress-bar {
height: 100%;
background: linear-gradient(90deg, #007bff, #0056b3);
transition: width 0.3s ease;
border-radius: 10px;
}
.upload-progress-text {
font-size: 0.9em;
color: #666;
margin-top: 5px;
display: block;
}
.form-hint {
color: #666;
font-size: 0.9em;
margin-bottom: 10px;
line-height: 1.4;
}
/* High Contrast Mode */
@media (prefers-contrast: high) {
.form-group input,

View File

@@ -1,6 +1,21 @@
import axios from 'axios';
const API_BASE_URL = 'http://localhost:3001/api';
// Runtime API URL detection - works in the browser
const getApiBaseUrl = (): string => {
const hostname = window.location.hostname;
if (hostname === 'localhost' || hostname === '127.0.0.1') {
// Local development
return 'http://localhost:3001/api';
} else {
// Network access - use same host as frontend
return `http://${hostname}:3001/api`;
}
};
const API_BASE_URL = getApiBaseUrl();
console.log('🔗 API Base URL:', API_BASE_URL); // Debug log
const api = axios.create({
baseURL: API_BASE_URL,
@@ -135,6 +150,33 @@ export const imageApi = {
getImageUrl: (imagePath: string): string => {
return `${API_BASE_URL}/images/serve/${imagePath}`;
},
// Upload images for a recipe
uploadImages: async (recipeId: number, files: File[], onProgress?: (progress: number) => void): Promise<ApiResponse<RecipeImage[]>> => {
const formData = new FormData();
files.forEach((file) => {
formData.append('images', file);
});
const response = await api.post(`/images/upload/${recipeId}`, formData, {
headers: {
'Content-Type': 'multipart/form-data',
},
onUploadProgress: (progressEvent) => {
if (onProgress && progressEvent.total) {
const progress = Math.round((progressEvent.loaded * 100) / progressEvent.total);
onProgress(progress);
}
},
});
return response.data;
},
// Delete an image
deleteImage: async (imageId: number): Promise<ApiResponse<null>> => {
const response = await api.delete(`/images/${imageId}`);
return response.data;
},
};
// Health check