mirror of
https://github.com/usatiuk/ustk-todolist.git
synced 2025-10-28 15:47:48 +01:00
54 lines
1.1 KiB
JavaScript
54 lines
1.1 KiB
JavaScript
const express = require('express');
|
|
const mongoose = require('mongoose');
|
|
const slugify = require('slugify');
|
|
|
|
const router = express.Router();
|
|
|
|
const { NotFoundError } = require('../errors');
|
|
|
|
const TodoList = mongoose.model('TodoList');
|
|
|
|
const asyncHelper = require('../asyncHelper');
|
|
|
|
// index
|
|
router.get(
|
|
'/',
|
|
asyncHelper(async (req, res) => {
|
|
const lists = await TodoList.find({})
|
|
.populate('todos')
|
|
.exec();
|
|
res.json(lists);
|
|
}),
|
|
);
|
|
|
|
// create
|
|
router.post(
|
|
'/',
|
|
asyncHelper(async (req, res) => {
|
|
const { name } = req.body;
|
|
const newList = new TodoList({ name });
|
|
newList.slug = slugify(name);
|
|
await newList.save();
|
|
res.json({ success: true });
|
|
}),
|
|
);
|
|
|
|
router.delete(
|
|
'/:slug',
|
|
asyncHelper(async (req, res) => {
|
|
const { slug } = req.params;
|
|
const list = await TodoList.findOne({ slug })
|
|
.populate('todos')
|
|
.exec();
|
|
if (!list) {
|
|
throw new NotFoundError();
|
|
}
|
|
list.todos.forEach((todo) => {
|
|
todo.remove();
|
|
});
|
|
list.remove();
|
|
res.json({ success: true });
|
|
}),
|
|
);
|
|
module.exports = router;
|