freeCodeCamp/api-server/server/boot/news.js

42 lines
929 B
JavaScript
Raw Normal View History

import debug from 'debug';
2018-07-31 15:58:04 +00:00
2018-11-29 12:12:15 +00:00
const log = debug('fcc:boot:news');
export default function newsBoot(app) {
2019-01-14 17:19:13 +00:00
const router = app.loopback.Router();
2018-11-29 12:12:15 +00:00
2019-01-14 17:19:13 +00:00
router.get('/n', (req, res) => res.redirect('/news'));
router.get('/n/:shortId', createShortLinkHandler(app));
2018-11-29 12:12:15 +00:00
}
function createShortLinkHandler(app) {
const { Article } = app.models;
return function shortLinkHandler(req, res, next) {
const { shortId } = req.params;
if (!shortId) {
2019-01-14 17:19:13 +00:00
return res.redirect('/news');
2018-11-29 12:12:15 +00:00
}
2019-01-14 17:19:13 +00:00
log('shortId', shortId);
2018-11-29 12:12:15 +00:00
return Article.findOne(
{
where: {
or: [{ shortId }, { slugPart: shortId }]
}
},
(err, article) => {
if (err) {
next(err);
}
if (!article) {
2019-01-14 17:19:13 +00:00
return res.redirect('/news');
2018-11-29 12:12:15 +00:00
}
const { slugPart } = article;
2019-01-14 17:19:13 +00:00
const slug = `/news/${slugPart}`;
return res.redirect(slug);
2018-11-29 12:12:15 +00:00
}
);
};
}