/
server.js
89 lines (69 loc) · 1.95 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
'use strict'
const http = require('http')
const express = require('express')
const chalk = require('chalk')
const config = require('config')
const bodyParser = require('body-parser')
const websocket = require('./lib/websocket')
// Initialize services
const app = express()
const server = http.createServer(app)
websocket(server)
// Export app
module.exports = app
// Disable X-Powered-By header
app.set('x-powered-by', false)
/*
bodyParser.json() =~= function (req, res, next) {
if (req.method === 'POST' && req.headers['content-type'] === 'application/json') {
req.on('data') → bufferiser
req.on('end') → parser + req.body = résultat du parsing + next()
} else {
next()
}
}
*/
app.use(bodyParser.json())
app.use(express.static('public'))
/*
function restricted (role) {
return function (req, res, next) {
if (!utilisateurARole(role)) {
res.status(403).end()
} else {
next()
}
}
}
*/
// Routing
// app.méthode(url, handler)
app.get('/', /*restricted('admin'),*/ (req, res) => {
res.send({ hello: 'world' })
})
app.get('/param/:variable([0-9]+)', (req, res) => {
res.send({ variable: req.params.variable })
})
app.get('/query', (req, res) => {
res.send({ variable: req.query.variable })
})
/*
Alternative : HAPI
app.get('/items', (req, res) => getFromDB().then(collection => res.render(collection)))
app.get('/items/:id', getItem)
app.post('/items', createItem)
app.put('/items/:id', updateItem)
app.delete('/items/:id', deleteItem)
*/
// Replaced by WS API
// app.get('/next-question', questions.next)
// app.post('/answer-question', questions.answer)
if (!module.parent) {
server.listen(config.server.port, () => {
console.log(chalk.green(`Server ready http://localhost:${server.address().port}`)) // eslint-disable-line
})
}
server.on('error', e => {
console.error(chalk.bold.red(`Failed to listen (error: ${e.message})`)) // eslint-disable-line
process.exit(1) // eslint-disable-line
})