-
Notifications
You must be signed in to change notification settings - Fork 2
/
server.js
435 lines (344 loc) · 11.9 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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
"use strict";
//########################################
// DECLARE/REQUIRE
//########################################
require('dotenv').config();
const PORT = process.env.PORT || 8080;
const ENV = process.env.ENV || "development";
const express = require("express");
const bodyParser = require("body-parser");
const sass = require("node-sass-middleware");
const app = express();
const knexConfig = require("./knexfile");
const knex = require("knex")(knexConfig[ENV]);
const morgan = require('morgan');
const knexLogger = require('knex-logger');
const grabity = require("grabity");
const cookieParser = require('cookie-parser');
let kumquat = (async () => {
let tags = await grabity.grab("https://www.flickr.com");
return tags;
})
//########################################
// DATABASE ROUTES
// Separated Routes for each Resource
//########################################
const usersRoutes = require("./routes/users");
const resourcesRoutes = require("./routes/resources");
const commentsRoutes = require("./routes/comments");
const likesRoutes = require("./routes/likes");
const ratingsRoutes = require("./routes/ratings");
const urgencyRoutes = require("./routes/urgency");
const promotionRoutes = require("./routes/promotion");
const navigationRoutes = require("./routes/navigation");
//########################################
// RUN/USE MIDDLEWARE
//########################################
// Load the logger first so all (static) HTTP requests are logged to STDOUT
// 'dev' = Concise output colored by response status for development use.
// The :status token will be colored red for server error codes, yellow for client error codes, cyan for redirection codes, and uncolored for all other codes.
app.use(morgan('dev'));
// Log knex SQL queries to STDOUT as well
app.use(knexLogger(knex));
app.set("view engine", "ejs");
app.use(bodyParser.urlencoded({
extended: true
}));
app.use("/styles", sass({
src: __dirname + "/styles",
dest: __dirname + "/public/styles",
debug: true,
outputStyle: 'expanded'
}));
app.use(express.static("public"));
app.use(cookieParser());
// Mount all resource routes
app.use("/api/users", usersRoutes(knex));
app.use("/api/resources", resourcesRoutes(knex));
app.use("/api/comments", commentsRoutes(knex));
app.use("/api/likes", likesRoutes(knex));
app.use("/api/ratings", ratingsRoutes(knex));
app.use("/api/urgency", urgencyRoutes(knex));
app.use("/api/promotion", promotionRoutes(knex));
app.use("/api/navigation", navigationRoutes(knex));
/*function searchUsers(req, res) {
knex.select('*')
.from('users')
// .where('users', 'ILIKE', '%%')
.asCallback(function(err, rows) {
if (err) return console.error(err);
console.log(`Loading users into page..`);
// loadResults(rows);
console.log(rows);
let templatevars = {
results: rows
}
res.render("results", templatevars);
// knex.destroy(); // force closes the pooling
});
}*/
//########################################
// LOGIN INFORMATION
//########################################
// const loginInfo = require("./scripts/loginInfo");
var me = "Raymond";
var other_users = "";
//########################################
// LOAD PAGES
//########################################
// Log in
app.post("/login", (req, res) => {
console.log("req.body.username: " + req.body.username);
console.log("req.body.password: " + req.body.password);
var inputUsername = req.body.username;
var inputPassword = req.body.password;
knex('users').where('name', inputUsername)
.asCallback(function(err, rows) {
if (err) return console.error(err);
console.log(rows[0]);
// if (rows[0].password === inputPassword) {
// console.log('Welome back');
// me = rows[0].name;
// let templatevars = {
// userInfo: rows
// }
res.redirect("/");
// } else {
// console.log("Nothing will happen yet..")
// $error.text("Your username or password is incorrect.")
// $('#login-error').show()
// }
})
})
// // Search by user
// app.get("/search", (req, res) => {
// //searchUsers(req, res)
// console.log("You saw me.", req.query);
// knex.select('*')
// .from('users')
// // .where('users', 'ILIKE', '%%')
// .asCallback(function(err, rows) {
// if (err) return console.error(err);
// console.log(`Loading users into page..`);
// // loadResults(rows);
// console.log(rows);
// let templatevars = {
// results: rows
// }
// res.render("results", templatevars);
// });
// });
// Returns an array with a single object, being the resources table object from the database. Remember to access the result at [0]
const findResourceById = async function (resourceId) {
return await knex('resources').where('id', resourceId);
}
// Returns an array with a single object, being the users table object from the database. Remember to access the result at [0].
const findUserById = async function (userId) {
return await knex('users').where('id', userId);
}
// Returns an array of objects containing the resources associated with the passed userID. Iterate through the array to access them.
// const findResourcesByUser = async function (userId) {
// return await knex.select("*").from("resources").join("users", "users.id", "=", "resources.user_id").where('users.id', userId);
// }
// // Returns an array of objects containing the resources associated with the passed userID. Iterate through the array to access them.
// const findUserByResource = async function (resourceId) {
// return await knex.raw(`SELECT users.name, users.id FROM users JOIN resources ON resources.user_id=users.id WHERE resources.id = ${resourceId}`);
// // return await knex.select("name").from("users").join("resources", "users.id", "=", "resources.user_id").where('resources.user_id', resourceId);
// }
const handleResourceWithMeta = function(resourceId, cb) {
return knex.raw(`select * from resources join users on resources.user_id = users.id where resources.id = ${resourceId} ORDER BY date_created DESC`).asCallback(function(err, rows) {
if (err) return console.error(err);
cb(rows.rows);
});
}
const handleResourcesWithMeta = function(tags, cb) {
return knex.raw(`select * from resources join users on resources.user_id = users.id where tags ilike '%${tags}%' ORDER BY date_created DESC`).asCallback(function(err, rows) {
if (err) return console.error(err);
cb(rows.rows);
});
}
const getResourcesByUser = function(userId, cb) {
return knex.raw(`select * from resources join users on resources.user_id = users.id where users.id = '${userId}' ORDER BY date_created DESC`).asCallback(function(err, rows) {
if (err) return console.error(err);
cb(rows.rows);
});
}
// const getResourceWithAllAssociatedMeta = async function (resourceid) {
// let userName = await findUserByResource(resourceid);
// let resourceRecord = await findResourceById(resourceid);
// return new Promise(function(resolve, reject) {
// resolve({
// user: userName.rows[0],
// kumquat: resourceRecord[0]
// });
// });
// }
// Discover page
app.get("/discover", (req, res) => {
// showAllResourcesWithMeta
return knex.raw(`select * from resources join users on resources.user_id = users.id order by date_created desc`)
.asCallback(function(err, rows) {
if (err) return console.error(err);
console.log("data: ", rows.rows);
let templatevars = {
allResources: rows.rows
}
res.render("discover", templatevars);
});
});
// Search by TAG
app.get("/search", (req, res) => {
handleResourcesWithMeta(req.query['search_tags'], function(rows) {
let templatevars = {
data: rows,
hits: rows.length,
searchTopic: req.query['search_tags']
};
res.render("results", templatevars);
});
});
// Home page
app.get("/", (req, res) => {
getResourcesByUser(5, function(rows) {
let templatevars = {
data: rows
};
res.render("index", templatevars);
});
});
// Login page
app.get("/login", (req, res) => {
res.render("login");
});
//Templating page
app.get("/temp", (req, res) => {
res.render("templating");
});
// Results page
app.get("/results", (req, res) => {});
// Registration page
app.get("/register", (req, res) => {
res.render("register");
});
// Load Edit Profile Page
app.get("/edit", (req, res) => {
knex('users').where('name', me)
.asCallback(function(err, rows) {
if (err) return console.error(err);
let templatevars = {
userInfo: rows[0]
}
res.render("edit_user_profile", templatevars);
});
})
// Edit Profile
app.post("/edit", (req, res) => {
console.log(req.body.name)
console.log(req.body.email)
console.log(req.body.password)
console.log(req.body.avatar)
console.log(req.body.bio)
knex('users').where('name', req.body.username)
.update({
name: req.body.name,
email: req.body.email,
password: req.body.password,
avatar_url: req.body.avatar,
bio: req.body.bio
})
knex('users').where('name', req.body.username)
.asCallback(function(err, rows) {
if (err) return console.error(err);
console.log("This is the updated info:");
console.log(rows[0]);
let templatevars = {
userInfo: rows[0]
}
res.redirect("index", templatevars);
});
})
// Individual resource page
// app.get("/resource/:resourceid", async (req, res) => {
// let userName = await findUserByResource(req.params.resourceid);
// let resourceRecord = await findResourceById(req.params.resourceid);
// console.log("userName", userName);
// console.log("resourceRecord", resourceRecord[0]);
// let resourcePicture = await grabity.grab(resourceRecord[0].url);
// let templatevars = {
// picture: resourcePicture["og:image"],
// user: userName.rows[0],
// kumquat: resourceRecord[0]
// }
// console.log("templatevars is:", templatevars);
// res.render("view_resource", templatevars);
// })
app.get("/resource/:resourceid", async (req, res) => {
handleResourceWithMeta(req.params.resourceid, function(rows) {
let templatevars = {
kumquat: rows[0]
}
res.render("view_resource", templatevars);
})
// let templatevars = await getResourceWithAllAssociatedMeta(req.params.resourceid);
// res.render("view_resource", templatevars);
})
// Testing Porp: User by ID
app.get("/user/:userId", async (req, res) => {
getResourcesByUser(req.params.userId, function(rows) {
let templatevars = {
data: rows
};
res.render("other_user_profile", templatevars);
});
});
// Add new resource
// app.get("/users/:id/new", (req, res) => {
// res.render("new_resource");
// });
app.get("/new_resource", async (req, res) => {
// Testing grabity on page
// let kumquat = await grabity.grab("https://www.flickr.com");
// let templatevars = {kumquat:kumquat}
res.render("new_resource");
/*(async () => {
let it = await grabity.grabIt("https://www.flickr.com");
console.log(it);
})();*/
});
app.post("/new_resource", async (req,res) => {
let currentDate = new Date();
let kumquat = await grabity.grab(req.body['url']);
let pictureURL = kumquat["og:image"];
knex("resources")
.insert({
title: req.body['title'],
url: req.body['url'],
description: req.body['description'],
date_created: currentDate,
tags: req.body['tags'],
picture_url: pictureURL,
rating: req.body['rating'],
user_id: 5
})
.then((rows) => {
console.log(rows)
})
.catch(function(err) {
console.error(err);
})
res.redirect("/");
})
// Other user's Profile
app.get("/users/:id/", (req, res) => {
res.render("other_user_profile");
});
// // User Profile page
// app.get("/:id", (req, res) => {
// res.render("/:id");
// });
//########################################
// LISTEN PORT
//########################################
app.listen(PORT, () => {
console.log("Kumquat app listening on port " + PORT);
});