|
1 | 1 | const http = require('http');
|
2 |
| -const Party = require('./models/party'); |
3 | 2 |
|
4 |
| -function bodyMiddleware(req, res, next) { |
5 |
| - if (['GET', 'HEAD', 'DELETE', 'OPTIONS'].includes(req.method)) { |
6 |
| - return next(req, res); |
7 |
| - } |
| 3 | +const PartyController = require('./controllers/party'); |
| 4 | +const bodyMiddleware = require('./middlewares/body'); |
| 5 | +const errorMiddleware = require('./middlewares/error'); |
| 6 | +const notFoundMiddleware = require('./middlewares/notFound'); |
8 | 7 |
|
9 |
| - let data = ''; |
10 |
| - |
11 |
| - req.on('data', (chunk) => data += chunk); |
12 |
| - req.on('end', () => { |
13 |
| - try { |
14 |
| - data = JSON.parse(data); |
15 |
| - } catch { |
16 |
| - res.statusCode = 400 |
17 |
| - return res.end('JSON body is invalid'); |
18 |
| - } |
19 |
| - |
20 |
| - req.body = data; |
21 |
| - |
22 |
| - next(req, res); |
23 |
| - }) |
24 |
| -} |
25 |
| - |
26 |
| -function errorMiddleware(req, res, next) { |
27 |
| - try { |
28 |
| - next(req, res); |
29 |
| - } catch (err) { |
30 |
| - res.statusCode = 500; |
31 |
| - res.end(err.message); |
32 |
| - } |
33 |
| -} |
34 | 8 |
|
35 | 9 | function handleRequest(req, res) {
|
36 |
| - bodyMiddleware(req, res, (req, res) => errorMiddleware(req, res, handleRouting)); |
37 |
| -} |
38 |
| - |
39 |
| -function handleRouting(req, res) { |
40 |
| - if (req.method === 'POST' && req.url === '/party') { |
41 |
| - Party.currentParty = new Party(req.body.min || 0, req.body.max || 100); |
42 |
| - res.statusCode = 204; |
43 |
| - } else if (req.method === 'PUT' && req.url === '/party/current') { |
44 |
| - if (!Party.currentParty) { |
45 |
| - throw new Error('No party'); |
46 |
| - } |
47 |
| - |
48 |
| - const result = Party.currentParty.guess(req.body); |
49 |
| - if (result === '=') { |
50 |
| - res.write(`Félicitation, le chiffre était ${Party.currentParty.number}`); |
51 |
| - } else { |
52 |
| - res.write(result); // + or - |
53 |
| - } |
54 |
| - res.statusCode = 200; |
55 |
| - } else if (req.method === 'GET' && req.url === '/party/current') { |
56 |
| - if (!Party.currentParty) { |
57 |
| - throw new Error('No party'); |
58 |
| - } |
59 |
| - |
60 |
| - res.statusCode = 200; |
61 |
| - res.write(Party.currentParty.guesses.join(', ')); |
62 |
| - } else { |
63 |
| - res.statusCode = 404; |
64 |
| - } |
65 |
| - |
66 |
| - res.end(); |
| 10 | + const middlewares = [ |
| 11 | + bodyMiddleware, |
| 12 | + errorMiddleware, |
| 13 | + PartyController.middleware, |
| 14 | + notFoundMiddleware, |
| 15 | + ] |
| 16 | + |
| 17 | + // @todo apply middleware one after the other |
| 18 | + // remplacer la ligne suivante, par quelque chose de dynamique |
| 19 | + // bodyMiddleware(req, res, (req, res) => errorMiddleware(req, res, handleRouting)); |
67 | 20 | }
|
68 | 21 |
|
69 | 22 |
|
|
0 commit comments