forked from alexhstone/people-picker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
80 lines (66 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
import express from 'express';
import fs from 'fs';
const getAllPeople = () => {
return JSON.parse(fs.readFileSync('./database.json')).people;
}
const getPersonById = id => {
return getAllPeople().find(person => person.id === +id)
}
let chosenPeople = []
let unchosenPeople = [...getAllPeople()]
let pickedPeople = [];
/**
* Selects a random person from the unchosenPeople, removes them from
* unchosenPeople, and adds them to chosenPeople.
* @returns The current/chosen random person
*/
const getRandomPerson = () => {
if(unchosenPeople.length === 0) {
unchosenPeople = [...pickedPeople];
pickedPeople = [];
}
let currentPerson = unchosenPeople[Math.floor(Math.random() * unchosenPeople.length)];
unchosenPeople = unchosenPeople.filter(p => p !== currentPerson);
pickedPeople = [...pickedPeople, currentPerson];
chosenPeople = [...chosenPeople, currentPerson];
return currentPerson;
};
const port = 3001;
const app = express();
app.get('/people', (req, res) => {
res.send(getAllPeople())
})
app.get('/people/chosen', (req, res) => {
res.send(chosenPeople);
})
app.get('/people/unchosen', (req, res) => {
res.send(unchosenPeople);
})
/**
* Basically starts over.
* Resets chosenPeople to empty. Resets unchosenPeople to all people.
*/
app.post('/people/reset', (req, res) => {
chosenPeople = [];
unchosenPeople = [...getAllPeople()];
res.sendStatus(204); // No content.
})
/**
* Calls getRandomPerson(). Notice that it changes chosenPeople and unchosenPeople
*/
app.post('/people/getRandom', (req, res) => {
const currentPerson = getRandomPerson();
console.log(currentPerson)
res.send(currentPerson)
})
app.get('/people/:id', (req, res) => {
const { id } = req.params;
const person = getPersonById(id);
if (!person)
res.status(404).send(`Person ${id} was not found.`)
res.send(person);
})
app.use(express.static("./public"));
app.listen(port, () => {
console.log(`listening for HTTP requests on port ${port}`);
})