0
Fork 0
mirror of https://github.com/TryGhost/Ghost.git synced 2025-02-24 23:48:13 -05:00
ghost/core/server/apps/amp/lib/router.js
Hannah Wolfe 98f5ae00fc
Introduced renderer to DRY up controllers (#9235)
refs #5091, #9192

- Renderer figures out templates, contexts, and does a render call
- Templating is now handled with a single function
- Context call is made in the renderer

Note:  to make this work, all controllers now define a little bit of config, currently stored in res._route. (That's a totally temporary location, as is res._template... when a sensible naming convention reveals itself I'll get rid of the weird _). This exposes a type and for custom routes a template name & default.
2017-11-10 12:44:29 +00:00

61 lines
1.8 KiB
JavaScript

var path = require('path'),
express = require('express'),
ampRouter = express.Router(),
i18n = require('../../../i18n'),
// Dirty requires
errors = require('../../../errors'),
postLookup = require('../../../controllers/frontend/post-lookup'),
renderer = require('../../../controllers/frontend/renderer'),
templateName = 'amp';
function _renderer(req, res, next) {
// Note: this is super similar to the config middleware used in channels
// @TODO refactor into to something explicit & DRY this up
res._route = {
type: 'custom',
templateName: templateName,
defaultTemplate: path.resolve(__dirname, 'views', templateName + '.hbs')
};
// Renderer begin
// Format data
var data = req.body || {};
// CASE: we only support amp pages for posts that are not static pages
if (!data.post || data.post.page) {
return next(new errors.NotFoundError({message: i18n.t('errors.errors.pageNotFound')}));
}
// Render Call
return renderer(req, res, data);
}
// This here is a controller.
// In fact, this whole file is nothing more than a controller + renderer & doesn't need to be a router
function getPostData(req, res, next) {
req.body = req.body || {};
postLookup(res.locals.relativeUrl)
.then(function handleResult(result) {
if (result && result.post) {
req.body.post = result.post;
}
next();
})
.catch(next);
}
// AMP frontend route
ampRouter
.route('/')
.get(
getPostData,
_renderer
);
module.exports = ampRouter;
module.exports.renderer = _renderer;
module.exports.getPostData = getPostData;