66 lines
3.2 KiB
JavaScript
66 lines
3.2 KiB
JavaScript
function createCrudRoutes(app, auth, table, options = {}) {
|
||
const { authenticateToken, requireAdmin } = auth;
|
||
const prefix = options.prefix || `/api/admin/${table}`;
|
||
const allowedFields = options.fields || [];
|
||
const extraRoutes = options.extraRoutes || null;
|
||
|
||
app.get(prefix, authenticateToken, requireAdmin, (req, res) => {
|
||
const orderBy = options.orderBy || 'sort_order';
|
||
db.all(`SELECT * FROM ${table} ORDER BY ${orderBy}`, (err, rows) => {
|
||
if (err) { console.error(err); return res.status(500).json({ error: 'Ошибка БД' }); }
|
||
res.json(rows);
|
||
});
|
||
});
|
||
|
||
app.post(prefix, authenticateToken, requireAdmin, (req, res) => {
|
||
const values = allowedFields.map(f => req.body[f] !== undefined ? req.body[f] : null);
|
||
const placeholders = values.map(() => '?').join(', ');
|
||
const cols = allowedFields.join(', ');
|
||
const stmt = db.prepare(`INSERT INTO ${table} (${cols}) VALUES (${placeholders})`);
|
||
stmt.run(...values, function(err) {
|
||
if (err) { console.error(err); return res.status(500).json({ error: 'Ошибка создания' }); }
|
||
db.get(`SELECT * FROM ${table} WHERE id = ?`, [this.lastID], (err2, row) => {
|
||
if (err2) return res.status(500).json({ error: 'Ошибка получения' });
|
||
res.status(201).json(row);
|
||
});
|
||
});
|
||
stmt.finalize();
|
||
});
|
||
|
||
app.put(`${prefix}/:id`, authenticateToken, requireAdmin, (req, res) => {
|
||
const id = parseInt(req.params.id);
|
||
if (isNaN(id)) return res.status(400).json({ error: 'Неверный ID' });
|
||
const setClauses = allowedFields.map(f => `${f} = ?`).join(', ');
|
||
const values = allowedFields.map(f => req.body[f] !== undefined ? req.body[f] : null);
|
||
values.push(id);
|
||
const stmt = db.prepare(`UPDATE ${table} SET ${setClauses} WHERE id = ?`);
|
||
stmt.run(...values, function(err) {
|
||
if (err) { console.error(err); return res.status(500).json({ error: 'Ошибка обновления' }); }
|
||
if (this.changes === 0) return res.status(404).json({ error: 'Не найдено' });
|
||
db.get(`SELECT * FROM ${table} WHERE id = ?`, [id], (err2, row) => {
|
||
if (err2) return res.status(500).json({ error: 'Ошибка получения' });
|
||
res.json(row);
|
||
});
|
||
});
|
||
stmt.finalize();
|
||
});
|
||
|
||
app.delete(`${prefix}/:id`, authenticateToken, requireAdmin, (req, res) => {
|
||
const id = parseInt(req.params.id);
|
||
if (isNaN(id)) return res.status(400).json({ error: 'Неверный ID' });
|
||
const stmt = db.prepare(`DELETE FROM ${table} WHERE id = ?`);
|
||
stmt.run(id, function(err) {
|
||
if (err) { console.error(err); return res.status(500).json({ error: 'Ошибка удаления' }); }
|
||
if (this.changes === 0) return res.status(404).json({ error: 'Не найдено' });
|
||
res.json({ message: 'Удалено' });
|
||
});
|
||
stmt.finalize();
|
||
});
|
||
|
||
if (extraRoutes) extraRoutes(app, authenticateToken, requireAdmin);
|
||
}
|
||
|
||
let db;
|
||
function init(database) { db = database; }
|
||
module.exports = { createCrudRoutes, init };
|