forked from cs4241-21a/a2-shortstack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.improved.js
More file actions
131 lines (108 loc) · 3.73 KB
/
Copy pathserver.improved.js
File metadata and controls
131 lines (108 loc) · 3.73 KB
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
const http = require('http');
const fs = require('fs');
// IMPORTANT: you must run `npm install` in the directory for this assignment
// to install the mime library used in the following line of code
const mime = require('mime');
const dir = 'public/';
const port = 3000;
// data is a slightly modified version of what is at https://surlalunefairytales.com/annotated-a-g.html
// the annotation numbers were removed, but everything else was retained
// files were run through the form handler to create these json files
const startingDataFileNames = ["emperor's new clothes.json", "cinderella.json", "golden goose.json"];
const appdata = startingDataFileNames.map((filename) => JSON.parse(fs.readFileSync(filename)));
const server = http.createServer(function(request, response) {
if (request.method === 'GET') {
handleGet(request, response)
} else if (request.method === 'POST') {
handlePost(request, response)
}
})
const handleGet = function(request, response) {
const filename = dir + request.url.slice(1)
if (request.url === '/data') {
response.writeHeader(200, { 'Content-Type': 'application/json' });
response.end(JSON.stringify(appdata));
} else if (request.url === '/') {
sendFile(response, 'public/index.html');
} else {
sendFile(response, filename);
}
}
// a word has some number of letter or number characters, and apostrophes and hypens
// this ends up matching "--", but fixing it would make the regex pretty unplesant so I didn't
const WORD = RegExp(/[’'-\w]+/, 'g');
const getWords = (text) => {
let matchedWords = text.matchAll(WORD);
let matches = [];
for (let match of matchedWords) {
matches.push([match[0].toLowerCase(), match.index]);
}
let words = {};
matches.forEach((elm) => {
if (words[elm[0]]) {
words[elm[0]].positions.push(elm[1]);
} else {
words[elm[0]] = { 'positions': [elm[1]] };
}
});
return words;
}
const addDataToDB = (data) => {
const title = data.title;
let index = 0;
for (let entry of appdata) {
if (entry.title === title) {
appdata[index] = data;
return;
}
index++;
}
appdata.push(data);
}
const removeFromDB = (title) => {
let index = 0;
for (let entry of appdata) {
if (entry.title === title) {
appdata.splice(index, 1);
return;
}
index++;
}
}
const handlePost = function(request, response) {
let dataString = '';
request.on('data', function(data) {
dataString += data;
});
request.on('end', function() {
const parsed = JSON.parse(dataString);
const title = parsed.title;
const text = parsed.text;
const action = parsed.action;
if (action === "delete") {
removeFromDB(title);
} else {
const words = getWords(title + ' ' + text);
const data = { title, text, words };
addDataToDB(data);
}
response.writeHead(200, "OK", { 'Content-Type': 'application/json' });
response.end(JSON.stringify(appdata));
})
}
const sendFile = function(response, filename) {
const type = mime.getType(filename)
fs.readFile(filename, function(err, content) {
// if the error = null, then we've loaded the file successfully
if (err === null) {
// status code: https://httpstatuses.com
response.writeHeader(200, { 'Content-Type': type })
response.end(content)
} else {
// file not found, error code 404
response.writeHeader(404)
response.end('404 Error: File Not Found')
}
})
}
server.listen(process.env.PORT || port)