2018-07-31 16:58:04 +01:00
|
|
|
import React from 'react';
|
|
|
|
import { renderToString } from 'react-dom/server';
|
2018-08-01 12:42:00 +01:00
|
|
|
import { StaticRouter } from 'react-router-dom';
|
2018-07-31 16:58:04 +01:00
|
|
|
|
|
|
|
import NewsApp from '../../news/NewsApp';
|
|
|
|
|
2018-08-01 12:42:00 +01:00
|
|
|
function serveNewsApp(req, res) {
|
|
|
|
const context = {};
|
|
|
|
const markup = renderToString(
|
|
|
|
<StaticRouter basename='/news' context={context} location={req.url}>
|
|
|
|
<NewsApp />
|
|
|
|
</StaticRouter>
|
|
|
|
);
|
2018-08-02 16:48:02 +01:00
|
|
|
if (context.url) {
|
|
|
|
// 'client-side' routing hit on a redirect
|
|
|
|
return res.redirect(context.url);
|
|
|
|
}
|
2018-08-01 12:42:00 +01:00
|
|
|
return res.render('layout-news', { title: 'News | freeCodeCamp', markup });
|
|
|
|
}
|
|
|
|
|
2018-08-03 10:32:38 +01:00
|
|
|
function createReferralHandler(app) {
|
|
|
|
return function referralHandler(req, res, next) {
|
|
|
|
const { Article } = app.models;
|
|
|
|
const { shortId } = req.params;
|
|
|
|
if (!shortId) {
|
|
|
|
return res.redirect('/news');
|
|
|
|
}
|
|
|
|
console.log(shortId);
|
|
|
|
return Article.findOne(
|
|
|
|
{
|
|
|
|
where: {
|
|
|
|
or: [{ shortId }, { slugPart: shortId }]
|
|
|
|
}
|
|
|
|
},
|
|
|
|
(err, article) => {
|
|
|
|
if (err) {
|
|
|
|
next(err);
|
|
|
|
}
|
|
|
|
if (!article) {
|
|
|
|
return res.redirect('/news');
|
|
|
|
}
|
|
|
|
const {
|
|
|
|
slugPart,
|
|
|
|
shortId,
|
|
|
|
author: { username }
|
|
|
|
} = article;
|
|
|
|
const slug = `/news/${username}/${slugPart}--${shortId}`;
|
|
|
|
return res.redirect(slug);
|
|
|
|
}
|
|
|
|
);
|
|
|
|
};
|
|
|
|
}
|
2018-08-02 16:48:02 +01:00
|
|
|
|
2018-08-03 10:32:38 +01:00
|
|
|
export default function newsBoot(app) {
|
2018-07-31 16:34:32 +01:00
|
|
|
const router = app.loopback.Router();
|
|
|
|
|
2018-08-03 10:32:38 +01:00
|
|
|
router.get('/n', (req, res) => res.redirect('/news'));
|
|
|
|
router.get('/n/:shortId', createReferralHandler(app));
|
|
|
|
|
2018-08-01 12:42:00 +01:00
|
|
|
router.get('/news', serveNewsApp);
|
|
|
|
router.get('/news/*', serveNewsApp);
|
2018-07-31 16:34:32 +01:00
|
|
|
|
2018-08-01 12:42:00 +01:00
|
|
|
app.use(router);
|
2018-07-31 16:34:32 +01:00
|
|
|
}
|