Skip to content

Commit 4456c8d

Browse files
committed
first step
0 parents  commit 4456c8d

File tree

2 files changed

+104
-0
lines changed

2 files changed

+104
-0
lines changed

main.js

+71
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
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);

models/party.js

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
class Party {
2+
number = null;
3+
guesses = [];
4+
score = null;
5+
solved = false;
6+
tries = 0;
7+
8+
static currentParty = null;
9+
10+
constructor(min, max) {
11+
this.number = Math.floor(Math.random() * (max - min) + min);
12+
}
13+
14+
guess(input) {
15+
const inputNb = +input;
16+
if (isNaN(inputNb)) {
17+
throw new Error('Input is not a number')
18+
}
19+
20+
this.tries++;
21+
this.guesses.push(input);
22+
23+
if (inputNb > this.number) return '-';
24+
if (inputNb < this.number) return '+';
25+
26+
this.solved = true;
27+
this.score = this.tries;
28+
29+
return '=';
30+
}
31+
}
32+
33+
module.exports = Party;

0 commit comments

Comments
 (0)