use list id for routing

This commit is contained in:
2018-05-27 15:07:50 +03:00
parent 6598874331
commit 00f71bb78d
5 changed files with 1388 additions and 6546 deletions

View File

@@ -1,17 +0,0 @@
const mongoose = require('mongoose');
const asyncHelper = require('../asyncHelper');
const TodoList = mongoose.model('TodoList');
const { NotFoundError } = require('../errors');
// listId middleware
module.exports = asyncHelper(async (req, res, next) => {
const { slug } = req.params;
const list = await TodoList.findOne({ slug }).exec();
if (!list) {
throw new NotFoundError('cant find list');
}
res.locals.listId = list._id;
next();
});

View File

@@ -7,8 +7,6 @@ const TodoList = mongoose.model('TodoList');
const asyncHelper = require('../asyncHelper');
const listIdMiddleware = require('./listIdMiddleware');
// index
router.get(
'/',
@@ -33,10 +31,9 @@ router.post(
// delete
router.delete(
'/:slug',
listIdMiddleware,
'/:listId',
asyncHelper(async (req, res) => {
const { listId } = res.locals;
const { listId } = req.params;
const list = await TodoList.findById(listId)
.populate('todos')
.exec();
@@ -47,10 +44,9 @@ router.delete(
// update
router.patch(
'/:slug',
listIdMiddleware,
'/:listId',
asyncHelper(async (req, res) => {
const { listId } = res.locals;
const { listId } = req.params;
const { name } = req.body;
const patch = {};
if (name !== undefined) {
@@ -61,11 +57,17 @@ router.patch(
{ $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'));
router.use(
'/:listId/todos',
(req, res, next) => {
res.locals.listId = req.params.listId;
next();
},
require('./todos'),
);
module.exports = router;