-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
111 lines (81 loc) · 2.01 KB
/
server.js
File metadata and controls
111 lines (81 loc) · 2.01 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
106
107
108
109
110
111
// BASE SETUP
// dependencies
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var morgan = require('morgan');
// log requests to the console
app.use(morgan('dev'));
// configure body parser
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = Number(process.env.PORT || 8080);
var mongoose = require('mongoose');
// connect to database
mongoose.connect('mongodb://dima:123@ds039135.mongolab.com:39135/heroku_xkbthxdx');
var Bear = require('./app/models/bear');
// ROUTES
var router = express.Router();
// middleware to use for all requests
router.use(function(req, res, next) {
console.log('Something is happening.');
next();
});
router.get('/', function(req, res) {
res.json({ message: 'hooray! welcome to our api!' });
});
router.route('/bears')
.post(function(req, res) {
var bear = new Bear();
bear.name = req.body.name;
console.log(req.body.name + " body");
bear.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Bear created!' });
});
})
.get(function(req, res) {
Bear.find(function(err, bears) {
if (err) {
res.send(err);
console.log(bears);
}
console.log(bears);
res.json(bears);
});
});
router.route('/bears/:bear_id')
.get(function(req, res) {
Bear.findById(req.params.bear_id, function(err, bear) {
if (err)
res.send(err);
res.json(bear);
});
})
.put(function(req, res) {
Bear.findById(req.params.bear_id, function(err, bear) {
if (err)
res.send(err);
bear.name = req.body.name;
bear.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Bear updated!' });
});
});
})
.delete(function(req, res) {
Bear.remove({
_id: req.params.bear_id
}, function(err, bear) {
if (err)
res.send(err);
res.json({ message: 'Successfully deleted' });
});
});
// REGISTER ROUTES
app.use('/', router);
// START THE SERVER
app.listen(port);
console.log('Magic happens on port ' + port);