0
Fork 0
mirror of https://github.com/TryGhost/Ghost.git synced 2025-01-13 22:41:32 -05:00
ghost/core/server/api/index.js
Harry Wolff 91ca4a43e5 Fix routing of posts and static pages
closes #1757 and #1773

- switches routes.frontend for posts and pages
to use a regex with two capturing groups.  This removes
the need to dynamically remove an express route at a
later point, leaving the decision making to frontend
controller.

- added unit tests for all routing conditions that 
can arise for posts and pages.

- updated functional tests to also test for same thing
in unit tests

- removes old code from server/api/index that used
to fix this issue, but is no longer needed

- removed some un-needed require statements in routes/admin
2013-12-30 02:04:46 -05:00

79 lines
2.5 KiB
JavaScript

// # Ghost Data API
// Provides access to the data model
var _ = require('underscore'),
when = require('when'),
config = require('../config'),
errors = require('../errorHandling'),
db = require('./db'),
settings = require('./settings'),
notifications = require('./notifications'),
posts = require('./posts'),
users = require('./users'),
tags = require('./tags'),
requestHandler,
init;
// ## Request Handlers
function invalidateCache(req, res, result) {
var parsedUrl = req._parsedUrl.pathname.replace(/\/$/, '').split('/'),
method = req.method,
endpoint = parsedUrl[4],
id = parsedUrl[5],
cacheInvalidate,
jsonResult = result.toJSON ? result.toJSON() : result;
if (method === 'POST' || method === 'PUT' || method === 'DELETE') {
if (endpoint === 'settings' || endpoint === 'users' || endpoint === 'db') {
cacheInvalidate = "/*";
} else if (endpoint === 'posts') {
cacheInvalidate = "/, /page/*, /rss/, /rss/*";
if (id && jsonResult.slug) {
cacheInvalidate += ', /' + jsonResult.slug + '/';
}
}
if (cacheInvalidate) {
res.set({
"X-Cache-Invalidate": cacheInvalidate
});
}
}
}
// ### requestHandler
// decorator for api functions which are called via an HTTP request
// takes the API method and wraps it so that it gets data from the request and returns a sensible JSON response
requestHandler = function (apiMethod) {
return function (req, res) {
var options = _.extend(req.body, req.query, req.params),
apiContext = {
user: req.session && req.session.user
};
return apiMethod.call(apiContext, options).then(function (result) {
invalidateCache(req, res, result);
res.json(result || {});
}, function (error) {
var errorCode = error.errorCode || 500,
errorMsg = {error: _.isString(error) ? error : (_.isObject(error) ? error.message : 'Unknown API Error')};
res.json(errorCode, errorMsg);
});
};
};
init = function () {
return settings.updateSettingsCache();
};
// Public API
module.exports = {
posts: posts,
users: users,
tags: tags,
notifications: notifications,
settings: settings,
db: db,
requestHandler: requestHandler,
init: init
};