refactor: remove duplicate code when loading track/comment params
This commit is contained in:
parent
dbe4b1db17
commit
4bfd55e110
|
@ -10,22 +10,31 @@ const currentTracks = new Map();
|
||||||
const { parseTrackPoints, normalizeUserAgent } = require('../../logic/tracks');
|
const { parseTrackPoints, normalizeUserAgent } = require('../../logic/tracks');
|
||||||
const wrapRoute = require('../../_helpers/wrapRoute');
|
const wrapRoute = require('../../_helpers/wrapRoute');
|
||||||
|
|
||||||
// Preload track objects on routes with ':track'
|
function preloadByParam(target, getValueFromParam) {
|
||||||
router.param('track', async (req, res, next, slug) => {
|
return async (req, res, next, paramValue) => {
|
||||||
try {
|
try {
|
||||||
const track = await Track.findOne({ slug }).populate('author');
|
const value = await getValueFromParam(paramValue);
|
||||||
|
|
||||||
if (!track) {
|
if (!value) {
|
||||||
return res.sendStatus(404);
|
return res.sendStatus(404);
|
||||||
}
|
}
|
||||||
|
|
||||||
req.track = track;
|
req[target] = value;
|
||||||
|
|
||||||
return next();
|
return next();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
return next(err);
|
return next(err);
|
||||||
}
|
}
|
||||||
});
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
router.param(
|
||||||
|
'track',
|
||||||
|
preloadByParam('track', (slug) => Track.findOne({ slug }).populate('author')),
|
||||||
|
);
|
||||||
|
router.param(
|
||||||
|
'comment',
|
||||||
|
preloadByParam('comment', (id) => Comment.findById(id)),
|
||||||
|
);
|
||||||
|
|
||||||
router.param('comment', async (req, res, next, id) => {
|
router.param('comment', async (req, res, next, id) => {
|
||||||
try {
|
try {
|
||||||
|
@ -63,7 +72,7 @@ router.get(
|
||||||
query.tagList = { $in: [req.query.tag] };
|
query.tagList = { $in: [req.query.tag] };
|
||||||
}
|
}
|
||||||
|
|
||||||
const author = req.query.author ? await User.findOne({ username: req.query.author }) : null
|
const author = req.query.author ? await User.findOne({ username: req.query.author }) : null;
|
||||||
|
|
||||||
if (author) {
|
if (author) {
|
||||||
query.author = author._id;
|
query.author = author._id;
|
||||||
|
|
Loading…
Reference in a new issue