2020-11-20 10:02:30 +00:00
|
|
|
const router = require('express').Router();
|
|
|
|
const mongoose = require('mongoose');
|
|
|
|
const User = mongoose.model('User');
|
2020-11-20 10:30:12 +00:00
|
|
|
const wrapRoute = require('../../_helpers/wrapRoute');
|
2020-11-20 10:02:30 +00:00
|
|
|
const auth = require('../auth');
|
2020-04-13 00:02:40 +00:00
|
|
|
|
|
|
|
// Preload user profile on routes with ':username'
|
2020-11-20 10:30:12 +00:00
|
|
|
router.param('username', async function (req, res, next, username) {
|
|
|
|
try {
|
|
|
|
const user = await User.findOne({ username: username });
|
|
|
|
if (!user) {
|
|
|
|
return res.sendStatus(404);
|
|
|
|
}
|
2020-04-13 00:02:40 +00:00
|
|
|
|
2020-11-20 10:30:12 +00:00
|
|
|
req.profile = user;
|
2020-04-13 00:02:40 +00:00
|
|
|
|
2020-11-20 10:30:12 +00:00
|
|
|
return next();
|
|
|
|
} catch (err) {
|
|
|
|
next(err);
|
|
|
|
}
|
2020-04-13 00:02:40 +00:00
|
|
|
});
|
|
|
|
|
2020-11-20 10:30:12 +00:00
|
|
|
router.get(
|
|
|
|
'/:username',
|
|
|
|
auth.optional,
|
|
|
|
wrapRoute(async (req, res) => {
|
|
|
|
if (!req.payload) {
|
|
|
|
return res.json({ profile: req.profile.toProfileJSONFor(false) });
|
|
|
|
}
|
2020-04-13 00:02:40 +00:00
|
|
|
|
2020-11-20 10:30:12 +00:00
|
|
|
const user = await User.findById(req.payload.id);
|
|
|
|
if (!user) {
|
|
|
|
return res.json({ profile: req.profile.toProfileJSONFor(false) });
|
|
|
|
}
|
2020-04-13 00:02:40 +00:00
|
|
|
|
2020-11-20 10:30:12 +00:00
|
|
|
return res.json({ profile: req.profile.toProfileJSONFor(user) });
|
|
|
|
}),
|
|
|
|
);
|
2020-04-13 00:02:40 +00:00
|
|
|
|
2020-11-20 10:30:12 +00:00
|
|
|
router.post(
|
|
|
|
'/:username/follow',
|
|
|
|
auth.required,
|
|
|
|
wrapRoute(async (req, res) => {
|
|
|
|
const profileId = req.profile._id;
|
2020-04-13 00:02:40 +00:00
|
|
|
|
2020-11-20 10:30:12 +00:00
|
|
|
const user = await User.findById(req.payload.id);
|
|
|
|
if (!user) {
|
|
|
|
return res.sendStatus(401);
|
|
|
|
}
|
2020-04-13 00:02:40 +00:00
|
|
|
|
2020-11-20 10:30:12 +00:00
|
|
|
await user.follow(profileId);
|
|
|
|
return res.json({ profile: req.profile.toProfileJSONFor(user) });
|
|
|
|
}),
|
|
|
|
);
|
2020-04-13 00:02:40 +00:00
|
|
|
|
2020-11-20 10:30:12 +00:00
|
|
|
router.delete(
|
|
|
|
'/:username/follow',
|
|
|
|
auth.required,
|
|
|
|
wrapRoute(async (req, res) => {
|
|
|
|
const profileId = req.profile._id;
|
2020-04-13 00:02:40 +00:00
|
|
|
|
2020-11-20 10:30:12 +00:00
|
|
|
const user = User.findById(req.payload.id);
|
|
|
|
if (!user) {
|
|
|
|
return res.sendStatus(401);
|
|
|
|
}
|
|
|
|
|
|
|
|
await user.unfollow(profileId);
|
|
|
|
return res.json({ profile: req.profile.toProfileJSONFor(user) });
|
|
|
|
}),
|
|
|
|
);
|
2020-04-13 00:02:40 +00:00
|
|
|
|
|
|
|
module.exports = router;
|