-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.js
265 lines (247 loc) · 6.38 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
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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
"use strict";
// Imports
const fs = require('fs');
const http = require('http');
const mongodb = require('mongodb');
const url = require('url');
const path = require('path');
// Where we will store our connection to MongoDB
let db, recipes;
// Load the templates
const templates = {};
['index', '404'].forEach(name => {
// We are turning the html files into a str we can eval as a template
let tmplstr = '`' + fs.readFileSync(`templates/${name}.html`).toString() + '`';
templates[name] = tmplstr;
});
// Setup the tables
const tables = {};
// Store any session information in the form:
// (session key): {session data}
const sessions = {};
// Port to listen on
const PORT = process.env.port || 80;
// Handle displaying common errors.
function errorDocument(response, error) {
switch (error) {
case 404:
default:
response.writeHead(404, "Not Found", {});
response.end(
eval(templates['404'])
);
}
}
function indexDocument(response){
recipes.find({}, (error, cursor) => {
if (error){
console.error(new Error(error));
}
cursor.toArray((error, recipes) => {
if (error) {
console.error(new Error(error));
}
// template index uses: recipes
response.writeHead(200, 'All good', {});
response.end(
eval(templates['index'])
);
});
})
}
// function recipeAddDocument(response, error = false ){
// response.writeHead(200, 'All good', {});
// response.end(
// eval(templates['add-recipe'])
// );
// }
// function recipeDisplayDocument(response, id){
// recipesCollection.find({'id': id}, (error, cursor) => {
// cursor.forEach((recipe) => {
// response.writeHead(200, 'All good', {});
// response.end(
// eval(templates['recipe-display'])
// );
// })
// });
// }
// Helper to read a stream into a string
function stream2str(stream, callback) {
let str = "";
stream.on('data', (chunk) => {
str += chunk;
});
stream.on('end', () => {
callback(str);
});
}
// Function to get HTTP POST data out of a request
function getPostData(req, callback) {
stream2str(req, str => {
let entries = str.split('&');
let data = {};
entries.forEach(entry => {
let [key, value] = entry.split('=');
key = decodeURIComponent(key);
value = decodeURIComponent(value);
data[key] = value;
});
callback(data);
});
}
// This is a bit like Express routing, except that it has no dependencies.
// The order here matters.
let patterns = [
{
// Static Files
methods: ["get"],
regex: [
/(\/static\/)(.+)*/,
/(\/js\/)(.+)*/,
/(\/css\/)(.+)*/,
],
handler: function(req, res, params) {
let [match, folder, file] = params;
// path.normalize will hopefully make it so that people can't request files outside of the static directories.
let fileAbsolute = process.cwd() + path.normalize(folder + file);
if (fs.existsSync(fileAbsolute)) {
let fileHandle = fs.createReadStream(fileAbsolute);
fileHandle.on('open', () => {
fileHandle.pipe(res);
});
} else {
errorDocument(res, 404);
}
}
},
// {
// // Add recipe page
// methods: ["get"],
// regex: [
// /\/recipes\/add\//
// ],
// handler: function(req, res, params) {
// recipeAddDocument(res);
// }
// },
{
// Recipe pages
methods: ["get"],
regex: [
/\/recipes\//
],
handler: function(req, res, params) {
let [match, id] = params;
indexDocument(res);
}
},
{
// Rest Api endpoint
methods: ["get", "post", "put", "delete"],
regex: [
/\/api\/recipes\//
],
handler: function(req, res, params) {
// Decrease the number of toLowerCase() statements
req.method = req.method.toLowerCase();
if (req.method == "get") {
// This would be if I was requesting recipes over ajax later on.
// recipesCollection.find({'id': data.id}, (error, cursor) => {
// cursor.forEach(document => {
// res.writeHead(200, "Successfully returning recipe", {});
// res.end(JSON.stringify(document));
// })
// });
} else if (req.method == "post") {
stream2str(req, (str) => {
let data = JSON.parse(str);
data._id = mongodb.ObjectId();
recipes.insert(data);
res.writeHead(200, "Inserted Successfully", {});
res.end(JSON.stringify(data));
});
} else if (req.method == "put") {
stream2str(req, (str) => {
let data = JSON.parse(str);
data._id = mongodb.ObjectId(data._id);
recipes.update({'_id': data._id}, data).then(result => {
res.writeHead(200, "Updated Successfully", {});
res.end(str);
});
});
} else { // Method = delete
stream2str(req, (str) => {
let data = JSON.parse(str);
recipes.remove({"_id": mongodb.ObjectId(data._id)}).then(results => {
res.writeHead(200, "ok", {});
res.end("{}");
});
});
}
}
},
{
// Main Application Page
methods: ["get"],
regex: [
/\//
],
handler: function(req, res, params) {
indexDocument(res);
}
}
];
// Create our server.
let server = new http.Server();
server.on('request', (req, res) => {
let reqUrl = url.parse(req.url);
console.log(`New Request for ${req.url}`);
for (let endpoint of patterns) {
// skip if the method isn't correct
if (endpoint.methods && !endpoint.methods.some(method => {
return method.toLowerCase() == req.method.toLowerCase();
})) {
continue;
}
let params = false;
for (let expr of endpoint.regex) {
if ((params = expr.exec(reqUrl.pathname))) {
console.log(` - Using ${expr} to handle it.`);
break;
}
}
if (params) {
endpoint.handler(req, res, params);
return;
}
}
// If no handler is found, then we will use our default
console.error(`Url ${req.url} and method ${req.method} doesn't have a route handler`);
errorDocument(res, 404);
});
// Connect to the database and start the server
// Database information
const DB_USERNAME = "cs290_casters",
DB_USERPASS = "dZDPDyDZcNpzcDh",
DB_HOST = "classmongo.engr.oregonstate.edu",
DB_PORT = 27017,
DB_NAME = "cs290_casters";
// const DB_USERNAME = false,
// DB_HOST = "localhost",
// DB_PORT = 27017,
// DB_NAME = "cs290fp";
const mongoUrl = `mongodb://${DB_USERNAME ?
`${DB_USERNAME}:${DB_USERPASS}@` : ''
}${DB_HOST}:${DB_PORT}/${DB_NAME}`;
mongodb.MongoClient.connect(mongoUrl, (err, mongoDb) => {
if (err){
console.error(`Unable to connect to the database because ${err}`);
return;
} else {
console.log(`Connected to the database`);
}
db = mongoDb;
recipes = db.collection('recipes');
server.listen(PORT);
console.log(`Server listening on ${PORT}`);
});