-
Notifications
You must be signed in to change notification settings - Fork 2
/
server.js
70 lines (59 loc) · 1.73 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
"use strict";
var mongoose = require('mongoose'),
express = require('express'),
app = express();
mongoose.connect('mongodb://localhost/highscores');
var GameEntrySchema = new mongoose.Schema({
gameId: { type: String, required: true },
player: { type: String, required: true },
score: { type: Number, required: true },
scope: String,
createdAt: { type: Date, 'default': Date.now }
});
var GameEntry = mongoose.model('GameEntry', GameEntrySchema);
function getList(gameId, options, cb) {
options = options || {};
var query = GameEntry.find({ gameId: gameId }, null, {})
.lean()
.sort({ score: options.order || -1 })
.limit(options.limit || 10);
if (options.scope) {
query.where('scope', options.scope );
}
query.exec(cb);
}
function addToList(gameId, attributes, cb) {
var item = new GameEntry(attributes);
item.set('gameId', gameId);
item.save(cb);
}
app.use(express.bodyParser());
app.use(express.methodOverride());
app.get('/:gameId', function(req, res) {
var options = {
order: req.query.reverse ? -1 : 1,
limit: req.query.limit || 10,
scope: req.query.scope || null
};
getList(req.params.gameId, options, function(err, items) {
res.type('application/json');
if (err) {
res.jsonp(400, { error: err.message });
} else {
res.jsonp({ items: items });
}
});
});
app.post('/:gameId', function(req, res) {
addToList(req.params.gameId, req.body, function(err) {
res.header('Access-Control-Allow-Origin', '*');
res.type('application/json');
if (err) {
res.send(500, { error: err.message || 'Undefined error' });
} else {
res.send({ success: true });
}
});
});
app.listen(8181);
console.log("Started server at 172.0.0.1:8181");