-
Notifications
You must be signed in to change notification settings - Fork 4
/
server.js
executable file
·296 lines (231 loc) · 9.83 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
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var ObjectId = require('mongoose').Types.ObjectId
var port = process.env.PORT || 8080; // set our port
var staticdir = process.env.NODE_ENV === 'production' ? 'dist.prod' : 'dist.dev'; // get static files dir
// get all data/stuff of the body (POST) parameters
app.use(bodyParser.json()); // parse application/json
//app.use(bodyParser.json({ type: 'application/vnd.api+json' })); // parse application/vnd.api+json as json
//app.use(bodyParser.urlencoded({ extended: true })); // parse application/x-www-form-urlencoded
app.use(methodOverride('X-HTTP-Method-Override')); // override with the X-HTTP-Method-Override header in the request. simulate DELETE/PUT
app.use(express.static(__dirname + '/' + staticdir)); // set the static files location /public/img will be /img for users
// models ==================================================
var Book = require('./devServer/models/book');
var User = require('./devServer/models/user');
var Activity = require('./devServer/models/activity');
// db ======================================================
var mongoose = require('mongoose');
mongoose.connect('mongodb://collaborativebookshelf:collaborativebookshelf@localhost:27017/collaborativebookshelf'); // connect to our database
// routes ==================================================
var router = express.Router(); // get an instance of the express Router
// middleware to use for all requests
router.use(function(req, res, next) {
// do logging
// console.log('Something is happening.');
next(); // make sure we go to the next routes and don't stop here
});
// test route to make sure everything is working (accessed at GET http://localhost:8080/api)
// router.get('/', function(req, res) {
// res.json({ message: 'hooray! welcome to our api!' });
// });
// on routes that end in /books
// ----------------------------------------------------
router.route('/books')
.get(function(req, res) {
if (req.query.borrowed_by) {
query = {'borrowed_by.google_id': req.query.borrowed_by}
} else if (req.query.recommended_by) {
query = {'recommended_by': { $elemMatch: { $eq: new ObjectId(req.query.recommended_by) } } }
} else if (req.query.voted_by) {
query = {'voted_by': { $elemMatch: { $eq: new ObjectId(req.query.voted_by) } } }
} else {
query = {'acquired': req.query.acquired}
}
Book
.find(query)
.populate('recommended_by')
.populate('voted_by')
.exec(function(err, books) {
if (err) { console.log(err); res.send(err); }
res.json(books);
});
})
.post(function(req, res) {
var book = new Book(req.body);
book.save(function(err) {
if (err) { console.log(err); res.send(err); }
res.json(book);
});
})
// on routes that end in /books/:book_id
// ----------------------------------------------------
router.route('/books/:book_id')
.get(function(req, res) {
Book
.findById(req.params.book_id)
.populate('recommended_by')
.populate('voted_by')
.exec(function(err, book) {
if (err) { console.log(err); res.send(err); }
res.json(book);
});
})
.put(function(req, res) {
console.log("Pushing book")
console.log(req.body)
Book.findById(req.params.book_id, function(err, book) {
if (err) { console.log(err); res.send(err); }
book.title = req.body.title;
book.subtitle = req.body.subtitle;
book.google_id = req.body.google_id;
book.goodreads_id = req.body.goodreads_id;
book.authors = req.body.authors;
book.publisher = req.body.publisher;
book.published_date = req.body.published_date;
book.description = req.body.description;
book.categories = req.body.categories;
book.thumbnail = req.body.thumbnail;
book.language = req.body.language;
book.borrowed_by = req.body.borrowed_by;
book.recommended_by = req.body.recommended_by;
book.voted_by = req.body.voted_by;
book.acquired = req.body.acquired;
book.comment = req.body.comment;
book.google_ratings_avg = req.body.google_ratings_avg;
book.google_ratings_count = req.body.google_ratings_count;
book.goodreads_ratings_avg = req.body.goodreads_ratings_avg;
book.goodreads_ratings_count = req.body.goodreads_ratings_count;
book.save(function(err) {
if (err) { console.log(err); res.send(err); }
Book
.findById(req.params.book_id)
.populate('recommended_by')
.populate('voted_by')
.exec(function(err, book) {
if (err) { console.log(err); res.send(err); }
res.json(book);
});
});
});
})
.delete(function(req, res) {
Book.remove({
_id: req.params.book_id
}, function(err, book) {
if (err) { console.log(err); res.send(err); }
res.json({ message: 'Successfully deleted' });
});
});
// on routes that end in /users
// ----------------------------------------------------
router.route('/users')
.get(function(req, res) {
User.find(function(err, users) {
if (err) { console.log(err); res.send(err); }
res.json(users);
});
})
.post(function(req, res) {
var user = new User(req.body);
user.save(function(err) {
if (err) { console.log(err); res.send(err); }
res.json(user);
});
})
// on routes that end in /users/:google_id
// ----------------------------------------------------
router.route('/users/:google_id')
// THIS SHOULD NOT HAVE TO EXIST
.post(function(req, res) {
var user = new User(req.body);
user.save(function(err) {
if (err) { console.log(err); res.send(err); }
res.json(user);
});
})
.get(function(req, res) {
User.findOne({ google_id : req.params.google_id }, function(err, user) {
if (err) { console.log(err); res.send(err); }
res.json(user);
});
})
.put(function(req, res) {
User.findOne({ google_id : req.params.google_id }, function(err, user) {
if (err) { console.log(err); res.send(err); }
user.name = req.body.name;
user.email = req.body.email;
user.picture = req.body.picture;
user.google_id = req.body.google_id;
user.save(function(err) {
if (err) {
console.log(err)
res.send(err);
}
res.json(user);
});
});
})
.delete(function(req, res) {
User.remove({
google_id : req.params.user_id
}, function(err, user) {
if (err) { console.log(err); res.send(err); }
res.json({ message: 'Successfully deleted' });
});
});
// on routes that end in /activities
// ----------------------------------------------------
router.route('/activities')
.get(function(req, res) {
Activity
.find()
.populate('book', '_id title thumbnail')
.exec(function(err, activities) {
if (err) { console.log(err); res.send(err); }
res.json(activities);
});
})
.post(function(req, res) {
var activity = new Activity(req.body);
activity.save(function(err) {
if (err) { console.log(err); res.send(err); }
res.json(activity);
});
})
// small web scraping to fetch goodreads data
// ----------------------------------------------------
router.route('/goodreads/:goodreads_id')
.get(function(req, res) {
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xmlhttp = new XMLHttpRequest();
var url = 'https://www.goodreads.com/book/show/' + req.params.goodreads_id;
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
response = {}
var ratings_avg_regex = /itemprop="ratingValue">(.*?)<\/span>/g
var ratings_count_regex = /itemprop="ratingCount">(.*?) Ratings<\/span>/g
if (ratings_avg_regex.test(xmlhttp.responseText) && ratings_count_regex.test(xmlhttp.responseText)) {
ratings_avg_regex.lastIndex = 0;
var match = ratings_avg_regex.exec(xmlhttp.responseText);
response.ratings_avg = match[1];
ratings_count_regex.lastIndex = 0;
var match = ratings_count_regex.exec(xmlhttp.responseText);
response.ratings_count = match[1].replace(",","")
} else {
response.error = 'Unable to retrieve rating information'
}
res.json(response)
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
})
// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
app.use('/api', router);
// start app ===============================================
app.listen(port); // startup our app at http://localhost:8080
console.log('Starting server on port ' + port); // shoutout to the user
exports = module.exports = app; // expose app