-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathprofile.js
345 lines (307 loc) · 8.37 KB
/
profile.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
const express = require('express');
const axios = require('axios');
const config = require('config');
const router = express.Router();
const auth = require('../../middleware/auth');
const { check, validationResult } = require('express-validator');
// bring in normalize to give us a proper url, regardless of what user entered
const normalize = require('normalize-url');
const Profile = require('../../models/Profile');
const User = require('../../models/User');
const Post = require('../../models/Post');
// @route GET api/profile/me
// @desc Get current users profile
// @access Private
router.get('/me', auth, async (req, res) => {
try {
const profile = await Profile.findOne({
user: req.user.id
});
if (!profile) {
return res.status(400).json({ msg: 'There is no profile for this user' });
}
// only populate from user document if profile exists
res.json(profile.populate('user', ['name', 'avatar']));
} catch (err) {
console.error(err.message);
res.status(500).send('Server Error');
}
});
// @route POST api/profile
// @desc Create or update user profile
// @access Private
router.post(
'/',
[
auth,
[
check('status', 'Status is required')
.not()
.isEmpty(),
check('skills', 'Skills is required')
.not()
.isEmpty()
]
],
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const {
company,
location,
website,
bio,
skills,
status,
githubusername,
youtube,
twitter,
instagram,
linkedin,
facebook
} = req.body;
const profileFields = {
user: req.user.id,
company,
location,
website: website === '' ? '' : normalize(website, { forceHttps: true }),
bio,
skills: Array.isArray(skills)
? skills
: skills.split(',').map(skill => ' ' + skill.trim()),
status,
githubusername
};
// Build social object and add to profileFields
const socialfields = { youtube, twitter, instagram, linkedin, facebook };
for (const [key, value] of Object.entries(socialfields)) {
if (value.length > 0)
socialfields[key] = normalize(value, { forceHttps: true });
}
profileFields.social = socialfields;
try {
// Using upsert option (creates new doc if no match is found):
let profile = await Profile.findOneAndUpdate(
{ user: req.user.id },
{ $set: profileFields },
{ new: true, upsert: true }
);
res.json(profile);
} catch (err) {
console.error(err.message);
res.status(500).send('Server Error');
}
}
);
// @route GET api/profile
// @desc Get all profiles
// @access Public
router.get('/', async (req, res) => {
try {
const profiles = await Profile.find().populate('user', ['name', 'avatar']);
res.json(profiles);
} catch (err) {
console.error(err.message);
res.status(500).send('Server Error');
}
});
// @route GET api/profile/user/:user_id
// @desc Get profile by user ID
// @access Public
router.get('/user/:user_id', async (req, res) => {
try {
const profile = await Profile.findOne({
user: req.params.user_id
}).populate('user', ['name', 'avatar']);
if (!profile) return res.status(400).json({ msg: 'Profile not found' });
res.json(profile);
} catch (err) {
console.error(err.message);
if (err.kind == 'ObjectId') {
return res.status(400).json({ msg: 'Profile not found' });
}
res.status(500).send('Server Error');
}
});
// @route DELETE api/profile
// @desc Delete profile, user & posts
// @access Private
router.delete('/', auth, async (req, res) => {
try {
// Remove user posts
await Post.deleteMany({ user: req.user.id });
// Remove profile
await Profile.findOneAndRemove({ user: req.user.id });
// Remove user
await User.findOneAndRemove({ _id: req.user.id });
res.json({ msg: 'User deleted' });
} catch (err) {
console.error(err.message);
res.status(500).send('Server Error');
}
});
// @route PUT api/profile/experience
// @desc Add profile experience
// @access Private
router.put(
'/experience',
[
auth,
[
check('title', 'Title is required')
.not()
.isEmpty(),
check('company', 'Company is required')
.not()
.isEmpty(),
check('from', 'From date is required and needs to be from the past')
.not()
.isEmpty()
.custom((value, { req }) => (req.body.to ? value < req.body.to : true))
]
],
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const {
title,
company,
location,
from,
to,
current,
description
} = req.body;
const newExp = {
title,
company,
location,
from,
to,
current,
description
};
try {
const profile = await Profile.findOne({ user: req.user.id });
profile.experience.unshift(newExp);
await profile.save();
res.json(profile);
} catch (err) {
console.error(err.message);
res.status(500).send('Server Error');
}
}
);
// @route DELETE api/profile/experience/:exp_id
// @desc Delete experience from profile
// @access Private
router.delete('/experience/:exp_id', auth, async (req, res) => {
try {
const foundProfile = await Profile.findOne({ user: req.user.id });
foundProfile.experience = foundProfile.experience.filter(
exp => exp._id.toString() !== req.params.exp_id
);
await foundProfile.save();
return res.status(200).json(foundProfile);
} catch (error) {
console.error(error);
return res.status(500).json({ msg: 'Server error' });
}
});
// @route PUT api/profile/education
// @desc Add profile education
// @access Private
router.put(
'/education',
[
auth,
[
check('school', 'School is required')
.not()
.isEmpty(),
check('degree', 'Degree is required')
.not()
.isEmpty(),
check('fieldofstudy', 'Field of study is required')
.not()
.isEmpty(),
check('from', 'From date is required and needs to be from the past')
.not()
.isEmpty()
.custom((value, { req }) => (req.body.to ? value < req.body.to : true))
]
],
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const {
school,
degree,
fieldofstudy,
from,
to,
current,
description
} = req.body;
const newEdu = {
school,
degree,
fieldofstudy,
from,
to,
current,
description
};
try {
const profile = await Profile.findOne({ user: req.user.id });
profile.education.unshift(newEdu);
await profile.save();
res.json(profile);
} catch (err) {
console.error(err.message);
res.status(500).send('Server Error');
}
}
);
// @route DELETE api/profile/education/:edu_id
// @desc Delete education from profile
// @access Private
router.delete('/education/:edu_id', auth, async (req, res) => {
try {
const foundProfile = await Profile.findOne({ user: req.user.id });
foundProfile.education = foundProfile.education.filter(
edu => edu._id.toString() !== req.params.edu_id
);
await foundProfile.save();
return res.status(200).json(foundProfile);
} catch (error) {
console.error(error);
return res.status(500).json({ msg: 'Server error' });
}
});
// @route GET api/profile/github/:username
// @desc Get user repos from Github
// @access Public
router.get('/github/:username', async (req, res) => {
try {
const uri = encodeURI(
`https://api.github.com/users/${req.params.username}/repos?per_page=5&sort=created:asc`
);
const headers = {
'user-agent': 'node.js',
Authorization: `token ${config.get('githubToken')}`
};
const gitHubResponse = await axios.get(uri, { headers });
return res.json(gitHubResponse.data);
} catch (err) {
console.error(err.message);
return res.status(404).json({ msg: 'No Github profile found' });
}
});
module.exports = router;