-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackend.js
More file actions
82 lines (77 loc) · 2.45 KB
/
backend.js
File metadata and controls
82 lines (77 loc) · 2.45 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
var bodyParser = require('body-parser')
var cors = require('cors')
var express = require('express')
var _ = require('lodash')
var sqlite = require('sqlite3')
var db = new sqlite.Database('hof.db')
db.run(`
CREATE TABLE IF NOT EXISTS
RoguelikeHof (
Player TEXT,
Score INTEGER,
Date DATE,
DungeonLevel INTEGER,
CauseOfDeath TEXT,
Version TEXT
)`)
var app = express()
app.use(cors())
app.use(bodyParser.json())
function validateBody(body) {
// TODO
var okPlayer = _.isString(body.player) && body.player.length > 0 && body.player.length <= 8
var okScore = _.isInteger(body.score) && body.score >= 0 && body.score < 1e6
var okDate = _.isString(body.date) && body.date.length == 10 && !_.isNaN(Date.parse(body.date))
var okLevel = _.isInteger(body.dungeonLevel) && body.dungeonLevel >= 0 && body.dungeonLevel < 1e6
var okCause = _.isString(body.causeOfDeath) && body.causeOfDeath.length < 50
var okVersion = _.isString(body.version) && body.version.match(/\d+\.\d+\.\d+/)
return okPlayer && okScore && okDate && okLevel && okCause && okVersion
}
app.post('/roguelike/hof', (req, res) => {
if (validateBody(req.body)) {
console.log(req.body)
db.get('SELECT COUNT(*) AS Ranking FROM RoguelikeHof WHERE Version = ? AND Score >= ?', [req.body.version, req.body.score], (err, row) => {
if (err) {
console.log(err)
res.sendStatus(500)
} else {
var ranking = row.Ranking
console.log('ranking: ' + JSON.stringify(row))
db.run(`
INSERT INTO
RoguelikeHof
(Player, Score, Date, DungeonLevel, CauseOfDeath, Version)
VALUES (?, ?, ?, ?, ?, ?)`, [
req.body.player,
req.body.score,
req.body.date,
req.body.dungeonLevel,
req.body.causeOfDeath,
req.body.version
], (err) => {
if (err) {
console.log(err)
res.sendStatus(500)
} else {
db.all('SELECT * FROM RoguelikeHof WHERE Version = ? ORDER BY Score DESC LIMIT 8', [req.body.version], (err, rows) => {
if (err) {
console.log(err)
res.sendStatus(500)
} else {
res.json({
ranking,
hof: rows
})
}
})
}
})
}
})
} else {
res.sendStatus(400)
}
})
app.listen(3001, () => {
console.log('app listening')
})