remove lists

This commit is contained in:
2018-05-17 12:13:14 +03:00
parent 5486b4582f
commit 8255ec05b9
4 changed files with 43 additions and 9 deletions

22
app.js
View File

@@ -44,15 +44,21 @@ app.use((req, res) => {
});
// handle errors
app.use((err, req, res, next) => {
if (err.name === 'ValidationError') {
res.status(400);
res.json({ success: false, error: err });
} else {
res.status(500);
res.json({ success: false, error: err });
app.use((error, req, res, next) => {
switch (error.name) {
case 'ValidationError':
res.status(400);
res.json({ success: false, error });
break;
case 'NotFound':
res.status(404);
res.json({ success: false, error });
break;
default:
res.status(500);
res.json({ success: false, error });
}
next(err);
next(error);
});
app.listen(process.env.PORT, () => {

9
errors/index.js Normal file
View File

@@ -0,0 +1,9 @@
class NotFoundError extends Error {
constructor(...args) {
super(...args);
Error.captureStackTrace(this, NotFoundError);
this.name = 'NotFound';
}
}
module.exports = { NotFoundError };

View File

@@ -6,7 +6,7 @@
"main": "app.js",
"scripts": {
"start": "node ./app.js",
"start-mon": "npx nodemon --inspect ./app.js",
"debug": "npx nodemon --inspect ./app.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",

View File

@@ -3,6 +3,8 @@ const mongoose = require('mongoose');
const router = express.Router();
const { NotFoundError } = require('../errors');
const TodoList = mongoose.model('TodoList');
const asyncHelper = require('../asyncHelper');
@@ -29,4 +31,21 @@ router.post(
}),
);
router.delete(
'/:id',
asyncHelper(async (req, res) => {
const { id } = req.params;
const list = await TodoList.findById(id)
.populate('todos')
.exec();
if (!list) {
throw new NotFoundError();
}
list.todos.forEach((todo) => {
todo.remove();
});
list.remove();
res.json({ success: true });
}),
);
module.exports = router;