-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy path7-http_express.js
92 lines (82 loc) · 2.84 KB
/
7-http_express.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
81
82
83
84
85
86
87
88
89
90
91
92
const express = require('express');
const fs = require('fs');
const app = express();
const PORT = 1245;
const DB_FILE = process.argv.length > 2 ? process.argv[2] : '';
const countStudents = (dataPath) => new Promise((resolve, reject) => {
if (!dataPath) {
reject(new Error('Cannot load the database'));
}
if (dataPath) {
fs.readFile(dataPath, (err, data) => {
if (err) {
reject(new Error('Cannot load the database'));
}
if (data) {
const reportParts = [];
const fileLines = data.toString('utf-8').trim().split('\n');
const studentGroups = {};
const dbFieldNames = fileLines[0].split(',');
const studentPropNames = dbFieldNames.slice(
0,
dbFieldNames.length - 1,
);
for (const line of fileLines.slice(1)) {
const studentRecord = line.split(',');
const studentPropValues = studentRecord.slice(
0,
studentRecord.length - 1,
);
const field = studentRecord[studentRecord.length - 1];
if (!Object.keys(studentGroups).includes(field)) {
studentGroups[field] = [];
}
const studentEntries = studentPropNames.map((propName, idx) => [
propName,
studentPropValues[idx],
]);
studentGroups[field].push(Object.fromEntries(studentEntries));
}
const totalStudents = Object.values(studentGroups).reduce(
(pre, cur) => (pre || []).length + cur.length,
);
reportParts.push(`Number of students: ${totalStudents}`);
for (const [field, group] of Object.entries(studentGroups)) {
reportParts.push([
`Number of students in ${field}: ${group.length}.`,
'List:',
group.map((student) => student.firstname).join(', '),
].join(' '));
}
resolve(reportParts.join('\n'));
}
});
}
});
app.get('/', (_, res) => {
res.send('Hello Holberton School!');
});
app.get('/students', (_, res) => {
const responseParts = ['This is the list of our students'];
countStudents(DB_FILE)
.then((report) => {
responseParts.push(report);
const responseText = responseParts.join('\n');
res.setHeader('Content-Type', 'text/plain');
res.setHeader('Content-Length', responseText.length);
res.statusCode = 200;
res.write(Buffer.from(responseText));
})
.catch((err) => {
responseParts.push(err instanceof Error ? err.message : err.toString());
const responseText = responseParts.join('\n');
res.setHeader('Content-Type', 'text/plain');
res.setHeader('Content-Length', responseText.length);
res.statusCode = 200;
res.write(Buffer.from(responseText));
});
});
app.listen(PORT, () => {
console.log(`Server listening on PORT ${PORT}`);
});
module.exports = app;