-
Notifications
You must be signed in to change notification settings - Fork 3
/
app.js
85 lines (72 loc) · 1.83 KB
/
app.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
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/contacts');
var express = require('express');
var bodyParser = require('body-parser');
var jsonParser = bodyParser.json();
var app = express();
var Contact = require('./lib/contacts.js');
var util = require('util');
app.get('/contacts', function(req, res) {
Contact.find({}, function(error, contactList) {
res.json(contactList);
});
});
app.get('/contacts/:id', function(req, res) {
Contact.find({
_id: req.params.id
}, function(error, contact) {
res.json(contact);
});
});
app.post('/contacts', jsonParser);
app.post('/contacts', function(req, res) {
Contact.create(req.body, function(error, contact) {
if (error) {
console.log(error);
res.sendStatus(400);
} else {
res.sendStatus(201);
}
});
});
app.put('/contacts/:id', jsonParser);
app.put('/contacts/:id', function(req, res) {
Contact.findByIdAndUpdate(req.params.id, req.body, function(error, contact) {
if (error) {
console.log(error);
res.sendStatus(400);
} else {
res.sendStatus(200);
}
});
});
app.patch('/contacts/:id', jsonParser);
app.patch('/contacts/:id', function(req, res) {
Contact.findByIdAndUpdate(req.params.id, {
$set: req.body
}, function(error, contact) {
if (error) {
console.log(error);
res.sendStatus(400);
} else {
res.sendStatus(200);
}
});
});
app.delete('/contacts/:id', function(req, res) {
Contact.remove({
_id: req.params.id
}, function(error) {
if (error) {
console.log(error);
res.sendStatus(400);
} else {
res.sendStatus(204);
}
});
});
var server = app.listen(3000, function() {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});