This repository has been archived by the owner on Dec 4, 2017. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.js
79 lines (69 loc) · 2.06 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
/*eslint new-cap:0 */
'use strict';
var path = require('path');
var express = require('express');
var bodyParser = require('body-parser');
var errorHandler = require('errorhandler');
var app = express();
var http = require('http').Server(app);
var mongoose = require('mongoose');
var options = {
port: process.env.VCAP_APP_PORT || 3000,
mongo: process.env.MONGO || 'mongodb://localhost/yow-hackathon'
};
if(process.env.VCAP_SERVICES){
var svcs = JSON.parse(process.env.VCAP_SERVICES);
options.mongo = svcs['mongodb-2.2'][0].credentials.url;
}
var Attendee = mongoose.model('Attendee', {
mail: {type: String, unique: true},
name: String,
is_attending: Boolean,
pizza: String
});
function demongify(doc) {
doc = doc.toObject();
delete doc._id;
delete doc.__v;
return doc;
}
mongoose.connect(options.mongo);
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, '/public')));
app.use(errorHandler({ dumpExceptions: true, showStack: true }));
app.get('/api/attendees', function(req, res) {
Attendee.find(function(err, attendees) {
if(!err) {
return res.send(attendees.map(demongify));
} else {
return console.error(err);
}
});
});
app.post('/api/attendees', function (req, res) {
Attendee.findOneAndUpdate({mail: req.body.mail}, {
name: req.body.name,
is_attending: req.body.is_attending,
pizza: req.body.pizza
}, {upsert: true}, function(err, attendee) {
if(err) {
return console.error(err);
} else {
return res.send(demongify(attendee));
}
});
});
app.get('/api/attendees/:mail', function (req, res){
return Attendee.findOne({ mail: req.params.mail}, function (err, attendee) {
if (!err ) {
if(attendee) {
return res.send(demongify(attendee));
} else {
return res.status(404).send('Not found ' + req.params.mail);
}
} else {
return console.log(err);
}
});
});
http.listen(options.port);