-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
100 lines (80 loc) · 2.18 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
96
97
var http = require('http'),
express = require('express'),
mongoose = require('mongoose'),
morgan = require('morgan'),
bodyParser = require('body-parser'),
methodOverride = require('method-override'),
fs = require('fs'),
app = express();
mongoose.connect('mongodb://localhost:27017');
app.use(express.static('client'));
app.use(morgan('dev'));
app.use(bodyParser.urlencoded({'extended':'true'}));
app.use(bodyParser.json());
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
app.use(methodOverride());
var Todo = mongoose.model('Todo', {
title: String,
order: Number,
completed: Boolean
});
app.get('/api/todos', function(req, res){
Todo.find(function(err, todos){
if(err){
res.send(err);
} else {
res.json(todos);
}
});
});
app.post('/api/todos', function(req, res){
var todo = new Todo({
title: req.body.title,
order: req.body.order,
completed: req.body.completed
});
todo.save(function() {
res.send(todo);
});
});
app.put('/api/todos/:id', function(req, res){
var todo = new Todo({
title: req.body.title,
order: req.body.order,
completed: req.body.completed
});
var id = req.params.id;
Todo.findById(id, function(err, todo){
if(err){
throw err;
}
todo.title = req.body.title;
todo.order = req.body.order;
todo.completed = req.body.completed;
todo.save(function(err) {
if(err){
throw err;
}
res.send(todo);
});
});
});
app.delete('/api/todos/:id', function(req, res){
var id = req.params.id;
Todo.findById(id, function(err, todo){
if(err){
throw err;
}
todo.remove(function(err) {
if(err){
throw err;
}
});
});
res.end();
});
app.get('/', function(req,res){
res.end(fs.readFileSync('index.html'));
})
app.listen(8888);
console.log("Server started");