-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
90 lines (76 loc) · 2.35 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
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var fs = require('fs');
// connet to mongodb
mongoose.connect('mongodb://learn-mongo:learn@ds243008.mlab.com:43008/learn-mongo');
var db = mongoose.connection;
//var Person = require('./models/person.js');
var Activity = require('./models/activities.js');
var PORT = process.env.PORT || 3000;
var middlewares = {
logger: function(req, res, next){
fs.appendFile('logs.txt', new Date().toString() +' | '+ req.method + ' | ' + req.connection.remoteAddress + ' | ' + req.originalUrl + '\n', (err) => {
// throws an error, you could also catch it here
if (err) throw err;
});
next();
}
};
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json()); // support json encoded bodies
//app.use(express.static(__dirname + '/public'));
// root level route
app.get('/', function(req, res){
res.send('welcome to my api');
});
// get all the activities
app.get('/api/activity', function(req, res){
Activity.find({},function(err, activities){
if(err){
throw err;
}
res.json(activities);
}).limit(200);
});
// get the single activity
app.get('/api/activity/:id', function(req, res){
Activity.findById(new mongoose.Types.ObjectId(req.params.id),function(err, activity){
if(err){
throw err;
}
res.json(activity);
});
});
// create activity
app.post('/api/activity', (req, res)=>{
req.body._id = mongoose.Types.ObjectId;
Activity.create(req.body,function(err, newActivity){
if(err){
throw err;
}
res.json(newActivity);
});
})
// update activity
app.put('/api/activity/:id', function(req, res){
Activity.findOneAndUpdate(new mongoose.Types.ObjectId(req.params.id), req.body,function(err, activity){
if(err){
throw err;
}
res.json(activity);
});
});
// delete item
app.delete('/api/activity/:id', function(req, res){
Activity.remove({_id : new mongoose.Types.ObjectId(req.params.id)},function(err, activity){
if(err){
throw err;
}
res.json('The item was deleted!');
});
});
app.listen(PORT, function(){
console.log('Node is running on port ' + PORT);
});