-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
330 lines (300 loc) · 6.79 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
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
require('dotenv').config();
const express = require('express');
const app = express();
const cors = require('cors');
const bodyParser = require('body-parser');
var _ = require('lodash');
const jwt = require('jsonwebtoken');
const multer = require('multer');
const storage = multer.memoryStorage();
const upload = multer({ storage: storage });
const db = require('./models');
const errorHandler = require('./handlers/error');
const authRoutes = require('./routes/auth');
const postsRoutes = require('./routes/posts');
const commentsRoutes = require('./routes/comments');
const friendsRoutes = require('./routes/friends');
const {
loginRequired,
ensureCorrectUser
} = require('./middleware/auth');
const { getFriends } = require('./middleware/friends');
const PORT = process.env.PORT || 5051;
app.use(cors());
app.use(bodyParser.json());
app.use('/api/auth', authRoutes);
// GET user data again if signed in
app.get(
'/api/user/:id',
loginRequired,
ensureCorrectUser,
async function(req, res, next) {
try {
let user = await db.User
.findById(req.params.id)
.populate('requests', {
username : true,
id : true
});
const pickedUser = _.pick(user, [
'username',
'email',
'id',
'friends',
'posts',
'requests',
'profileImage'
]);
let {
id,
username,
profileImage,
friends,
posts,
requests
} = pickedUser;
let token = jwt.sign(
{
id,
username,
// profileImage,
friends,
posts,
requests
},
process.env.SECRET_KEY
);
pickedUser.token = token;
console.log(
'--->> GET /user/:id route:',
req.params,
user,
pickedUser
);
return res.status(200).json(pickedUser);
} catch (err) {
return next({
status : 401,
message : 'Please log in first'
});
}
}
);
// POST route for uploading profileImage
app.post(
'/api/users/:id/profile/avi',
loginRequired,
ensureCorrectUser,
upload.single('profileImage'),
async function(req, res, next) {
console.log(
'POST /api/users/:id/profile/avi, req.params:',
req.params
);
console.log(
'POST /api/users/:id/profile/avi, req.file:',
req.file
);
try {
if (
req.file.mimetype === 'image/png' ||
req.file.mimetype === 'image/jpeg'
) {
let foundUser = await db.User.findById(
req.params.id
);
// console.log('foundUser', foundUser);
foundUser.profileImage = req.file.buffer;
await foundUser.save();
return res
.status(200)
.json({ profileImage: foundUser.profileImage });
} else {
console.log('!!!NOT AN IMAGE FILE!!!');
return next({
status : 404,
message : 'Please upload a valid image file'
});
}
} catch (err) {
return next({
status : 404,
message : 'Please upload a valid image file'
});
}
}
);
// GET comments on a post
app.get(
'/api/users/:id/posts/:post_id/comments',
loginRequired,
getFriends,
async function(req, res, next) {
console.log(
'GET /api/users/:id/posts/:post_id/comments/'
);
console.log(
'GET /api/users/:id/posts/:post_id/comments/, req.params',
req.params
);
console.log(
'GET /api/users/:id/posts/:post_id/comments/, req.params.post_id',
req.params.post_id
);
console.log(
'GET /api/users/:id/posts/:post_id/comments, res.locals',
res.locals
);
try {
let comments = await db.Comment
.find({ post: req.params.post_id })
.sort({ createdAt: 'asc' })
.populate('user', {
username : true,
profileImage : true
});
console.log('GET /:post_id/comments', comments);
return res.status(200).json(comments);
} catch (err) {
return next(err);
}
}
);
// comments routes to create, update, and delete comments
app.use(
'/api/users/:id/posts/:post_id/comments',
loginRequired,
ensureCorrectUser,
commentsRoutes
);
// GET specific post
app.get(
'/api/users/:id/posts/:post_id/',
loginRequired,
getFriends,
async function(req, res, next) {
console.log('GET /api/users/:id/posts/:post_id/');
try {
let post = await db.Post.findById(req.params.post_id);
let comments = await db.Comment
.find({ post: req.params.post_id })
.sort({ createdAt: 'asc' })
.populate('user', {
username : true,
profileImage : true
});
console.log('GET /:post_id', post, comments);
return res.status(200).json({ post, comments });
} catch (err) {
return next(err);
}
}
);
// other posts routes to create, update, and delete posts: all require ensureCorrectUser
app.use(
'/api/users/:id/posts',
loginRequired,
ensureCorrectUser,
postsRoutes
);
// friendsRoutes to display friend info and add/removefriends
app.use(
'/api/users/:id/profile',
loginRequired,
friendsRoutes
);
// GET scroll route that displays friends' posts
app.get(
'/api/scroll',
loginRequired,
getFriends,
async function(req, res, next) {
// console.log('/api/scroll:', req, res);
console.log('/api/scroll:');
try {
console.log('/api/scroll, res.locals:', res.locals);
let posts = await db.Post
.find({
$or : [
{ user: { $in: res.locals.friends } },
{ user: res.locals.you }
]
})
.sort({ createdAt: 'desc' })
.populate('user', {
username : true,
profileImage : true
});
console.log('/api/scroll, posts:', posts);
return res.status(200).json(posts);
} catch (err) {
return next(err);
}
}
);
// GET search route for finding users to friend
app.post('/api/search', loginRequired, async function(
req,
res,
next
) {
try {
console.log('/api/search route:', req.body, req.query);
let foundUser = null;
let pickedUser = null;
// search via username
// {'$regex': req.body.query, $options:'i'} makes the search case-insensitive
foundUser = await db.User.findOne({
username : { $regex: req.body.query, $options: 'i' }
});
console.log('...search via username:', foundUser);
if (foundUser) {
pickedUser = _.pick(foundUser, [
'username',
'email',
'_id',
'profileImage'
]);
console.log(
'...Found via username!',
foundUser,
pickedUser
);
return res.status(200).json({ pickedUser });
}
// search via email
foundUser = await db.User.findOne({
email : { $regex: req.body.query, $options: 'i' }
});
console.log('...search via email:', foundUser);
if (foundUser) {
pickedUser = _.pick(foundUser, [
'username',
'email',
'_id',
'profileImage'
]);
console.log(
'...Found via email!',
foundUser,
pickedUser
);
return res.status(200).json({ pickedUser });
}
return next({
status : 404,
message : 'User not found'
});
} catch (err) {
return next(err);
}
});
app.use(function(req, res, next) {
let err = new Error('Not Found');
err.status = 404;
next(err);
});
app.use(errorHandler);
app.listen(PORT, function() {
console.log(`Server is running on port ${PORT}`);
});