Files
ustk-todolist/routes/lists.js
2018-05-23 20:46:47 +03:00

72 lines
1.5 KiB
JavaScript

const express = require('express');
const mongoose = require('mongoose');
const router = express.Router();
const TodoList = mongoose.model('TodoList');
const asyncHelper = require('../asyncHelper');
const listIdMiddleware = require('./listIdMiddleware');
// index
router.get(
'/',
asyncHelper(async (req, res) => {
const lists = await TodoList.find({})
.populate('todos')
.exec();
res.json({ success: true, data: lists.map(list => list.toJson()) });
}),
);
// create
router.post(
'/',
asyncHelper(async (req, res) => {
const { name } = req.body;
const newList = new TodoList({ name });
await newList.save();
res.json({ success: true, data: newList.toJson() });
}),
);
// delete
router.delete(
'/:slug',
listIdMiddleware,
asyncHelper(async (req, res) => {
const { listId } = res.locals;
const list = await TodoList.findById(listId)
.populate('todos')
.exec();
await list.remove();
res.json({ success: true });
}),
);
// update
router.patch(
'/:slug',
listIdMiddleware,
asyncHelper(async (req, res) => {
const { listId } = res.locals;
const { name } = req.body;
const patch = {};
if (name !== undefined) {
patch.name = name;
}
const list = await TodoList.findByIdAndUpdate(
{ _id: listId },
{ $set: patch },
{ new: true },
).exec();
await list.slugify();
await list.save();
res.json({ success: true, data: list.toJson() });
}),
);
router.use('/:slug/todos', listIdMiddleware, require('./todos'));
module.exports = router;