-
Notifications
You must be signed in to change notification settings - Fork 149
/
server.js
95 lines (81 loc) · 2.75 KB
/
server.js
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
var application_root = __dirname,
express = require('express'),
app = express(),
path = require('path'),
config = require('config'),
orm = require('./orm').configure(config.get('database')),
Tasks = require('./db/models/task').instance(orm),
server = require('http').createServer(app),
socket = require('socket.io'),
bodyParser = require('body-parser'),
methodOverride = require('method-override'),
errorHandler = require('errorhandler');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// override with the X-HTTP-Method-Override header in the request
app.use(methodOverride('X-HTTP-Method-Override'));
app.use(express.static(path.join(application_root, 'public')));
if (process.env.NODE_ENV === 'development') {
// only use in development
app.use(errorHandler({
dumpExceptions: true,
showStack: true
}));
}
var port = process.env.PORT || config.get('port');
server.listen(port, function () {
console.log('Express server listening on port %d in %s mode', port, app.settings.env);
});
var io = socket.listen(server);
app.get('/tasks', function (req, res) {
return Tasks.all().then(function (tasks) {
return res.send(tasks);
});
});
app.post('/tasks', function (req, res) {
return Tasks.create({
content: req.body.content,
parentId: req.body.parentId || '00000000-0000-0000-0000-000000000000',
isCompleted: false
}).then(function (task) {
return res.send(task);
});
});
app.put('/tasks', function (req, res) {
return Tasks.create({
content: req.body.content,
parentId: req.body.parentId || '00000000-0000-0000-0000-000000000000',
isCompleted: false
}).then(function (task) {
return res.send(task);
});
});
app.get('/tasks/:id', function (req, res) {
return Tasks.findById(req.params.id).then(function (task) {
return res.send(task);
});
});
app.put('/tasks/:id', function (req, res) {
Tasks.findById(req.params.id).then(function (task) {
task.content = req.body.content;
task.priority = req.body.priority;
task.parentId = req.body.parentId || '00000000-0000-0000-0000-000000000000';
task.isFolded = req.body.isFolded == true;
task.isCompleted = req.body.isCompleted == true;
return task.save().then(function (task) {
return res.send(task);
});
});
});
app.delete('/tasks/:id', function (req, res) {
Tasks.findById(req.params.id).then(function (task) {
return task.destroy().then(function () {
return res.send('');
});
});
});
io.sockets.on('connection', function (socket) {
socket.on('task', function (data) {
socket.broadcast.emit('task', data);
});
});