refactor: switch to async/await syntax in track routes

This commit is contained in:
Paul Bienkowski 2020-11-18 23:00:08 +01:00
parent 114a9677f1
commit f890fc673f
2 changed files with 348 additions and 378 deletions

View file

@ -8,7 +8,7 @@
"start": "node ./app.js",
"dev": "nodemon ./app.js",
"mongo:stop": "docker stop realworld-mongo && docker rm realworld-mongo",
"autoformat": "eslint --fix logic",
"autoformat": "eslint --fix logic routes/api/tracks.js",
"test": "jest"
},
"repository": {

View file

@ -9,11 +9,19 @@ const currentTracks = new Map();
const TrackInfo = require('../../logic/TrackInfo');
const { addPointsToTrack } = require('../../logic/tracks');
const wrapRoute = (fn) => async (req, res, next) => {
try {
return await fn(req, res);
} catch (err) {
next(err);
}
};
// Preload track objects on routes with ':track'
router.param('track', function (req, res, next, slug) {
Track.findOne({ slug: slug })
.populate('author')
.then(function (track) {
router.param('track', async (req, res, next, slug) => {
try {
const track = await Track.findOne({ slug }).populate('author');
if (!track) {
return res.sendStatus(404);
}
@ -21,13 +29,15 @@ router.param('track', function (req, res, next, slug) {
req.track = track;
return next();
})
.catch(next);
} catch (err) {
return next(err);
}
});
router.param('comment', function (req, res, next, id) {
Comment.findById(id)
.then(function (comment) {
router.param('comment', async (req, res, next, id) => {
try {
const comment = await Comment.findById(id);
if (!comment) {
return res.sendStatus(404);
}
@ -35,11 +45,15 @@ router.param('comment', function (req, res, next, id) {
req.comment = comment;
return next();
})
.catch(next);
} catch (err) {
return next(err);
}
});
router.get('/', auth.optional, function (req, res, next) {
router.get(
'/',
auth.optional,
wrapRoute(async (req, res) => {
const query = {};
let limit = 20;
let offset = 0;
@ -56,13 +70,10 @@ router.get('/', auth.optional, function (req, res, next) {
query.tagList = { $in: [req.query.tag] };
}
Promise.all([
const [author, favoriter] = await Promise.all([
req.query.author ? User.findOne({ username: req.query.author }) : null,
req.query.favorited ? User.findOne({ username: req.query.favorited }) : null,
])
.then(function (results) {
const author = results[0];
const favoriter = results[1];
]);
if (author) {
query.author = author._id;
@ -74,7 +85,7 @@ router.get('/', auth.optional, function (req, res, next) {
query._id = { $in: [] };
}
return Promise.all([
const results = await Promise.all([
Track.find(query)
.limit(Number(limit))
.skip(Number(offset))
@ -85,30 +96,21 @@ router.get('/', auth.optional, function (req, res, next) {
.exec(),
Track.countDocuments(query).exec(),
req.payload ? User.findById(req.payload.id) : null,
]).then(function (results) {
const tracks = results[0];
// const tracksCount = results[1];
const user = results[2];
// console.log(tracks);
const retTracks = [];
for (const t of tracks) {
// console.log(t);
// if (t.author.areTracksVisibleForAll || t.author == user) {
retTracks.push(t);
// }
}
return res.json({
tracks: retTracks.map(function (track) {
return track.toJSONFor(user);
}),
tracksCount: retTracks.length,
});
});
})
.catch(next);
});
]);
router.get('/feed', auth.required, function (req, res, next) {
const [tracks, tracksCount, user] = results;
return res.json({
tracks: tracks.map((track) => track.toJSONFor(user)),
tracksCount,
});
}),
);
router.get(
'/feed',
auth.required,
wrapRoute(async (req, res) => {
let limit = 20;
let offset = 0;
@ -120,22 +122,22 @@ router.get('/feed', auth.required, function (req, res, next) {
offset = req.query.offset;
}
User.findById(req.payload.id).then(function (user) {
const user = await User.findById(req.payload.id);
if (!user) {
return res.sendStatus(401);
}
if (user.following !== '') {
Promise.all([
Track.find({ author: { $in: user.following } })
const showByUserIds = [req.payload.id, ...(user.following || [])];
const [tracks, tracksCount] = await Promise.all([
Track.find({ author: { $in: showByUserIds } })
.limit(Number(limit))
.skip(Number(offset))
.populate('author')
.exec(),
Track.countDocuments({ author: { $in: user.following } }),
])
.then(function (results) {
const tracks = results[0];
const tracksCount = results[1];
Track.countDocuments({ author: { $in: showByUserIds } }),
]);
return res.json({
tracks: tracks.map(function (track) {
@ -143,36 +145,15 @@ router.get('/feed', auth.required, function (req, res, next) {
}),
tracksCount: tracksCount,
});
})
.catch(next);
} else {
Promise.all([
Track.find({ author: { $in: req.payload.id } })
.limit(Number(limit))
.skip(Number(offset))
.populate('author')
.exec(),
Track.countDocuments({ author: { $in: req.payload.id } }),
])
.then(function (results) {
const tracks = results[0];
const tracksCount = results[1];
return res.json({
tracks: tracks.map(function (track) {
return track.toJSONFor(user);
}),
tracksCount: tracksCount,
});
})
.catch(next);
}
});
});
);
router.post(
'/',
auth.required,
wrapRoute(async (req, res) => {
const user = await User.findById(req.payload.id);
router.post('/', auth.required, function (req, res, next) {
User.findById(req.payload.id)
.then(function (user) {
if (!user) {
return res.sendStatus(401);
}
@ -183,26 +164,24 @@ router.post('/', auth.required, function (req, res, next) {
track.author = user;
track.visible = track.author.areTracksVisibleForAll;
trackData.save(function (err) {
if (err) {
console.log('failed to save trackData');
}
});
await trackData.save();
await track.save();
return track.save().then(function () {
// console.log(track.author);
return res.json({ track: track.toJSONFor(user) });
});
})
.catch(next);
});
}),
);
router.post('/add', auth.optional, function (req, res, next) {
router.post(
'/add',
auth.optional,
wrapRoute(async (req, res) => {
// console.log("Add");
// console.log(req.payload);
User.findById(req.body.id)
.then(function (user) {
const user = await User.findById(req.body.id);
if (!user) {
return res.sendStatus(401);
}
@ -220,20 +199,20 @@ router.post('/add', auth.optional, function (req, res, next) {
ti.track.author = user;
}
// return track.save().then(function(){
// console.log(track.author);
// await track.save()
// return res.json({ track: track.toJSONFor(user) });
return res.sendStatus(200);
// });
})
.catch(next);
});
}),
);
router.post('/begin', auth.optional, function (req, res, next) {
router.post(
'/begin',
auth.optional,
wrapRoute(async (req, res) => {
// console.log("Begin");
// console.log(req.payload);
User.findById(req.body.id)
.then(function (user) {
const user = await User.findById(req.body.id);
if (!user) {
return res.sendStatus(401);
}
@ -254,19 +233,17 @@ router.post('/begin', auth.optional, function (req, res, next) {
// console.log(track.trackData.points[0].date);
ti.track.author = user;
// return track.save().then(function () {
// await track.save()
// console.log(track.author);
return res.sendStatus(200);
// });
})
.catch(next);
});
}),
);
router.post('/end', auth.optional, function (req, res, next) {
// console.log("End");
// console.log(req.payload);
User.findById(req.body.id)
.then(function (user) {
router.post(
'/end',
auth.optional,
wrapRoute(async (req, res) => {
const user = await User.findById(req.body.id);
if (!user) {
return res.sendStatus(401);
}
@ -289,33 +266,29 @@ router.post('/end', auth.optional, function (req, res, next) {
// console.log(track);
// console.log("user:"+user);
return ti.track.save().then(function () {
await ti.track.save();
// console.log("TLen" + ti.track);
// console.log("TLen" + ti.trackData);
// console.log("TLen" + ti.trackData.points.length);
ti.trackData.save(function (err) {
if (err) {
console.log('failed to save trackData' + err.toString());
}
});
await ti.trackData.save();
console.log('successfulSave:');
return res.sendStatus(200);
});
})
.catch(next);
});
}),
);
// return a track
router.get('/:track', auth.optional, function (req, res, next) {
Promise.all([req.payload ? User.findById(req.payload.id) : null, req.track.populate('author').execPopulate()])
.then(function (results) {
const user = results[0];
router.get(
'/:track',
auth.optional,
wrapRoute(async (req, res) => {
const [user] = await Promise.all([
req.payload ? User.findById(req.payload.id) : null,
req.track.populate('author').execPopulate(),
]);
return res.json({ track: req.track.toJSONFor(user, { body: true }) });
})
.catch(next);
});
}),
);
// update track
router.put('/:track', auth.required, async function (req, res, next) {
@ -356,69 +329,68 @@ router.put('/:track', auth.required, async function (req, res, next) {
});
// delete track
router.delete('/:track', auth.required, function (req, res, next) {
User.findById(req.payload.id)
.then(function (user) {
router.delete(
'/:track',
auth.required,
wrapRoute(async (req, res) => {
const user = await User.findById(req.payload.id);
if (!user) {
return res.sendStatus(401);
}
if (req.track.author._id.toString() === req.payload.id.toString()) {
TrackData.findByIdAndDelete(req.track.trackData, function (err, td) {
console.log('doneDelete');
}); // delet our track data
return req.track.remove().then(function () {
await TrackData.findByIdAndDelete(req.track.trackData);
await req.track.remove();
return res.sendStatus(204);
});
} else {
return res.sendStatus(403);
}
})
.catch(next);
});
}),
);
// Favorite an track
router.post('/:track/favorite', auth.required, function (req, res, next) {
router.post(
'/:track/favorite',
auth.required,
wrapRoute(async (req, res) => {
const trackId = req.track._id;
User.findById(req.payload.id)
.then(function (user) {
const user = await User.findById(req.payload.id);
if (!user) {
return res.sendStatus(401);
}
return user.favorite(trackId).then(function () {
return req.track.updateFavoriteCount().then(function (track) {
await user.favorite(trackId);
const track = await req.track.updateFavoriteCount();
return res.json({ track: track.toJSONFor(user) });
});
});
})
.catch(next);
});
}),
);
// Unfavorite an track
router.delete('/:track/favorite', auth.required, function (req, res, next) {
router.delete(
'/:track/favorite',
auth.required,
wrapRoute(async (req, res) => {
const trackId = req.track._id;
User.findById(req.payload.id)
.then(function (user) {
const user = await User.findById(req.payload.id);
if (!user) {
return res.sendStatus(401);
}
return user.unfavorite(trackId).then(function () {
return req.track.updateFavoriteCount().then(function (track) {
await user.unfavorite(trackId);
const track = await req.track.updateFavoriteCount();
return res.json({ track: track.toJSONFor(user) });
});
});
})
.catch(next);
});
}),
);
// return an track's comments
router.get('/:track/comments', auth.optional, function (req, res, next) {
Promise.resolve(req.payload ? User.findById(req.payload.id) : null)
.then(function (user) {
return req.track
router.get(
'/:track/comments',
auth.optional,
wrapRoute(async (req, res) => {
const user = await Promise.resolve(req.payload ? User.findById(req.payload.id) : null);
await req.track
.populate({
path: 'comments',
populate: {
@ -430,22 +402,22 @@ router.get('/:track/comments', auth.optional, function (req, res, next) {
},
},
})
.execPopulate()
.then(function (track) {
.execPopulate();
return res.json({
comments: req.track.comments.map(function (comment) {
return comment.toJSONFor(user);
}),
});
});
})
.catch(next);
});
}),
);
// create a new comment
router.post('/:track/comments', auth.required, function (req, res, next) {
User.findById(req.payload.id)
.then(function (user) {
router.post(
'/:track/comments',
auth.required,
wrapRoute(async (req, res) => {
const user = await User.findById(req.payload.id);
if (!user) {
return res.sendStatus(401);
}
@ -454,42 +426,40 @@ router.post('/:track/comments', auth.required, function (req, res, next) {
comment.track = req.track;
comment.author = user;
return comment.save().then(function () {
await comment.save();
req.track.comments.push(comment);
return req.track.save().then(function (track) {
res.json({ comment: comment.toJSONFor(user) });
});
});
})
.catch(next);
});
await req.track.save();
return res.json({ comment: comment.toJSONFor(user) });
}),
);
router.delete('/:track/comments/:comment', auth.required, function (req, res, next) {
router.delete(
'/:track/comments/:comment',
auth.required,
wrapRoute(async (req, res) => {
if (req.comment.author.toString() === req.payload.id.toString()) {
req.track.comments.remove(req.comment._id);
req.track
.save()
.then(Comment.find({ _id: req.comment._id }).remove().exec())
.then(function () {
await req.track.save();
await Comment.find({ _id: req.comment._id }).remove();
res.sendStatus(204);
});
} else {
res.sendStatus(403);
}
});
}),
);
// return an track's trackData
router.get('/:track/TrackData', auth.optional, function (req, res, next) {
Promise.resolve(req.payload ? User.findById(req.payload.id) : null)
.then(function (user) {
router.get(
'/:track/TrackData',
auth.optional,
wrapRoute(async (req, res) => {
// console.log("requestTrackData"+req.track);
TrackData.findById(req.track.trackData, function (err, trackData) {
const trackData = await TrackData.findById(req.track.trackData);
// console.log({trackData: trackData});
return res.json({ trackData: trackData });
});
})
.catch(next);
});
}),
);
module.exports = router;