2025-08-28 23:04:25 +03:00

101 lines
2.5 KiB
JavaScript

const express = require('express');
const router = express.Router();
const db = require('../database');
// Get all cards
router.get('/', (req, res) => {
db.all('SELECT * FROM cards ORDER BY created_at DESC', (err, rows) => {
if (err) {
console.error(err);
res.status(500).json({ error: 'Database error' });
} else {
res.json(rows);
}
});
});
// Get card by ID
router.get('/:id', (req, res) => {
const { id } = req.params;
db.get('SELECT * FROM cards WHERE id = ?', [id], (err, row) => {
if (err) {
console.error(err);
res.status(500).json({ error: 'Database error' });
} else if (!row) {
res.status(404).json({ error: 'Card not found' });
} else {
res.json(row);
}
});
});
// Create new card
router.post('/', (req, res) => {
const { name, bank, description, image_url } = req.body;
if (!name || !bank) {
return res.status(400).json({ error: 'Name and bank are required' });
}
db.run(
'INSERT INTO cards (name, bank, description, image_url) VALUES (?, ?, ?, ?)',
[name, bank, description, image_url],
function(err) {
if (err) {
console.error(err);
res.status(500).json({ error: 'Database error' });
} else {
res.status(201).json({
id: this.lastID,
name,
bank,
description,
image_url
});
}
}
);
});
// Update card
router.put('/:id', (req, res) => {
const { id } = req.params;
const { name, bank, description, image_url } = req.body;
if (!name || !bank) {
return res.status(400).json({ error: 'Name and bank are required' });
}
db.run(
'UPDATE cards SET name = ?, bank = ?, description = ?, image_url = ? WHERE id = ?',
[name, bank, description, image_url, id],
function(err) {
if (err) {
console.error(err);
res.status(500).json({ error: 'Database error' });
} else if (this.changes === 0) {
res.status(404).json({ error: 'Card not found' });
} else {
res.json({ id: parseInt(id), name, bank, description, image_url });
}
}
);
});
// Delete card
router.delete('/:id', (req, res) => {
const { id } = req.params;
db.run('DELETE FROM cards WHERE id = ?', [id], function(err) {
if (err) {
console.error(err);
res.status(500).json({ error: 'Database error' });
} else if (this.changes === 0) {
res.status(404).json({ error: 'Card not found' });
} else {
res.json({ message: 'Card deleted successfully' });
}
});
});
module.exports = router;