Files
ustk-todolist/routes/todos.js
2018-05-30 21:42:30 +03:00

68 lines
1.6 KiB
JavaScript

const express = require('express');
const mongoose = require('mongoose');
const router = express.Router();
const Todo = mongoose.model('Todo');
const asyncHelper = require('../asyncHelper');
const { NotFoundError } = require('../errors');
// index
router.get(
'/',
asyncHelper(async (req, res) => {
const { listId } = res.locals || req.body;
const todos = await Todo.find({ list: listId, user: req.user.id }).exec();
res.json({ success: true, data: todos.map(todo => todo.toJson()) });
}),
);
// create
router.post(
'/',
asyncHelper(async (req, res) => {
const { listId } = res.locals || req.body;
const { text } = req.body;
const todo = new Todo({ text, list: listId, user: req.user.id });
await todo.save();
res.json({ success: true, data: todo.toJson() });
}),
);
// update
router.patch(
'/:todoId',
asyncHelper(async (req, res) => {
const { todoId } = req.params;
const { text, completed } = req.body;
const todo = await Todo.find({ _id: todoId, user: req.user.id });
if (!todo) {
throw new NotFoundError("can't find todo");
}
if (text !== undefined) {
todo.text = text;
}
if (completed !== undefined) {
todo.completed = completed;
}
res.json({ success: true, data: todo.toJson() });
}),
);
// delete
router.delete(
'/:todoId',
asyncHelper(async (req, res) => {
const { todoId } = req.params;
const todo = await Todo.find({ _id: todoId, user: req.user.id }).exec();
if (!todo) {
throw new NotFoundError(`can't find todo with id ${todoId}`);
}
await todo.remove();
res.json({ success: true });
}),
);
module.exports = router;