-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathserver.js
69 lines (54 loc) · 1.68 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
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors());
app.use(express.json());
app.locals.title = 'Math API';
app.locals.solutions = [];
app.set('port', 3001);
app.listen(app.get('port'), () => {
console.log(`${app.locals.title} is now running on ${app.get('port')}!`);
});
app.get('/solutions', (request, response) => {
response.status(200).json(app.locals.solutions);
});
app.post('/:operation', (request, response) => {
const operation = request.params.operation;
const numbers = request.body.numbers;
if (!numbers.length) {
return response.status(422).json({ message: `You did not send any numbers.`})
}
let nonnumbers = numbers.filter(number => {
return (typeof number !== 'number')
})
if (nonnumbers.length) {
return response.status(422).json({ message: `You submitted an invalid data type. Only send numbers.`})
}
let solution = numbers[0];
let equation = '';
numbers.forEach((number, index) => {
if (index === 0) {
equation += `${number}`
} else {
equation += ` / ${number}`
if (operation === 'add') {
solution += number
} else if (operation === 'subtract') {
solution -= number
} else if (operation === 'multiply') {
solution *= number
} else if (operation === 'divide') {
solution /= number
} else {
return response.status(404).json({ message: `That is a not a valid endpoint. Try '/add', '/subtract', '/multiply', or '/divide'.`})
}
}
})
const newSolution = {
id: Date.now(),
equation,
solution
}
app.locals.solutions.push(newSolution);
response.status(201).json(newSolution);
});