Ghost/core/server/controllers/frontend/post-lookup.js
Hannah Wolfe 63723aa36a 🎨 Move settings cache & cleanup settings API (#8057)
closes #8037

🔥 Remove API-level default settings population
- This is a relic!
- We ALWAYS populate defaults on server start therefore this code could never run.
- This was a lot of complicated code that wasn't even needed!!

🎨 Move settings cache
- Move settings cache to be its own thing
- Update all references
- Adds TODOs for further cleanup

🎨 Create settings initialisation step
- Create new settings library, which will eventually house more code
- Unify the interface for initialising settings (will be more useful later)
- Reduce number of calls to updateSettingsCache
2017-02-27 16:53:04 +01:00

70 lines
2.2 KiB
JavaScript

var _ = require('lodash'),
Promise = require('bluebird'),
url = require('url'),
routeMatch = require('path-match')(),
api = require('../../api'),
settingsCache = require('../../settings/cache'),
optionsFormat = '/:options?';
function getOptionsFormat(linkStructure) {
return linkStructure.replace(/\/$/, '') + optionsFormat;
}
function postLookup(postUrl) {
var postPath = url.parse(postUrl).path,
postPermalink = settingsCache.get('permalinks'),
pagePermalink = '/:slug/',
isEditURL = false,
matchFuncPost,
matchFuncPage,
postParams,
params;
// Convert saved permalink into a path-match function
matchFuncPost = routeMatch(getOptionsFormat(postPermalink));
matchFuncPage = routeMatch(getOptionsFormat(pagePermalink));
postParams = matchFuncPost(postPath);
// Check if the path matches the permalink structure.
// If there are no matches found, test to see if this is a page instead
params = postParams || matchFuncPage(postPath);
// if there are no matches for either then return empty
if (params === false) {
return Promise.resolve();
}
// If params contains options, and it is equal to 'edit', this is an edit URL
if (params.options && params.options.toLowerCase() === 'edit') {
isEditURL = true;
}
// Query database to find post
return api.posts.read(_.extend(_.pick(params, 'slug', 'id'), {include: 'author,tags'})).then(function then(result) {
var post = result.posts[0];
if (!post) {
return Promise.resolve();
}
// CASE: we originally couldn't match the post based on date permalink and we tried to check if its a page
if (!post.page && !postParams) {
return Promise.resolve();
}
// CASE: we only support /:slug format for pages
if (post.page && matchFuncPage(postPath) === false) {
return Promise.resolve();
}
return {
post: post,
isEditURL: isEditURL,
isUnknownOption: isEditURL ? false : params.options ? true : false
};
});
}
module.exports = postLookup;