-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
134 lines (108 loc) · 3.54 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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
// server.js
/* ========================================
* ============= SETUP ====================
* ======================================== */
var express = require('express');
var bodyParser = require('body-parser');
var mongodb = require('mongodb');
var path = require('path');
//var ObjectID = mongodb.ObjectID;
var ObjectID = require('mongodb').ObjectID;
var PLAYERS_COLLECTION = 'players';
var app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8080;
// Create database variable to reuse connection pool in app
var db;
// Connect to database before starting application server
var uri = process.env.MONGODB_URI || process.env.MONGOLAB_URI ||
'mongodb://heroku_506s23zx:[email protected]:21171/heroku_506s23zx';
mongodb.MongoClient.connect(uri, function (err, database) {
if (err) {
console.log(err);
process.exit(1);
}
// Save database object from the callback for reuse
db = database;
console.log('Database connection ready');
// Initialize app
var server = app.listen(port, function () {
console.log('Listening on port', port);
});
});
// Set locations of static files
app.use(express.static(path.join(__dirname, '/dist')));
/* ========================================
* ============= API ROUTES ===============
* ======================================== */
// Error handler
function handleError(res, reason, message, code) {
console.log('Error: ' + reason);
res.status(code || 500).json({'error': message});
}
/* '/api/players'
* GET: finds all players
* POST: creates a new player
*/
app.get('/api/players', function(req, res) {
db.collection(PLAYERS_COLLECTION).find({}).toArray(function(err, docs) {
if (err) {
handleError(res, err.message, 'Failed to get players.');
} else {
res.status(200).json(docs);
}
});
});
app.post('/api/players', function(req, res) {
var newPlayer = req.body;
newPlayer.mturk_code = (function() {
var code = '';
var candidates = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
for (var i=0; i < 8; i++)
code += candidates.charAt(Math.floor(Math.random() * candidates.length));
return code;
})();
db.collection(PLAYERS_COLLECTION).insertOne(newPlayer, function(err, doc) {
if (err) {
handleError(res, err.message, 'Failed to create new player.');
} else {
res.status(201).json(doc.ops[0]);
}
});
});
/* '/api/players/:id'
* GET: find player by id
* PUT: update player by id
* DELETE: delete player by id
*/
app.get('/api/players/:id', function(req,res) {
db.collection(PLAYERS_COLLECTION).findOne({ _id: new ObjectID(req.params.id) }, function(err, doc) {
if (err) {
handleError(res, err.message, 'Failed to get contact');
} else {
res.status(200).json(doc);
}
});
});
app.put('/api/players/:id', function(req, res) {
var updateDoc = req.body;
delete updateDoc._id;
db.collection(PLAYERS_COLLECTION).updateOne({_id: new ObjectID(req.params.id)}, updateDoc, function(err, doc) {
if (err) {
handleError(res, err.message, "Failed to update player");
} else {
updateDoc._id = req.params.id;
res.status(200).json(updateDoc);
}
});
});
app.delete('/api/players/:id', function(req, res) {
db.collection(PLAYERS_COLLECTION).deleteOne({ _id: new ObjectId(req.params.id) }, function(err, result) {
if (err) {
handleError(res, err.message, 'Failed to delete player');
} else {
res.status(200).json(req.params.id);
}
});
});