tasks.js
2.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
var express = require('express'),
User = require('../models/User'),
Task = require('../models/Task');
module.exports = function(io) {
var router = express.Router();
function needAuth(req, res, next) {
if (req.isAuthenticated()) {
next();
} else {
res.status(401).json({message: 'Not authorized'});
}
}
router.get('/', needAuth, function(req, res, next) {
Task.find({user: req.user.id}, function(err, tasks) {
if (err) {
return res.status(500).json({message: 'internal error', desc: err});
}
res.json(tasks);
});
});
router.post('/', needAuth, function(req, res, next) {
console.log(req.body);
if (!req.body.content) {
return res.status(400).json({message: 'need content'});
}
var task = new Task({
content: req.body.content,
category: req.body.category || "N/A",
priority: req.body.priority || 3,
deadline: req.body.deadline,
user: req.user.id
});
task.save(function(err, doc) {
if (err) {
return res.status(500).json({message: 'internal error', desc: err});
}
io.to(req.user.id.toString()).emit('updated');
res.status(201).json(doc);
});
});
router.put('/:id', needAuth, function(req, res, next) {
Task.findById(req.params.id, function(err, task) {
if (err) {
return res.status(500).json({message: 'internal error', desc: err});
}
if (!task) {
return res.status(404).json({message: 'task not found'});
}
if (req.body.content) {
task.content = req.body.content;
}
if (req.body.category) {
task.category = req.body.category;
}
if (req.body.priority) {
task.priority = req.body.priority;
}
if (req.body.deadline) {
task.deadline = req.body.deadline;
}
if (req.body.done) {
task.done = req.body.done;
}
task.save(function(err) {
if (err) {
return res.status(500).json({message: 'internal error', desc: err});
}
io.to(req.user.id.toString()).emit('updated');
res.json(task);
});
});
});
router.get('/:id', needAuth, function(req, res, next) {
Task.findById(req.params.id, function(err, task) {
if (err) {
return res.status(500).json({message: 'internal error', desc: err});
}
if (!task) {
return res.status(404).json({message: 'task not found'});
}
res.json(task);
});
});
router.delete('/:id', needAuth, function(req, res, next) {
Task.findOneAndRemove({_id: req.params.id}, function(err, task) {
if (err) {
return res.status(500).json({message: 'internal error', desc: err});
}
if (!task) {
return res.status(404).json({message: 'task not found'});
}
io.to(req.user.id.toString()).emit('updated');
res.json({id: task._id});
});
});
return router;
};