Skip to content

Commit

Permalink
Ensure middleware functions are named
Browse files Browse the repository at this point in the history
refs TryGhost#5091

- adds names to all middleware functions, for debugging purposes
  • Loading branch information
ErisDS committed Jun 2, 2015
1 parent 6ab5e70 commit 9e7002c
Show file tree
Hide file tree
Showing 14 changed files with 145 additions and 151 deletions.
22 changes: 11 additions & 11 deletions core/server/api/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ var _ = require('lodash'),
* Initialise the API - populate the settings cache
* @return {Promise(Settings)} Resolves to Settings Collection
*/
init = function () {
init = function init() {
return settings.updateSettingsCache();
};

Expand All @@ -53,7 +53,7 @@ init = function () {
* @param {Object} result API method result
* @return {String} Resolves to header string
*/
cacheInvalidationHeader = function (req, result) {
cacheInvalidationHeader = function cacheInvalidationHeader(req, result) {
var parsedUrl = req._parsedUrl.pathname.replace(/^\/|\/$/g, '').split('/'),
method = req.method,
endpoint = parsedUrl[0],
Expand Down Expand Up @@ -100,7 +100,7 @@ cacheInvalidationHeader = function (req, result) {
* @param {Object} result API method result
* @return {String} Resolves to header string
*/
locationHeader = function (req, result) {
locationHeader = function locationHeader(req, result) {
var apiRoot = config.urlFor('api'),
location,
newObject;
Expand Down Expand Up @@ -138,8 +138,8 @@ locationHeader = function (req, result) {
* @see http://tools.ietf.org/html/rfc598
* @return {string}
*/
contentDispositionHeader = function () {
return dataExport.fileName().then(function (filename) {
contentDispositionHeader = function contentDispositionHeader() {
return dataExport.fileName().then(function then(filename) {
return 'Attachment; filename="' + filename + '"';
});
};
Expand All @@ -152,15 +152,15 @@ contentDispositionHeader = function () {
* @param {Array} error
* @return {{errors: Array, statusCode: number}}
*/
formatHttpErrors = function (error) {
formatHttpErrors = function formatHttpErrors(error) {
var statusCode = 500,
errors = [];

if (!_.isArray(error)) {
error = [].concat(error);
}

_.each(error, function (errorItem) {
_.each(error, function each(errorItem) {
var errorContent = {};

// TODO: add logic to set the correct status code
Expand All @@ -175,7 +175,7 @@ formatHttpErrors = function (error) {
return {errors: errors, statusCode: statusCode};
};

addHeaders = function (apiMethod, req, res, result) {
addHeaders = function addHeaders(apiMethod, req, res, result) {
var cacheInvalidation,
location,
contentDisposition;
Expand Down Expand Up @@ -220,8 +220,8 @@ addHeaders = function (apiMethod, req, res, result) {
* @param {Function} apiMethod API method to call
* @return {Function} middleware format function to be called by the route when a matching request is made
*/
http = function (apiMethod) {
return function (req, res) {
http = function http(apiMethod) {
return function apiHandler(req, res) {
// We define 2 properties for using as arguments in API calls:
var object = req.body,
options = _.extend({}, req.files, req.query, req.params, {
Expand All @@ -240,7 +240,7 @@ http = function (apiMethod) {
return apiMethod(object, options).tap(function onSuccess(response) {
// Add X-Cache-Invalidate, Location, and Content-Disposition headers
return addHeaders(apiMethod, req, res, response);
}).then(function (response) {
}).then(function then(response) {
// Send a properly formatting HTTP response containing the data with correct headers
res.json(response || {});
}).catch(function onError(error) {
Expand Down
14 changes: 7 additions & 7 deletions core/server/controllers/admin.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,12 @@ adminControllers = {
// Route: index
// Path: /ghost/
// Method: GET
index: function (req, res) {
index: function index(req, res) {
/*jslint unparam:true*/

function renderIndex() {
return api.configuration.browse().then(function (data) {
var apiConfig = _.omit(data.configuration, function (value) {
return api.configuration.browse().then(function then(data) {
var apiConfig = _.omit(data.configuration, function omit(value) {
return _.contains(['environment', 'database', 'mail', 'version'], value.key);
});

Expand All @@ -25,9 +25,9 @@ adminControllers = {
});
}

updateCheck().then(function () {
updateCheck().then(function then() {
return updateCheck.showUpdateNotification();
}).then(function (updateVersion) {
}).then(function then(updateVersion) {
if (!updateVersion) {
return;
}
Expand All @@ -40,12 +40,12 @@ adminControllers = {
message: 'Ghost ' + updateVersion + ' is available! Hot Damn. <a href="http://support.ghost.org/how-to-upgrade/" target="_blank">Click here</a> to upgrade.'
};

return api.notifications.browse({context: {internal: true}}).then(function (results) {
return api.notifications.browse({context: {internal: true}}).then(function then(results) {
if (!_.some(results.notifications, {message: notification.message})) {
return api.notifications.add({notifications: [notification]}, {context: {internal: true}});
}
});
}).finally(function () {
}).finally(function noMatterWhat() {
renderIndex();
}).catch(errors.logError);
}
Expand Down
56 changes: 23 additions & 33 deletions core/server/controllers/frontend.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ var _ = require('lodash'),
staticPostPermalink = routeMatch('/:slug/:edit?');

function getPostPage(options) {
return api.settings.read('postsPerPage').then(function (response) {
return api.settings.read('postsPerPage').then(function then(response) {
var postPP = response.settings[0],
postsPerPage = parseInt(postPP.value, 10);

Expand Down Expand Up @@ -58,7 +58,12 @@ function formatResponse(post) {
}

function handleError(next) {
return function (err) {
return function handleError(err) {
// If we've thrown an error message of type: 'NotFound' then we found no path match.
if (err.errorType === 'NotFoundError') {
return next();
}

return next(err);
};
}
Expand Down Expand Up @@ -100,7 +105,7 @@ function setResponseContext(req, res, data) {
// Add Request context parameter to the data object
// to be passed down to the templates
function setReqCtx(req, data) {
(Array.isArray(data) ? data : [data]).forEach(function (d) {
(Array.isArray(data) ? data : [data]).forEach(function forEach(d) {
d.secure = req.secure;
});
}
Expand All @@ -115,7 +120,7 @@ function getActiveThemePaths() {
context: {
internal: true
}
}).then(function (response) {
}).then(function then(response) {
var activeTheme = response.settings[0],
paths = config.paths.availableThemes[activeTheme.value];

Expand All @@ -130,8 +135,8 @@ function getActiveThemePaths() {
* Returns a function that takes the post to be rendered.
*/
function renderPost(req, res) {
return function (post) {
return getActiveThemePaths().then(function (paths) {
return function renderPost(post) {
return getActiveThemePaths().then(function then(paths) {
var view = template.getThemeViewForPost(paths, post),
response = formatResponse(post);

Expand Down Expand Up @@ -176,7 +181,7 @@ function renderChannel(channelOpts) {
return res.redirect(createUrl());
}

return getPostPage(options).then(function (page) {
return getPostPage(options).then(function then(page) {
// If page is greater than number of pages we have, redirect to last page
if (pageParam > page.meta.pagination.pages) {
return res.redirect(createUrl(page.meta.pagination.pages));
Expand All @@ -189,8 +194,8 @@ function renderChannel(channelOpts) {
setReqCtx(req, filter);
}

filters.doFilter('prePostsRender', page.posts, res.locals).then(function (posts) {
getActiveThemePaths().then(function (paths) {
filters.doFilter('prePostsRender', page.posts, res.locals).then(function then(posts) {
getActiveThemePaths().then(function then(paths) {
var view = 'index',
result,
extra = {};
Expand Down Expand Up @@ -241,14 +246,14 @@ frontendControllers = {
filter: 'author',
slugTemplate: true
}),
preview: function (req, res, next) {
preview: function preview(req, res, next) {
var params = {
uuid: req.params.uuid,
status: 'all',
include: 'author,tags,fields'
};

api.posts.read(params).then(function (result) {
api.posts.read(params).then(function then(result) {
var post = result.posts[0];

if (!post) {
Expand All @@ -263,21 +268,15 @@ frontendControllers = {

filters.doFilter('prePostsRender', post, res.locals)
.then(renderPost(req, res));
}).catch(function (err) {
if (err.errorType === 'NotFoundError') {
return next();
}

return handleError(next)(err);
});
}).catch(handleError(next));
},

single: function (req, res, next) {
single: function single(req, res, next) {
var postPath = req.path,
params,
usingStaticPermalink = false;

api.settings.read('permalinks').then(function (response) {
api.settings.read('permalinks').then(function then(response) {
var permalink = response.settings[0].value,
editFormat,
postLookup,
Expand Down Expand Up @@ -314,7 +313,7 @@ frontendControllers = {

// Query database to find post
return api.posts.read(postLookup);
}).then(function (result) {
}).then(function then(result) {
var post = result.posts[0],
postUrl = (params.edit) ? postPath.replace(params.edit + '/', '') : postPath;

Expand Down Expand Up @@ -358,21 +357,12 @@ frontendControllers = {
} else {
return next();
}
}).catch(function (err) {
// If we've thrown an error message
// of type: 'NotFound' then we found
// no path match.
if (err.errorType === 'NotFoundError') {
return next();
}

return handleError(next)(err);
});
}).catch(handleError(next));
},
rss: rss,
private: function (req, res) {
private: function private(req, res) {
var defaultPage = path.resolve(config.paths.adminViews, 'private.hbs');
return getActiveThemePaths().then(function (paths) {
return getActiveThemePaths().then(function then(paths) {
var data = {};
if (res.error) {
data.error = res.error;
Expand Down
20 changes: 10 additions & 10 deletions core/server/data/xml/rss/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ function isAuthor(req) {
}

function handleError(next) {
return function (err) {
return function handleError(err) {
return next(err);
};
}
Expand Down Expand Up @@ -82,8 +82,8 @@ function getBaseUrl(req, slugParam) {
function processUrls(html, siteUrl, itemUrl) {
var htmlContent = cheerio.load(html, {decodeEntities: false});
// convert relative resource urls to absolute
['href', 'src'].forEach(function (attributeName) {
htmlContent('[' + attributeName + ']').each(function (ix, el) {
['href', 'src'].forEach(function forEach(attributeName) {
htmlContent('[' + attributeName + ']').each(function each(ix, el) {
var baseUrl,
attributeValue,
parsed;
Expand Down Expand Up @@ -127,7 +127,7 @@ function processUrls(html, siteUrl, itemUrl) {
return htmlContent;
}

getFeedXml = function (path, data) {
getFeedXml = function getFeedXml(path, data) {
var dataHash = crypto.createHash('md5').update(JSON.stringify(data)).digest('hex');
if (!feedCache[path] || feedCache[path].hash !== dataHash) {
// We need to regenerate
Expand All @@ -140,7 +140,7 @@ getFeedXml = function (path, data) {
return feedCache[path].xml;
};

generateFeed = function (data) {
generateFeed = function generateFeed(data) {
var feed = new RSS({
title: data.title,
description: data.description,
Expand All @@ -154,7 +154,7 @@ generateFeed = function (data) {
}
});

data.results.posts.forEach(function (post) {
data.results.posts.forEach(function forEach(post) {
var itemUrl = config.urlFor('post', {post: post, permalinks: data.permalinks, secure: data.secure}, true),
htmlContent = processUrls(post.html, data.siteUrl, itemUrl),
item = {
Expand Down Expand Up @@ -196,12 +196,12 @@ generateFeed = function (data) {
feed.item(item);
});

return filters.doFilter('rss.feed', feed).then(function (feed) {
return filters.doFilter('rss.feed', feed).then(function then(feed) {
return feed.xml();
});
};

generate = function (req, res, next) {
generate = function generate(req, res, next) {
// Initialize RSS
var pageParam = req.params.page !== undefined ? parseInt(req.params.page, 10) : 1,
slugParam = req.params.slug,
Expand All @@ -213,7 +213,7 @@ generate = function (req, res, next) {
return res.redirect(baseUrl);
}

return getData(options).then(function (data) {
return getData(options).then(function then(data) {
var maxPage = data.results.meta.pagination.pages;

// If page is greater than number of pages we have, redirect to last page
Expand All @@ -226,7 +226,7 @@ generate = function (req, res, next) {
data.feedUrl = config.urlFor({relativeUrl: baseUrl, secure: req.secure}, true);
data.secure = req.secure;

return getFeedXml(req.originalUrl, data).then(function (feedXml) {
return getFeedXml(req.originalUrl, data).then(function then(feedXml) {
res.set('Content-Type', 'text/xml; charset=UTF-8');
res.send(feedXml);
});
Expand Down
10 changes: 5 additions & 5 deletions core/server/data/xml/sitemap/handler.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,28 +3,28 @@ var _ = require('lodash'),
sitemap = require('./index');

// Responsible for handling requests for sitemap files
module.exports = function (blogApp) {
module.exports = function handler(blogApp) {
var resourceTypes = ['posts', 'authors', 'tags', 'pages'],
verifyResourceType = function (req, res, next) {
verifyResourceType = function verifyResourceType(req, res, next) {
if (!_.contains(resourceTypes, req.params.resource)) {
return res.sendStatus(404);
}

next();
},
getResourceSiteMapXml = function (type, page) {
getResourceSiteMapXml = function getResourceSiteMapXml(type, page) {
return sitemap.getSiteMapXml(type, page);
};

blogApp.get('/sitemap.xml', function (req, res) {
blogApp.get('/sitemap.xml', function sitemapXML(req, res) {
res.set({
'Cache-Control': 'public, max-age=' + utils.ONE_HOUR_S,
'Content-Type': 'text/xml'
});
res.send(sitemap.getIndexXml());
});

blogApp.get('/sitemap-:resource.xml', verifyResourceType, function (req, res) {
blogApp.get('/sitemap-:resource.xml', verifyResourceType, function sitemapResourceXML(req, res) {
var type = req.params.resource,
page = 1,
siteMapXml = getResourceSiteMapXml(type, page);
Expand Down
Loading

0 comments on commit 9e7002c

Please sign in to comment.