Feature(server): Add response type detecting to lang redirect
This commit is contained in:
@ -1,5 +1,6 @@
|
|||||||
import supportedLanguages from '../../common/utils/supported-languages';
|
import supportedLanguages from '../../common/utils/supported-languages';
|
||||||
import passThroughs from '../utils/lang-passthrough-urls';
|
import passThroughs from '../utils/lang-passthrough-urls';
|
||||||
|
import accepts from 'accepts';
|
||||||
// import debug from 'debug';
|
// import debug from 'debug';
|
||||||
|
|
||||||
// const log = debug('fcc:controller:lang-redirect');
|
// const log = debug('fcc:controller:lang-redirect');
|
||||||
@ -7,6 +8,8 @@ const toLowerCase = String.prototype.toLowerCase;
|
|||||||
|
|
||||||
export default function redirectLang(app) {
|
export default function redirectLang(app) {
|
||||||
app.all('*', function(req, res, next) {
|
app.all('*', function(req, res, next) {
|
||||||
|
const accept = accepts(req);
|
||||||
|
const type = accept.type('html', 'json', 'text');
|
||||||
const { url, path } = req;
|
const { url, path } = req;
|
||||||
const langCode = toLowerCase.call(url.split('/')[1]);
|
const langCode = toLowerCase.call(url.split('/')[1]);
|
||||||
|
|
||||||
@ -14,14 +17,24 @@ export default function redirectLang(app) {
|
|||||||
return next();
|
return next();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (supportedLanguages[langCode]) {
|
if (!supportedLanguages[langCode]) {
|
||||||
|
// language aware redirect
|
||||||
|
console.log('foo', path, req.method);
|
||||||
|
return res.redirect(url);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (type === 'html') {
|
||||||
req.flash('errors', {
|
req.flash('errors', {
|
||||||
msg: `We couldn't find path ${ path }`
|
msg: `We couldn't find path ${ path }`
|
||||||
});
|
});
|
||||||
return res.render('404', { title: '404'});
|
return res.render('404', { title: '404'});
|
||||||
}
|
}
|
||||||
|
|
||||||
// language aware redirect
|
if (type === 'json') {
|
||||||
return res.redirect(url);
|
return res.status('404').json({ error: 'path not found' });
|
||||||
|
}
|
||||||
|
|
||||||
|
res.setHeader('Content-Type', 'text/plain');
|
||||||
|
return res.send('404 path not found');
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
@ -19,10 +19,10 @@ export default function prodErrorHandler() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// parse res type
|
// parse res type
|
||||||
var accept = accepts(req);
|
const accept = accepts(req);
|
||||||
var type = accept.type('html', 'json', 'text');
|
const type = accept.type('html', 'json', 'text');
|
||||||
|
|
||||||
var message = 'Oops! Something went wrong. Please try again later';
|
const message = 'Oops! Something went wrong. Please try again later';
|
||||||
if (type === 'html') {
|
if (type === 'html') {
|
||||||
if (typeof req.flash === 'function') {
|
if (typeof req.flash === 'function') {
|
||||||
req.flash(err.messageType || 'errors', {
|
req.flash(err.messageType || 'errors', {
|
||||||
|
Reference in New Issue
Block a user