51 lines
No EOL
1.5 KiB
JavaScript
51 lines
No EOL
1.5 KiB
JavaScript
module.exports = async function (app, opts) {
|
|
const db = require('../db');
|
|
const counterCreated = opts.counterCreated;
|
|
const counterDeleted = opts.counterDeleted;
|
|
const gaugeCount = opts.gaugeCount;
|
|
|
|
function refreshGauge() {
|
|
try {
|
|
const count = db.all().length;
|
|
gaugeCount.set(count);
|
|
} catch { }
|
|
}
|
|
|
|
app.get('/ui', async (req, reply) => {
|
|
if (!req.session.user) {
|
|
return reply.view('login_required.ejs', { user: req.session.user });
|
|
}
|
|
const todos = db.getTodosByUser(req.session.user.id);
|
|
return reply.view('index.ejs', { todos, user: req.session.user });
|
|
});
|
|
|
|
app.post('/ui/todos', async (req, reply) => {
|
|
const title = (req.body?.title || '').trim();
|
|
if (title) {
|
|
db.createTodo(req.session.user.id, title);
|
|
counterCreated.inc();
|
|
refreshGauge();
|
|
}
|
|
reply.redirect('/ui');
|
|
});
|
|
|
|
app.post('/ui/todos/:id/toggle', async (req, reply) => {
|
|
const id = Number(req.params.id);
|
|
const todo = db.getTodo(id);
|
|
if (todo) {
|
|
db.updateTodo(id, { completed: todo.completed ? 0 : 1 });
|
|
refreshGauge();
|
|
}
|
|
reply.redirect('/ui');
|
|
});
|
|
|
|
app.post('/ui/todos/:id/delete', async (req, reply) => {
|
|
const id = Number(req.params.id);
|
|
if (db.getTodo(id)) {
|
|
db.removeTodo(id);
|
|
counterDeleted.inc();
|
|
refreshGauge();
|
|
}
|
|
reply.redirect('/ui');
|
|
});
|
|
}; |