-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
203 lines (175 loc) · 6.29 KB
/
index.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
if (process.env.NODE_ENV !== "production") {
require('dotenv').config();
}
const express = require('express');
const app = express();
const path = require('path');
const port = process.env.PORT || 80;
const localIPAddress = "192.168.121.21";
const mongoose = require('mongoose');
const methodOverride = require('method-override');
// const activeDB = "Quote";
const Quote = require(`./models/SSCQuotesModel`);
const mongoString = process.env.MONGODB_ATLAS_KEY;
mongoose.connect(mongoString, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => {
console.log("MONGO CONNECTION OPEN!!!")
})
.catch(err => {
console.log("OH NO MONGO CONNECTION ERROR!!!!")
console.log(err)
})
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(express.urlencoded({ extended: true }));
app.use(methodOverride('_method'));
app.use(express.static(path.join(__dirname, 'public')));
const authors = [];
// app.use('/', (req, res) => {
// const authors = updateAuthors();
// });
async function updateAuthors() {
const authorQuery = await Quote.find({}, { _id: 0, author: 1 });
// console.log("===== authorQuery: ======")
// console.log(authorQuery)
const authors = [];
for (let authorObj of authorQuery) {
// console.log("===== authors: ======")
// console.log(authors)
// console.log("===== authorObj: ======")
// console.log(authorObj)
if (!authors.includes(authorObj.author[0])) {
authors.push(authorObj.author[0])
}
}
// console.log(authors);
return authors;
}
app.get('/', async (req, res) => {
const quotes = await Quote.find({})
const authors = await updateAuthors();
const pageTitle = "QuoteIt! Homepage";
res.render('quotes/index', { pageTitle, quotes, authors })
})
app.get('/about', (req, res) => {
const pageTitle = "About";
res.render('about/about', { pageTitle, authors })
})
app.get('/quotes', async (req, res) => {
const authors = await updateAuthors();
const { author, tags } = req.query;
const pageTitle = "View Quotes";
if (author) {
const quotes = await Quote.find({ author })
res.render('quotes/quotes', { pageTitle, quotes, authors, author, tags: "" })
} else if (tags) {
const quotes = await Quote.find({ tags })
res.render('quotes/quotes', { pageTitle, quotes, authors, author: "", tags })
} else {
const quotes = await Quote.find({})
res.render('quotes/quotes', { pageTitle, quotes, authors, author: 'Everyone' })
}
})
app.get('/api/random', async (req, res) => {
const authors = await updateAuthors();
const { author, tags } = req.query;
const quotes = await Quote.find({})
let quoteObject = quotes[Math.floor(Math.random() * quotes.length)];
const newQuoteObject = {
quoteString: `${quoteObject.quote} - ${quoteObject.author}`,
originalQuoteObject: quoteObject
}
res.send(newQuoteObject)
})
app.get('/api/:num', async (req, res) => {
const num = req.params.num;
const authors = await updateAuthors();
const { author, tags } = req.query;
const quotes = await Quote.find({})
const manyQuotes = []
while (manyQuotes.length < num) {
let quoteObject = quotes[Math.floor(Math.random() * quotes.length)];
console.log(manyQuotes)
manyQuotes.push({
quote: `${quoteObject.quote} - ${quoteObject.author}`
})
}
res.send(manyQuotes)
})
app.get('/quotes/new', async (req, res) => {
const authors = await updateAuthors();
const pageTitle = "New Quote";
res.render('quotes/new', { pageTitle, authors })
})
app.get('/quotes/search', async (req, res) => {
const authors = await updateAuthors();
const pageTitle = "New Quote";
res.render('quotes/search', { pageTitle, authors })
})
app.post('/quotes', async (req, res) => {
// console.log("Post request received")
const authors = await updateAuthors();
responseBody = req.body;
// Handle Multiple Tags (Comma Separated)
responseBody.tags = responseBody.tags.split(',');
for (let i = 0; i < responseBody.tags.length; i++) {
responseBody.tags[i] = responseBody.tags[i].trim();
}
// Handle Multiple Authors (Comma Separated)
responseBody.author = responseBody.author.split(',');
for (let i = 0; i < responseBody.author.length; i++) {
responseBody.author[i] = responseBody.author[i].trim();
}
// Handle date
if (req.body.date === "") {
let now = new Date();
req.body.date = `${now.getDate()
}/${now.getMonth() + 1}/${now.getFullYear()}`;
}
if (req.body.date.toLowerCase() === "today") {
let now = new Date();
req.body.date = `${now.getDate()} / ${now.getMonth() + 1} / ${now.getFullYear()}`;
}
const newQuote = new Quote(responseBody);
await newQuote.save();
// console.log(newQuote._id)
res.redirect(`/ quotes / ${newQuote._id}`)
})
app.get('/quotes/:id', async (req, res) => {
const authors = await updateAuthors();
const { id } = req.params;
const quote = await Quote.findById(id)
if (quote.author.length === 1) {
tempAuthor = quote.author;
} else {
tempAuthor = quote.author.join(", ");
}
const pageTitle = `Quote by ${tempAuthor}`;
res.render('quotes/show', { pageTitle, quote, authors })
})
app.get('/quotes/:id/edit', async (req, res) => {
const pageTitle = "Edit Quote";
const authors = await updateAuthors();
const { id } = req.params;
const quote = await Quote.findById(id);
res.render('quotes/edit', { pageTitle, quote, authors })
})
app.put('/quotes/:id', async (req, res) => {
if (req.body.author === "New Author") {
req.body.author = req.body.newAuthor;
delete req.body.newAuthor;
} else {
delete req.body.newAuthor;
}
const { id } = req.params;
const quote = await Quote.findByIdAndUpdate(id, req.body, { runValidators: true, new: true });
res.redirect(`/ quotes / ${quote._id}`);
})
app.delete('/quotes/:id', async (req, res) => {
const { id } = req.params;
const deletedQuote = await Quote.findByIdAndDelete(id);
res.redirect('/quotes');
})
app.listen(port, () => {
console.log(`App is listening on Localhost and IP Address ${localIPAddress}, on port ${port}.`)
})