Ghost/core/server/apps/amp/lib/router.js
Hannah Wolfe 61bf54ec88 🎉 Middleware refactor: Give the API its own express App (#7537)
refs #4172

* 🎨 Use bodyParser only where it is needed

This is a pretty extreme optimisation, however in the interests of killing middleware/index.js it
seemed prudent to move towards not having in there that wasn't strictly necessary 😁

We should reassess how apps do this sort of thing, but it seems pretty sane to declare bodyParsing
if and only if it is necessary.

* 🎨 Move all API code to API router

* 🎨 Refactor API into an App, not just a router

- Apps have their own rendering engines, only the frontend & the admin panel need views
- The API should be JSON only, with minimal middleware
- Individual sections within the API could/should be treated as Routers

* 🎨 Flatten API middleware inclusion

- get rid of the weird middleware object
- move the api-only middleware into the middleware/api folder
2016-10-11 10:36:00 +02:00

65 lines
1.9 KiB
JavaScript

var path = require('path'),
express = require('express'),
_ = require('lodash'),
ampRouter = express.Router(),
// Dirty requires
errors = require('../../../errors'),
templates = require('../../../controllers/frontend/templates'),
postLookup = require('../../../controllers/frontend/post-lookup'),
setResponseContext = require('../../../controllers/frontend/context');
function controller(req, res, next) {
var defaultView = path.resolve(__dirname, 'views', 'amp.hbs'),
paths = templates.getActiveThemePaths(req.app.get('activeTheme')),
data = req.amp;
if (res.error) {
data.error = res.error;
}
setResponseContext(req, res, data);
// we have to check the context. Our context must be ['post', 'amp'], otherwise we won't render the template
if (_.includes(res.locals.context, 'post') && _.includes(res.locals.context, 'amp')) {
if (paths.hasOwnProperty('amp.hbs')) {
return res.render('amp', data);
} else {
return res.render(defaultView, data);
}
} else {
return next();
}
}
function getPostData(req, res, next) {
// Create a req property where we can store our data
req.amp = {};
postLookup(res.locals.relativeUrl)
.then(function (result) {
if (result && result.post) {
req.amp.post = result.post;
}
next();
})
.catch(function (err) {
if (err instanceof errors.NotFoundError) {
return next(err);
}
next(err);
});
}
// AMP frontend route
ampRouter.route('/')
.get(
getPostData,
controller
);
module.exports = ampRouter;
module.exports.controller = controller;
module.exports.getPostData = getPostData;