This commit is contained in:
2018-05-19 19:51:04 +03:00
parent 8f0509b8f2
commit 97921d6ccc
4 changed files with 53 additions and 4 deletions

4
app.js
View File

@@ -37,6 +37,10 @@ app.use((error, req, res, next) => {
res.status(404);
res.json({ success: false, error });
break;
case 'BadRequestError':
res.status(400);
res.json({ success: false, error });
break;
default:
res.status(500);
res.json({ success: false, error });

View File

@@ -6,4 +6,12 @@ class NotFoundError extends Error {
}
}
module.exports = { NotFoundError };
class BadRequestError extends Error {
constructor(...args) {
super(...args);
Error.captureStackTrace(this, NotFoundError);
this.name = 'BadRequest';
}
}
module.exports = { NotFoundError, BadRequestError };

View File

@@ -3,8 +3,6 @@ const mongoose = require('mongoose');
const router = express.Router();
const { NotFoundError } = require('../errors');
const TodoList = mongoose.model('TodoList');
const asyncHelper = require('../asyncHelper');
@@ -47,6 +45,27 @@ router.delete(
}),
);
// update
router.patch(
'/:slug',
listIdMiddleware,
asyncHelper(async (req, res) => {
const { listId } = res.locals;
const { name } = req.body;
const patch = {};
if (name) {
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 });
}),
);
router.use('/:slug/todos', listIdMiddleware, require('./todos'));
module.exports = router;

View File

@@ -29,11 +29,29 @@ router.post(
}),
);
// update
router.patch(
'/:todoId',
asyncHelper(async (req, res) => {
const { todoId } = req.params;
const { text, completed } = req.body;
const patch = {};
if (text) {
patch.text = text;
}
if (completed) {
patch.completed = completed;
}
await Todo.update({ _id: todoId }, { $set: patch }).exec();
res.json({ success: true });
}),
);
// delete
router.delete(
'/:todoId',
asyncHelper(async (req, res) => {
const { todoId } = req.params;
console.log(todoId);
await Todo.findByIdAndRemove(todoId).exec();
res.json({ success: true });
}),