Files
web-cad/backend/routes/drawings.js
T

95 lines
2.5 KiB
JavaScript

const express = require('express');
const authenticate = require('../middleware/auth');
const Drawing = require('../models/Drawing');
const router = express.Router();
// All routes require authentication
router.use(authenticate);
// List drawings for current user
router.get('/', async (req, res) => {
try {
const drawings = await Drawing.findAll({
where: { userId: req.user.id },
attributes: ['id', 'name', 'updatedAt'],
order: [['updatedAt', 'DESC']],
});
res.json(drawings);
} catch (err) {
console.error(err);
res.status(500).json({ error: 'Failed to list drawings' });
}
});
// Create new drawing
router.post('/', async (req, res) => {
try {
const { name, canvas_json } = req.body;
const drawing = await Drawing.create({
name: name || 'Unbenannt',
canvas_json: canvas_json || '',
userId: req.user.id,
});
res.status(201).json(drawing);
} catch (err) {
console.error(err);
res.status(500).json({ error: 'Failed to create drawing' });
}
});
// Get single drawing
router.get('/:id', async (req, res) => {
try {
const drawing = await Drawing.findOne({
where: { id: req.params.id, userId: req.user.id },
});
if (!drawing) {
return res.status(404).json({ error: 'Drawing not found' });
}
res.json(drawing);
} catch (err) {
console.error(err);
res.status(500).json({ error: 'Failed to get drawing' });
}
});
// Update drawing
router.put('/:id', async (req, res) => {
try {
const drawing = await Drawing.findOne({
where: { id: req.params.id, userId: req.user.id },
});
if (!drawing) {
return res.status(404).json({ error: 'Drawing not found' });
}
const { name, canvas_json } = req.body;
if (name !== undefined) drawing.name = name;
if (canvas_json !== undefined) drawing.canvas_json = canvas_json;
await drawing.save();
res.json(drawing);
} catch (err) {
console.error(err);
res.status(500).json({ error: 'Failed to update drawing' });
}
});
// Delete drawing
router.delete('/:id', async (req, res) => {
try {
const drawing = await Drawing.findOne({
where: { id: req.params.id, userId: req.user.id },
});
if (!drawing) {
return res.status(404).json({ error: 'Drawing not found' });
}
await drawing.destroy();
res.json({ message: 'Drawing deleted' });
} catch (err) {
console.error(err);
res.status(500).json({ error: 'Failed to delete drawing' });
}
});
module.exports = router;