1
+ const http = require ( 'http' ) ;
2
+ const Party = require ( './models/party' ) ;
3
+
4
+ function bodyMiddleware ( req , res , next ) {
5
+ if ( [ 'GET' , 'HEAD' , 'DELETE' , 'OPTIONS' ] . includes ( req . method ) ) {
6
+ return next ( req , res ) ;
7
+ }
8
+
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
+
35
+ 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 ( ) ;
67
+ }
68
+
69
+
70
+ const server = http . createServer ( handleRequest ) ;
71
+ server . listen ( 8085 ) ;
0 commit comments