Files
Filamenteka/api/server.js
DaX 12e91d4c3e Remove refresh icon and fix Safari/WebKit runtime errors
- Removed manual refresh button from frontend (kept auto-refresh functionality)
- Fixed WebKit 'object cannot be found' error by replacing absolute positioning with flexbox
- Added lazy loading to images to prevent preload warnings
- Cleaned up unused imports and variables:
  - Removed unused useRef import
  - Removed unused colors state variable and colorService
  - Removed unused ColorSwatch import from FilamentTableV2
  - Removed unused getModifierIcon function from MaterialBadge
- Updated tests to match current implementation
- Improved layout stability for better cross-browser compatibility
- Removed temporary migration scripts

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-06-30 22:37:30 +02:00

193 lines
6.0 KiB
JavaScript

const express = require('express');
const { Pool } = require('pg');
const cors = require('cors');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
require('dotenv').config();
const app = express();
const PORT = process.env.PORT || 80;
// PostgreSQL connection
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
ssl: process.env.DATABASE_URL?.includes('amazonaws.com') ? { rejectUnauthorized: false } : false
});
// Middleware
app.use(cors({
origin: true, // Allow all origins in development
credentials: true,
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization'],
exposedHeaders: ['Content-Length', 'Content-Type'],
maxAge: 86400
}));
app.use(express.json());
// Handle preflight requests
app.options('*', cors());
// Health check route
app.get('/', (req, res) => {
res.json({ status: 'ok', service: 'Filamenteka API' });
});
// JWT middleware
const authenticateToken = (req, res, next) => {
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1];
if (!token) {
return res.status(401).json({ error: 'Unauthorized' });
}
jwt.verify(token, process.env.JWT_SECRET || 'your-secret-key', (err, user) => {
if (err) {
console.error('JWT verification error:', err);
return res.status(403).json({ error: 'Invalid token' });
}
req.user = user;
next();
});
};
// Auth endpoints
app.post('/api/login', async (req, res) => {
const { username, password } = req.body;
// For now, simple hardcoded admin check
if (username === 'admin' && password === process.env.ADMIN_PASSWORD) {
const token = jwt.sign({ username }, process.env.JWT_SECRET || 'your-secret-key', { expiresIn: '24h' });
res.json({ token });
} else {
res.status(401).json({ error: 'Invalid credentials' });
}
});
// Colors endpoints
app.get('/api/colors', async (req, res) => {
try {
const result = await pool.query('SELECT * FROM colors ORDER BY name');
res.json(result.rows);
} catch (error) {
console.error('Error fetching colors:', error);
res.status(500).json({ error: 'Failed to fetch colors' });
}
});
app.post('/api/colors', authenticateToken, async (req, res) => {
const { name, hex, cena_refill, cena_spulna } = req.body;
try {
const result = await pool.query(
'INSERT INTO colors (name, hex, cena_refill, cena_spulna) VALUES ($1, $2, $3, $4) RETURNING *',
[name, hex, cena_refill || 3499, cena_spulna || 3999]
);
res.json(result.rows[0]);
} catch (error) {
console.error('Error creating color:', error);
res.status(500).json({ error: 'Failed to create color' });
}
});
app.put('/api/colors/:id', authenticateToken, async (req, res) => {
const { id } = req.params;
const { name, hex, cena_refill, cena_spulna } = req.body;
try {
const result = await pool.query(
'UPDATE colors SET name = $1, hex = $2, cena_refill = $3, cena_spulna = $4, updated_at = CURRENT_TIMESTAMP WHERE id = $5 RETURNING *',
[name, hex, cena_refill || 3499, cena_spulna || 3999, id]
);
res.json(result.rows[0]);
} catch (error) {
console.error('Error updating color:', error);
res.status(500).json({ error: 'Failed to update color' });
}
});
app.delete('/api/colors/:id', authenticateToken, async (req, res) => {
const { id } = req.params;
try {
await pool.query('DELETE FROM colors WHERE id = $1', [id]);
res.json({ success: true });
} catch (error) {
console.error('Error deleting color:', error);
res.status(500).json({ error: 'Failed to delete color' });
}
});
// Filaments endpoints (PUBLIC - no auth required)
app.get('/api/filaments', async (req, res) => {
try {
const result = await pool.query('SELECT * FROM filaments ORDER BY created_at DESC');
res.json(result.rows);
} catch (error) {
console.error('Error fetching filaments:', error);
res.status(500).json({ error: 'Failed to fetch filaments' });
}
});
app.post('/api/filaments', authenticateToken, async (req, res) => {
const { tip, finish, boja, boja_hex, refill, spulna, cena } = req.body;
try {
// Ensure refill and spulna are numbers
const refillNum = parseInt(refill) || 0;
const spulnaNum = parseInt(spulna) || 0;
const kolicina = refillNum + spulnaNum;
const result = await pool.query(
`INSERT INTO filaments (tip, finish, boja, boja_hex, refill, spulna, kolicina, cena)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8) RETURNING *`,
[tip, finish, boja, boja_hex, refillNum, spulnaNum, kolicina, cena]
);
res.json(result.rows[0]);
} catch (error) {
console.error('Error creating filament:', error);
res.status(500).json({ error: 'Failed to create filament' });
}
});
app.put('/api/filaments/:id', authenticateToken, async (req, res) => {
const { id } = req.params;
const { tip, finish, boja, boja_hex, refill, spulna, cena } = req.body;
try {
// Ensure refill and spulna are numbers
const refillNum = parseInt(refill) || 0;
const spulnaNum = parseInt(spulna) || 0;
const kolicina = refillNum + spulnaNum;
const result = await pool.query(
`UPDATE filaments
SET tip = $1, finish = $2, boja = $3, boja_hex = $4,
refill = $5, spulna = $6, kolicina = $7, cena = $8,
updated_at = CURRENT_TIMESTAMP
WHERE id = $9 RETURNING *`,
[tip, finish, boja, boja_hex, refillNum, spulnaNum, kolicina, cena, id]
);
res.json(result.rows[0]);
} catch (error) {
console.error('Error updating filament:', error);
res.status(500).json({ error: 'Failed to update filament' });
}
});
app.delete('/api/filaments/:id', authenticateToken, async (req, res) => {
const { id } = req.params;
try {
await pool.query('DELETE FROM filaments WHERE id = $1', [id]);
res.json({ success: true });
} catch (error) {
console.error('Error deleting filament:', error);
res.status(500).json({ error: 'Failed to delete filament' });
}
});
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});