Misc cleanup & consistency amends (#9002)

no issue

- Consistent naming for postLookup
   - makes it easier to search and inspect the various usages
- Cleanup unneeded code
- Make res.render calls more consistent
- add some consistency to the calls to res.render
- Remove ancient reference to dataProvider
- Let's call it models everywhere now...
- Use consistent formatting across the API
- we're no longer using alignment in vars
- Misc other consistency changes in API
- always refer to local utils as apiUtils
- logical grouping of requires - dependencies, utils, "lib common" etc
- use xAPI to refer to API endpoints, e.g. mailAPI, settingsAPI for clarity
This commit is contained in:
Hannah Wolfe 2017-09-12 16:31:14 +01:00 committed by Katharina Irrgang
parent 2647b754d1
commit 4237446277
25 changed files with 375 additions and 388 deletions

View File

@ -1,19 +1,19 @@
var _ = require('lodash'),
var Promise = require('bluebird'),
_ = require('lodash'),
validator = require('validator'),
Promise = require('bluebird'),
pipeline = require('../utils/pipeline'),
settings = require('./settings'),
mail = require('./../mail'),
apiMail = require('./mail'),
globalUtils = require('../utils'),
utils = require('./utils'),
errors = require('../errors'),
apiUtils = require('./utils'),
models = require('../models'),
logging = require('../logging'),
events = require('../events'),
config = require('../config'),
errors = require('../errors'),
events = require('../events'),
i18n = require('../i18n'),
logging = require('../logging'),
spamPrevention = require('../middleware/api/spam-prevention'),
mailAPI = require('./mail'),
settingsAPI = require('./settings'),
authentication,
tokenSecurity = {};
@ -61,7 +61,7 @@ function setupTasks(setupData) {
var tasks;
function validateData(setupData) {
return utils.checkObject(setupData, 'setup').then(function then(checked) {
return apiUtils.checkObject(setupData, 'setup').then(function then(checked) {
var data = checked.setup[0];
return {
@ -109,7 +109,7 @@ function setupTasks(setupData) {
{key: 'description', value: i18n.t('common.api.authentication.sampleBlogDescription')}
];
return settings.edit({settings: userSettings}, context).return(user);
return settingsAPI.edit({settings: userSettings}, context).return(user);
}
function formatResponse(user) {
@ -141,7 +141,7 @@ authentication = {
var tasks;
function validateRequest(object) {
return utils.checkObject(object, 'passwordreset').then(function then(data) {
return apiUtils.checkObject(object, 'passwordreset').then(function then(data) {
var email = data.passwordreset[0].email;
if (typeof email !== 'string' || !validator.isEmail(email)) {
@ -158,7 +158,7 @@ authentication = {
var options = {context: {internal: true}},
dbHash, token;
return settings.read(_.merge({key: 'db_hash'}, options))
return settingsAPI.read(_.merge({key: 'db_hash'}, options))
.then(function fetchedSettings(response) {
dbHash = response.settings[0].value;
@ -205,7 +205,7 @@ authentication = {
}]
};
return apiMail.send(payload, {context: {internal: true}});
return mailAPI.send(payload, {context: {internal: true}});
});
}
@ -238,7 +238,7 @@ authentication = {
var tasks, tokenIsCorrect, dbHash, options = {context: {internal: true}}, tokenParts;
function validateRequest() {
return utils.validate('passwordreset')(object, options)
return apiUtils.validate('passwordreset')(object, options)
.then(function (options) {
var data = options.data.passwordreset[0];
@ -286,7 +286,7 @@ authentication = {
oldPassword = data.oldPassword,
newPassword = data.newPassword;
return settings.read(_.merge({key: 'db_hash'}, options))
return settingsAPI.read(_.merge({key: 'db_hash'}, options))
.then(function fetchedSettings(response) {
dbHash = response.settings[0].value;
@ -355,7 +355,7 @@ authentication = {
var tasks, invite, options = {context: {internal: true}};
function validateInvitation(invitation) {
return utils.checkObject(invitation, 'invitation')
return apiUtils.checkObject(invitation, 'invitation')
.then(function () {
if (!invitation.invitation[0].token) {
return Promise.reject(new errors.ValidationError({message: i18n.t('errors.api.authentication.noTokenProvided')}));
@ -532,7 +532,7 @@ authentication = {
}]
};
apiMail.send(payload, {context: {internal: true}}).catch(function (error) {
mailAPI.send(payload, {context: {internal: true}}).catch(function (error) {
logging.error(new errors.EmailError({
err: error,
context: i18n.t('errors.api.authentication.unableToSendWelcomeEmail'),

View File

@ -2,12 +2,11 @@
// RESTful API for the Client resource
var Promise = require('bluebird'),
_ = require('lodash'),
dataProvider = require('../models'),
errors = require('../errors'),
utils = require('./utils'),
pipeline = require('../utils/pipeline'),
apiUtils = require('./utils'),
models = require('../models'),
errors = require('../errors'),
i18n = require('../i18n'),
docName = 'clients',
clients;
@ -36,12 +35,12 @@ clients = {
function doQuery(options) {
// only User Agent (type = `ua`) clients are available at the moment.
options.data = _.extend(options.data, {type: 'ua'});
return dataProvider.Client.findOne(options.data, _.omit(options, ['data']));
return models.Client.findOne(options.data, _.omit(options, ['data']));
}
// Push all of our tasks into a `tasks` array in the correct order
tasks = [
utils.validate(docName, {attrs: attrs}),
apiUtils.validate(docName, {attrs: attrs}),
// TODO: add permissions
// utils.handlePublicPermissions(docName, 'read'),
doQuery

View File

@ -1,13 +1,12 @@
// # Configuration API
// RESTful API for browsing the configuration
var _ = require('lodash'),
var Promise = require('bluebird'),
_ = require('lodash'),
apiUtils = require('../utils'),
models = require('../models'),
config = require('../config'),
settingsCache = require('../settings/cache'),
ghostVersion = require('../utils/ghost-version'),
models = require('../models'),
Promise = require('bluebird'),
utils = require('../utils'),
configuration;
function fetchAvailableTimezones() {
@ -36,7 +35,7 @@ function getBaseConfig() {
return {
useGravatar: !config.isPrivacyDisabled('useGravatar'),
publicAPI: config.get('publicAPI') === true,
blogUrl: utils.url.urlFor('home', true),
blogUrl: apiUtils.url.urlFor('home', true),
blogTitle: settingsCache.get('title'),
routeKeywords: config.get('routeKeywords'),
clientExtensions: config.get('clientExtensions')

View File

@ -1,17 +1,17 @@
// # DB API
// API for DB operations
var Promise = require('bluebird'),
path = require('path'),
fs = require('fs'),
pipeline = require('../utils/pipeline'),
apiUtils = require('./utils'),
exporter = require('../data/export'),
importer = require('../data/importer'),
backupDatabase = require('../data/db/backup'),
models = require('../models'),
errors = require('../errors'),
utils = require('./utils'),
path = require('path'),
fs = require('fs'),
utilsUrl = require('../utils/url'),
config = require('../config'),
pipeline = require('../utils/pipeline'),
errors = require('../errors'),
utilsUrl = require('../utils/url'),
docName = 'db',
db;
@ -67,7 +67,7 @@ db = {
}
tasks = [
utils.handlePermissions(docName, 'exportContent'),
apiUtils.handlePermissions(docName, 'exportContent'),
exportContent
];
@ -94,7 +94,7 @@ db = {
}
tasks = [
utils.handlePermissions(docName, 'importContent'),
apiUtils.handlePermissions(docName, 'importContent'),
importContent
];
@ -129,7 +129,7 @@ db = {
}
tasks = [
utils.handlePermissions(docName, 'deleteAllContent'),
apiUtils.handlePermissions(docName, 'deleteAllContent'),
backupDatabase,
deleteContent
];

View File

@ -1,15 +1,15 @@
var _ = require('lodash'),
Promise = require('bluebird'),
var Promise = require('bluebird'),
_ = require('lodash'),
pipeline = require('../utils/pipeline'),
dataProvider = require('../models'),
settings = require('./settings'),
mail = require('./../mail'),
apiMail = require('./mail'),
globalUtils = require('../utils'),
utils = require('./utils'),
apiUtils = require('./utils'),
models = require('../models'),
errors = require('../errors'),
logging = require('../logging'),
i18n = require('../i18n'),
logging = require('../logging'),
mailAPI = require('./mail'),
settingsAPI = require('./settings'),
docName = 'invites',
allowedIncludes = ['created_by', 'updated_by'],
invites;
@ -19,13 +19,13 @@ invites = {
var tasks;
function modelQuery(options) {
return dataProvider.Invite.findPage(options);
return models.Invite.findPage(options);
}
tasks = [
utils.validate(docName, {opts: utils.browseDefaultOptions}),
utils.handlePublicPermissions(docName, 'browse'),
utils.convertOptions(allowedIncludes),
apiUtils.validate(docName, {opts: apiUtils.browseDefaultOptions}),
apiUtils.handlePublicPermissions(docName, 'browse'),
apiUtils.convertOptions(allowedIncludes),
modelQuery
];
@ -37,13 +37,13 @@ invites = {
tasks;
function modelQuery(options) {
return dataProvider.Invite.findOne(options.data, _.omit(options, ['data']));
return models.Invite.findOne(options.data, _.omit(options, ['data']));
}
tasks = [
utils.validate(docName, {attrs: attrs}),
utils.handlePublicPermissions(docName, 'read'),
utils.convertOptions(allowedIncludes),
apiUtils.validate(docName, {attrs: attrs}),
apiUtils.handlePublicPermissions(docName, 'read'),
apiUtils.convertOptions(allowedIncludes),
modelQuery
];
@ -61,7 +61,7 @@ invites = {
var tasks;
function modelQuery(options) {
return dataProvider.Invite.findOne({id: options.id}, _.omit(options, ['data']))
return models.Invite.findOne({id: options.id}, _.omit(options, ['data']))
.then(function (invite) {
if (!invite) {
throw new errors.NotFoundError({message: i18n.t('errors.api.invites.inviteNotFound')});
@ -72,9 +72,9 @@ invites = {
}
tasks = [
utils.validate(docName, {opts: utils.idDefaultOptions}),
utils.handlePermissions(docName, 'destroy'),
utils.convertOptions(allowedIncludes),
apiUtils.validate(docName, {opts: apiUtils.idDefaultOptions}),
apiUtils.handlePermissions(docName, 'destroy'),
apiUtils.convertOptions(allowedIncludes),
modelQuery
];
@ -90,11 +90,11 @@ invites = {
function addInvite(options) {
var data = options.data;
return dataProvider.Invite.add(data.invites[0], _.omit(options, 'data'))
return models.Invite.add(data.invites[0], _.omit(options, 'data'))
.then(function (_invite) {
invite = _invite;
return settings.read({key: 'title'});
return settingsAPI.read({key: 'title'});
})
.then(function (response) {
var adminUrl = globalUtils.url.urlFor('admin', true);
@ -124,10 +124,10 @@ invites = {
}]
};
return apiMail.send(payload, {context: {internal: true}});
return mailAPI.send(payload, {context: {internal: true}});
}).then(function () {
options.id = invite.id;
return dataProvider.Invite.edit({status: 'sent'}, options);
return models.Invite.edit({status: 'sent'}, options);
}).then(function () {
invite.set('status', 'sent');
var inviteAsJSON = invite.toJSON();
@ -146,7 +146,7 @@ invites = {
function destroyOldInvite(options) {
var data = options.data;
return dataProvider.Invite.findOne({email: data.invites[0].email}, _.omit(options, 'data'))
return models.Invite.findOne({email: data.invites[0].email}, _.omit(options, 'data'))
.then(function (invite) {
if (!invite) {
return Promise.resolve(options);
@ -173,7 +173,7 @@ invites = {
// We cannot use permissible because we don't have access to the role_id!!!
// Adding a permissible function to the invite model, doesn't give us much context of the invite we would like to add
// As we are looking forward to replace the permission system completely, we do not add a hack here
return dataProvider.Role.findOne({id: options.data.invites[0].role_id}).then(function (roleToInvite) {
return models.Role.findOne({id: options.data.invites[0].role_id}).then(function (roleToInvite) {
if (!roleToInvite) {
return Promise.reject(new errors.NotFoundError({message: i18n.t('errors.api.invites.roleNotFound')}));
}
@ -202,7 +202,7 @@ invites = {
}
function checkIfUserExists(options) {
return dataProvider.User.findOne({email: options.data.invites[0].email}, options)
return models.User.findOne({email: options.data.invites[0].email}, options)
.then(function (user) {
if (user) {
return Promise.reject(new errors.ValidationError({
@ -215,7 +215,7 @@ invites = {
}
function fetchLoggedInUser(options) {
return dataProvider.User.findOne({id: loggedInUser}, _.merge({}, options, {include: ['roles']}))
return models.User.findOne({id: loggedInUser}, _.merge({}, options, {include: ['roles']}))
.then(function (user) {
if (!user) {
return Promise.reject(new errors.NotFoundError({message: i18n.t('errors.api.users.userNotFound')}));
@ -227,9 +227,9 @@ invites = {
}
tasks = [
utils.validate(docName, {opts: ['email']}),
utils.handlePermissions(docName, 'add'),
utils.convertOptions(allowedIncludes),
apiUtils.validate(docName, {opts: ['email']}),
apiUtils.handlePermissions(docName, 'add'),
apiUtils.convertOptions(allowedIncludes),
fetchLoggedInUser,
validation,
checkIfUserExists,

View File

@ -3,12 +3,12 @@
var Promise = require('bluebird'),
pipeline = require('../utils/pipeline'),
apiUtils = require('./utils'),
models = require('../models'),
errors = require('../errors'),
mail = require('../mail'),
Models = require('../models'),
utils = require('./utils'),
notifications = require('./notifications'),
i18n = require('../i18n'),
mail = require('../mail'),
notificationsAPI = require('./notifications'),
docName = 'mail',
mailer,
apiMail;
@ -23,7 +23,7 @@ function sendMail(object) {
return mailer.send(object.mail[0].message).catch(function (err) {
if (mailer.state.usingDirect) {
notifications.add(
notificationsAPI.add(
{notifications: [{
type: 'warn',
message: [
@ -84,7 +84,7 @@ apiMail = {
}
tasks = [
utils.handlePermissions(docName, 'send'),
apiUtils.handlePermissions(docName, 'send'),
send,
formatResponse
];
@ -108,7 +108,7 @@ apiMail = {
*/
function modelQuery() {
return Models.User.findOne({id: options.context.user});
return models.User.findOne({id: options.context.user});
}
/**

View File

@ -3,14 +3,13 @@
var Promise = require('bluebird'),
_ = require('lodash'),
ObjectId = require('bson-objectid'),
permissions = require('../permissions'),
errors = require('../errors'),
settings = require('./settings'),
utils = require('./utils'),
pipeline = require('../utils/pipeline'),
permissions = require('../permissions'),
canThis = permissions.canThis,
apiUtils = require('./utils'),
errors = require('../errors'),
i18n = require('../i18n'),
settingsAPI = require('./settings'),
// Holds the persistent notifications
notificationsStore = [],
notifications;
@ -108,7 +107,7 @@ notifications = {
}
tasks = [
utils.validate('notifications'),
apiUtils.validate('notifications'),
handlePermissions,
saveNotifications
];
@ -135,10 +134,10 @@ notifications = {
*/
function markAsSeen(notification) {
var context = {internal: true};
return settings.read({key: 'seen_notifications', context: context}).then(function then(response) {
return settingsAPI.read({key: 'seen_notifications', context: context}).then(function then(response) {
var seenNotifications = JSON.parse(response.settings[0].value);
seenNotifications = _.uniqBy(seenNotifications.concat([notification.id]));
return settings.edit({settings: [{key: 'seen_notifications', value: seenNotifications}]}, {context: context});
return settingsAPI.edit({settings: [{key: 'seen_notifications', value: seenNotifications}]}, {context: context});
});
}
@ -181,7 +180,7 @@ notifications = {
}
tasks = [
utils.validate('notifications', {opts: utils.idDefaultOptions}),
apiUtils.validate('notifications', {opts: apiUtils.idDefaultOptions}),
handlePermissions,
destroyNotification
];

View File

@ -2,12 +2,11 @@
// RESTful API for the Post resource
var Promise = require('bluebird'),
_ = require('lodash'),
dataProvider = require('../models'),
errors = require('../errors'),
utils = require('./utils'),
pipeline = require('../utils/pipeline'),
apiUtils = require('./utils'),
models = require('../models'),
errors = require('../errors'),
i18n = require('../i18n'),
docName = 'posts',
allowedIncludes = [
'created_by', 'updated_by', 'published_by', 'author', 'tags', 'fields',
@ -46,7 +45,7 @@ posts = {
if (options && options.context && (options.context.user || options.context.internal)) {
extraOptions.push('staticPages');
}
permittedOptions = utils.browseDefaultOptions.concat(extraOptions);
permittedOptions = apiUtils.browseDefaultOptions.concat(extraOptions);
/**
* ### Model Query
@ -55,14 +54,14 @@ posts = {
* @returns {Object} options
*/
function modelQuery(options) {
return dataProvider.Post.findPage(options);
return models.Post.findPage(options);
}
// Push all of our tasks into a `tasks` array in the correct order
tasks = [
utils.validate(docName, {opts: permittedOptions}),
utils.handlePublicPermissions(docName, 'browse'),
utils.convertOptions(allowedIncludes, dataProvider.Post.allowedFormats),
apiUtils.validate(docName, {opts: permittedOptions}),
apiUtils.handlePublicPermissions(docName, 'browse'),
apiUtils.convertOptions(allowedIncludes, models.Post.allowedFormats),
modelQuery
];
@ -89,14 +88,14 @@ posts = {
* @returns {Object} options
*/
function modelQuery(options) {
return dataProvider.Post.findOne(options.data, _.omit(options, ['data']));
return models.Post.findOne(options.data, _.omit(options, ['data']));
}
// Push all of our tasks into a `tasks` array in the correct order
tasks = [
utils.validate(docName, {attrs: attrs, opts: options.opts || []}),
utils.handlePublicPermissions(docName, 'read'),
utils.convertOptions(allowedIncludes, dataProvider.Post.allowedFormats),
apiUtils.validate(docName, {attrs: attrs, opts: options.opts || []}),
apiUtils.handlePublicPermissions(docName, 'read'),
apiUtils.convertOptions(allowedIncludes, models.Post.allowedFormats),
modelQuery
];
@ -130,14 +129,14 @@ posts = {
* @returns {Object} options
*/
function modelQuery(options) {
return dataProvider.Post.edit(options.data.posts[0], _.omit(options, ['data']));
return models.Post.edit(options.data.posts[0], _.omit(options, ['data']));
}
// Push all of our tasks into a `tasks` array in the correct order
tasks = [
utils.validate(docName, {opts: utils.idDefaultOptions.concat(options.opts || [])}),
utils.handlePermissions(docName, 'edit'),
utils.convertOptions(allowedIncludes),
apiUtils.validate(docName, {opts: apiUtils.idDefaultOptions.concat(options.opts || [])}),
apiUtils.handlePermissions(docName, 'edit'),
apiUtils.convertOptions(allowedIncludes),
modelQuery
];
@ -177,14 +176,14 @@ posts = {
* @returns {Object} options
*/
function modelQuery(options) {
return dataProvider.Post.add(options.data.posts[0], _.omit(options, ['data']));
return models.Post.add(options.data.posts[0], _.omit(options, ['data']));
}
// Push all of our tasks into a `tasks` array in the correct order
tasks = [
utils.validate(docName),
utils.handlePermissions(docName, 'add'),
utils.convertOptions(allowedIncludes),
apiUtils.validate(docName),
apiUtils.handlePermissions(docName, 'add'),
apiUtils.convertOptions(allowedIncludes),
modelQuery
];
@ -216,7 +215,7 @@ posts = {
* @param {Object} options
*/
function deletePost(options) {
var Post = dataProvider.Post,
var Post = models.Post,
data = _.defaults({status: 'all'}, options),
fetchOpts = _.defaults({require: true, columns: 'id'}, options);
@ -229,9 +228,9 @@ posts = {
// Push all of our tasks into a `tasks` array in the correct order
tasks = [
utils.validate(docName, {opts: utils.idDefaultOptions}),
utils.handlePermissions(docName, 'destroy'),
utils.convertOptions(allowedIncludes),
apiUtils.validate(docName, {opts: apiUtils.idDefaultOptions}),
apiUtils.handlePermissions(docName, 'destroy'),
apiUtils.convertOptions(allowedIncludes),
deletePost
];

View File

@ -1,10 +1,10 @@
// # Roles API
// RESTful API for the Role resource
var Promise = require('bluebird'),
canThis = require('../permissions').canThis,
dataProvider = require('../models'),
pipeline = require('../utils/pipeline'),
utils = require('./utils'),
apiUtils = require('./utils'),
canThis = require('../permissions').canThis,
models = require('../models'),
docName = 'roles',
roles;
@ -39,13 +39,13 @@ roles = {
* @returns {Object} options
*/
function modelQuery(options) {
return dataProvider.Role.findAll(options);
return models.Role.findAll(options);
}
// Push all of our tasks into a `tasks` array in the correct order
tasks = [
utils.validate(docName, {opts: permittedOptions}),
utils.handlePermissions(docName, 'browse'),
apiUtils.validate(docName, {opts: permittedOptions}),
apiUtils.handlePermissions(docName, 'browse'),
modelQuery
];

View File

@ -1,13 +1,13 @@
var _ = require('lodash'),
Promise = require('bluebird'),
var Promise = require('bluebird'),
_ = require('lodash'),
moment = require('moment'),
pipeline = require('../utils/pipeline'),
apiUtils = require('./utils'),
models = require('../models'),
config = require('../config'),
pipeline = require(config.get('paths').corePath + '/server/utils/pipeline'),
dataProvider = require(config.get('paths').corePath + '/server/models'),
i18n = require(config.get('paths').corePath + '/server/i18n'),
errors = require(config.get('paths').corePath + '/server/errors'),
apiPosts = require(config.get('paths').corePath + '/server/api/posts'),
utils = require('./utils');
errors = require('../errors'),
i18n = require('../i18n'),
postsAPI = require('../api/posts');
/**
* Publish a scheduled post
@ -35,18 +35,18 @@ exports.publishPost = function publishPost(object, options) {
options.context = {internal: true};
return pipeline([
utils.validate('posts', {opts: utils.idDefaultOptions}),
apiUtils.validate('posts', {opts: apiUtils.idDefaultOptions}),
function (cleanOptions) {
cleanOptions.status = 'scheduled';
return dataProvider.Base.transaction(function (transacting) {
return models.Base.transaction(function (transacting) {
cleanOptions.transacting = transacting;
cleanOptions.forUpdate = true;
// CASE: extend allowed options, see api/utils.js
cleanOptions.opts = ['forUpdate', 'transacting'];
return apiPosts.read(cleanOptions)
return postsAPI.read(cleanOptions)
.then(function (result) {
post = result.posts[0];
publishedAtMoment = moment(post.published_at);
@ -59,7 +59,7 @@ exports.publishPost = function publishPost(object, options) {
return Promise.reject(new errors.NotFoundError({message: i18n.t('errors.api.job.publishInThePast')}));
}
return apiPosts.edit({
return postsAPI.edit({
posts: [{status: 'published'}]},
_.pick(cleanOptions, ['context', 'id', 'transacting', 'forUpdate', 'opts'])
);
@ -78,7 +78,7 @@ exports.getScheduledPosts = function readPosts(options) {
options.context = {internal: true};
return pipeline([
utils.validate('posts', {opts: ['from', 'to']}),
apiUtils.validate('posts', {opts: ['from', 'to']}),
function (cleanOptions) {
cleanOptions.filter = 'status:scheduled';
cleanOptions.columns = ['id', 'published_at', 'created_at'];
@ -91,7 +91,7 @@ exports.getScheduledPosts = function readPosts(options) {
cleanOptions.filter += '+created_at:<=\'' + moment(cleanOptions.to).format('YYYY-MM-DD HH:mm:ss') + '\'';
}
return dataProvider.Post.findAll(cleanOptions)
return models.Post.findAll(cleanOptions)
.then(function (result) {
return Promise.resolve({posts: result.models});
});

View File

@ -1,19 +1,15 @@
// # Settings API
// RESTful API for the Setting resource
var _ = require('lodash'),
dataProvider = require('../models'),
Promise = require('bluebird'),
var Promise = require('bluebird'),
_ = require('lodash'),
models = require('../models'),
canThis = require('../permissions').canThis,
apiUtils = require('./utils'),
errors = require('../errors'),
utils = require('./utils'),
i18n = require('../i18n'),
settingsCache = require('../settings/cache'),
docName = 'settings',
settings,
settingsCache = require('../settings/cache'),
settingsFilter,
settingsResult,
canEditAllSettings,
@ -223,9 +219,9 @@ settings = {
});
return canEditAllSettings(object.settings, options).then(function () {
return utils.checkObject(object, docName).then(function (checkedData) {
return apiUtils.checkObject(object, docName).then(function (checkedData) {
options.user = self.user;
return dataProvider.Settings.edit(checkedData.settings, options);
return models.Settings.edit(checkedData.settings, options);
}).then(function (settingsModelsArray) {
// Instead of a standard bookshelf collection, Settings.edit returns an array of Settings Models.
// We convert this to JSON, by calling toJSON on each Model (using invokeMap for ease)

View File

@ -1,7 +1,7 @@
// # Slack API
// API for sending Test Notifications to Slack
var events = require('../events'),
Promise = require('bluebird'),
var Promise = require('bluebird'),
events = require('../events'),
slack;
/**

View File

@ -1,13 +1,12 @@
// # Slug API
// RESTful API for the Slug resource
var dataProvider = require('../models'),
errors = require('../errors'),
Promise = require('bluebird'),
var Promise = require('bluebird'),
pipeline = require('../utils/pipeline'),
utils = require('./utils'),
apiUtils = require('./utils'),
models = require('../models'),
errors = require('../errors'),
i18n = require('../i18n'),
docName = 'slugs',
slugs,
allowedTypes;
@ -32,10 +31,10 @@ slugs = {
// `allowedTypes` is used to define allowed slug types and map them against its model class counterpart
allowedTypes = {
post: dataProvider.Post,
tag: dataProvider.Tag,
user: dataProvider.User,
app: dataProvider.App
post: models.Post,
tag: models.Tag,
user: models.User,
app: models.App
};
/**
@ -58,13 +57,13 @@ slugs = {
* @returns {Object} options
*/
function modelQuery(options) {
return dataProvider.Base.Model.generateSlug(allowedTypes[options.type], options.data.name, {status: 'all'});
return models.Base.Model.generateSlug(allowedTypes[options.type], options.data.name, {status: 'all'});
}
// Push all of our tasks into a `tasks` array in the correct order
tasks = [
utils.validate(docName, {opts: opts, attrs: attrs}),
utils.handlePermissions(docName, 'generate'),
apiUtils.validate(docName, {opts: opts, attrs: attrs}),
apiUtils.handlePermissions(docName, 'generate'),
checkAllowedTypes,
modelQuery
];

View File

@ -3,13 +3,12 @@
var Promise = require('bluebird'),
_ = require('lodash'),
fs = require('fs'),
dataProvider = require('../models'),
errors = require('../errors'),
utils = require('./utils'),
serverUtils = require('../utils'),
pipeline = require('../utils/pipeline'),
globalUtils = require('../utils'),
apiUtils = require('./utils'),
models = require('../models'),
errors = require('../errors'),
i18n = require('../i18n'),
docName = 'subscribers',
subscribers;
@ -34,13 +33,13 @@ subscribers = {
* @returns {Object} options
*/
function doQuery(options) {
return dataProvider.Subscriber.findPage(options);
return models.Subscriber.findPage(options);
}
// Push all of our tasks into a `tasks` array in the correct order
tasks = [
utils.validate(docName, {opts: utils.browseDefaultOptions}),
utils.handlePermissions(docName, 'browse'),
apiUtils.validate(docName, {opts: apiUtils.browseDefaultOptions}),
apiUtils.handlePermissions(docName, 'browse'),
doQuery
];
@ -64,13 +63,13 @@ subscribers = {
* @returns {Object} options
*/
function doQuery(options) {
return dataProvider.Subscriber.findOne(options.data, _.omit(options, ['data']));
return models.Subscriber.findOne(options.data, _.omit(options, ['data']));
}
// Push all of our tasks into a `tasks` array in the correct order
tasks = [
utils.validate(docName, {attrs: attrs}),
utils.handlePermissions(docName, 'read'),
apiUtils.validate(docName, {attrs: attrs}),
apiUtils.handlePermissions(docName, 'read'),
doQuery
];
@ -99,7 +98,7 @@ subscribers = {
* @returns {Object} options
*/
function doQuery(options) {
return dataProvider.Subscriber.getByEmail(options.data.subscribers[0].email)
return models.Subscriber.getByEmail(options.data.subscribers[0].email)
.then(function (subscriber) {
if (subscriber && options.context.external) {
// we don't expose this information
@ -108,7 +107,7 @@ subscribers = {
return Promise.reject(new errors.ValidationError({message: i18n.t('errors.api.subscribers.subscriberAlreadyExists')}));
}
return dataProvider.Subscriber.add(options.data.subscribers[0], _.omit(options, ['data'])).catch(function (error) {
return models.Subscriber.add(options.data.subscribers[0], _.omit(options, ['data'])).catch(function (error) {
if (error.code && error.message.toLowerCase().indexOf('unique') !== -1) {
return Promise.reject(new errors.ValidationError({message: i18n.t('errors.api.subscribers.subscriberAlreadyExists')}));
}
@ -120,8 +119,8 @@ subscribers = {
// Push all of our tasks into a `tasks` array in the correct order
tasks = [
utils.validate(docName),
utils.handlePermissions(docName, 'add'),
apiUtils.validate(docName),
apiUtils.handlePermissions(docName, 'add'),
doQuery
];
@ -149,13 +148,13 @@ subscribers = {
* @returns {Object} options
*/
function doQuery(options) {
return dataProvider.Subscriber.edit(options.data.subscribers[0], _.omit(options, ['data']));
return models.Subscriber.edit(options.data.subscribers[0], _.omit(options, ['data']));
}
// Push all of our tasks into a `tasks` array in the correct order
tasks = [
utils.validate(docName, {opts: utils.idDefaultOptions}),
utils.handlePermissions(docName, 'edit'),
apiUtils.validate(docName, {opts: apiUtils.idDefaultOptions}),
apiUtils.handlePermissions(docName, 'edit'),
doQuery
];
@ -187,13 +186,13 @@ subscribers = {
* @param {Object} options
*/
function doQuery(options) {
return dataProvider.Subscriber.destroy(options).return(null);
return models.Subscriber.destroy(options).return(null);
}
// Push all of our tasks into a `tasks` array in the correct order
tasks = [
utils.validate(docName, {opts: utils.idDefaultOptions}),
utils.handlePermissions(docName, 'destroy'),
apiUtils.validate(docName, {opts: apiUtils.idDefaultOptions}),
apiUtils.handlePermissions(docName, 'destroy'),
doQuery
];
@ -239,7 +238,7 @@ subscribers = {
// Export data, otherwise send error 500
function exportSubscribers() {
return dataProvider.Subscriber.findAll(options).then(function (data) {
return models.Subscriber.findAll(options).then(function (data) {
return formatCSV(data.toJSON(options));
}).catch(function (err) {
return Promise.reject(new errors.GhostError({err: err}));
@ -247,7 +246,7 @@ subscribers = {
}
tasks = [
utils.handlePermissions(docName, 'browse'),
apiUtils.handlePermissions(docName, 'browse'),
exportSubscribers
];
@ -272,7 +271,7 @@ subscribers = {
invalid = 0,
duplicates = 0;
return serverUtils.readCSV({
return globalUtils.readCSV({
path: filePath,
columnsToExtract: [{name: 'email', lookup: /email/i}]
}).then(function (result) {
@ -309,7 +308,7 @@ subscribers = {
}
tasks = [
utils.handlePermissions(docName, 'add'),
apiUtils.handlePermissions(docName, 'add'),
importCSV
];

View File

@ -2,12 +2,11 @@
// RESTful API for the Tag resource
var Promise = require('bluebird'),
_ = require('lodash'),
dataProvider = require('../models'),
errors = require('../errors'),
utils = require('./utils'),
pipeline = require('../utils/pipeline'),
apiUtils = require('./utils'),
models = require('../models'),
errors = require('../errors'),
i18n = require('../i18n'),
docName = 'tags',
allowedIncludes = ['count.posts'],
tags;
@ -33,14 +32,14 @@ tags = {
* @returns {Object} options
*/
function doQuery(options) {
return dataProvider.Tag.findPage(options);
return models.Tag.findPage(options);
}
// Push all of our tasks into a `tasks` array in the correct order
tasks = [
utils.validate(docName, {opts: utils.browseDefaultOptions}),
utils.handlePublicPermissions(docName, 'browse'),
utils.convertOptions(allowedIncludes),
apiUtils.validate(docName, {opts: apiUtils.browseDefaultOptions}),
apiUtils.handlePublicPermissions(docName, 'browse'),
apiUtils.convertOptions(allowedIncludes),
doQuery
];
@ -64,14 +63,14 @@ tags = {
* @returns {Object} options
*/
function doQuery(options) {
return dataProvider.Tag.findOne(options.data, _.omit(options, ['data']));
return models.Tag.findOne(options.data, _.omit(options, ['data']));
}
// Push all of our tasks into a `tasks` array in the correct order
tasks = [
utils.validate(docName, {attrs: attrs}),
utils.handlePublicPermissions(docName, 'read'),
utils.convertOptions(allowedIncludes),
apiUtils.validate(docName, {attrs: attrs}),
apiUtils.handlePublicPermissions(docName, 'read'),
apiUtils.convertOptions(allowedIncludes),
doQuery
];
@ -100,14 +99,14 @@ tags = {
* @returns {Object} options
*/
function doQuery(options) {
return dataProvider.Tag.add(options.data.tags[0], _.omit(options, ['data']));
return models.Tag.add(options.data.tags[0], _.omit(options, ['data']));
}
// Push all of our tasks into a `tasks` array in the correct order
tasks = [
utils.validate(docName),
utils.handlePermissions(docName, 'add'),
utils.convertOptions(allowedIncludes),
apiUtils.validate(docName),
apiUtils.handlePermissions(docName, 'add'),
apiUtils.convertOptions(allowedIncludes),
doQuery
];
@ -136,14 +135,14 @@ tags = {
* @returns {Object} options
*/
function doQuery(options) {
return dataProvider.Tag.edit(options.data.tags[0], _.omit(options, ['data']));
return models.Tag.edit(options.data.tags[0], _.omit(options, ['data']));
}
// Push all of our tasks into a `tasks` array in the correct order
tasks = [
utils.validate(docName, {opts: utils.idDefaultOptions}),
utils.handlePermissions(docName, 'edit'),
utils.convertOptions(allowedIncludes),
apiUtils.validate(docName, {opts: apiUtils.idDefaultOptions}),
apiUtils.handlePermissions(docName, 'edit'),
apiUtils.convertOptions(allowedIncludes),
doQuery
];
@ -175,14 +174,14 @@ tags = {
* @param {Object} options
*/
function deleteTag(options) {
return dataProvider.Tag.destroy(options).return(null);
return models.Tag.destroy(options).return(null);
}
// Push all of our tasks into a `tasks` array in the correct order
tasks = [
utils.validate(docName, {opts: utils.idDefaultOptions}),
utils.handlePermissions(docName, 'destroy'),
utils.convertOptions(allowedIncludes),
apiUtils.validate(docName, {opts: apiUtils.idDefaultOptions}),
apiUtils.handlePermissions(docName, 'destroy'),
apiUtils.convertOptions(allowedIncludes),
deleteTag
];

View File

@ -3,11 +3,11 @@
var debug = require('ghost-ignition').debug('api:themes'),
Promise = require('bluebird'),
fs = require('fs-extra'),
apiUtils = require('./utils'),
errors = require('../errors'),
events = require('../events'),
logging = require('../logging'),
apiUtils = require('./utils'),
i18n = require('../i18n'),
logging = require('../logging'),
settingsModel = require('../models/settings').Settings,
settingsCache = require('../settings/cache'),
themeUtils = require('../themes'),

View File

@ -2,12 +2,12 @@
// RESTful API for the User resource
var Promise = require('bluebird'),
_ = require('lodash'),
dataProvider = require('../models'),
pipeline = require('../utils/pipeline'),
apiUtils = require('./utils'),
canThis = require('../permissions').canThis,
models = require('../models'),
errors = require('../errors'),
events = require('../events'),
utils = require('./utils'),
pipeline = require('../utils/pipeline'),
i18n = require('../i18n'),
docName = 'users',
// TODO: implement created_by, updated_by
@ -28,7 +28,7 @@ users = {
*/
browse: function browse(options) {
var extraOptions = ['status'],
permittedOptions = utils.browseDefaultOptions.concat(extraOptions),
permittedOptions = apiUtils.browseDefaultOptions.concat(extraOptions),
tasks;
/**
@ -38,14 +38,14 @@ users = {
* @returns {Object} options
*/
function doQuery(options) {
return dataProvider.User.findPage(options);
return models.User.findPage(options);
}
// Push all of our tasks into a `tasks` array in the correct order
tasks = [
utils.validate(docName, {opts: permittedOptions}),
utils.handlePublicPermissions(docName, 'browse'),
utils.convertOptions(allowedIncludes),
apiUtils.validate(docName, {opts: permittedOptions}),
apiUtils.handlePublicPermissions(docName, 'browse'),
apiUtils.convertOptions(allowedIncludes),
doQuery
];
@ -75,14 +75,14 @@ users = {
* @returns {Object} options
*/
function doQuery(options) {
return dataProvider.User.findOne(options.data, _.omit(options, ['data']));
return models.User.findOne(options.data, _.omit(options, ['data']));
}
// Push all of our tasks into a `tasks` array in the correct order
tasks = [
utils.validate(docName, {attrs: attrs}),
utils.handlePublicPermissions(docName, 'read'),
utils.convertOptions(allowedIncludes),
apiUtils.validate(docName, {attrs: attrs}),
apiUtils.handlePublicPermissions(docName, 'read'),
apiUtils.convertOptions(allowedIncludes),
doQuery
];
@ -108,7 +108,7 @@ users = {
*/
edit: function edit(object, options) {
var extraOptions = ['editRoles'],
permittedOptions = extraOptions.concat(utils.idDefaultOptions),
permittedOptions = extraOptions.concat(apiUtils.idDefaultOptions),
tasks;
if (object.users && object.users[0] && object.users[0].roles && object.users[0].roles[0]) {
@ -137,7 +137,7 @@ users = {
return canThis(options.context).edit.user(options.id).then(function () {
// CASE: can't edit my own status to inactive or locked
if (options.id === options.context.user) {
if (dataProvider.User.inactiveStates.indexOf(options.data.users[0].status) !== -1) {
if (models.User.inactiveStates.indexOf(options.data.users[0].status) !== -1) {
return Promise.reject(new errors.NoPermissionError({
message: i18n.t('errors.api.users.cannotChangeStatus')
}));
@ -154,7 +154,7 @@ users = {
roleId = role.id || role,
editedUserId = options.id;
return dataProvider.User.findOne(
return models.User.findOne(
{id: options.context.user, status: 'all'}, {include: ['roles']}
).then(function (contextUser) {
var contextRoleId = contextUser.related('roles').toJSON(options)[0].id;
@ -165,7 +165,7 @@ users = {
}));
}
return dataProvider.User.findOne({role: 'Owner'}).then(function (owner) {
return models.User.findOne({role: 'Owner'}).then(function (owner) {
if (contextUser.id !== owner.id) {
if (editedUserId === owner.id) {
if (owner.related('roles').at(0).id !== roleId) {
@ -198,14 +198,14 @@ users = {
* @returns {Object} options
*/
function doQuery(options) {
return dataProvider.User.edit(options.data.users[0], _.omit(options, ['data']));
return models.User.edit(options.data.users[0], _.omit(options, ['data']));
}
// Push all of our tasks into a `tasks` array in the correct order
tasks = [
utils.validate(docName, {opts: permittedOptions}),
apiUtils.validate(docName, {opts: permittedOptions}),
handlePermissions,
utils.convertOptions(allowedIncludes),
apiUtils.convertOptions(allowedIncludes),
doQuery
];
@ -250,15 +250,15 @@ users = {
* @param {Object} options
*/
function deleteUser(options) {
return dataProvider.Base.transaction(function (t) {
return models.Base.transaction(function (t) {
options.transacting = t;
return Promise.all([
dataProvider.Accesstoken.destroyByUser(options),
dataProvider.Refreshtoken.destroyByUser(options),
dataProvider.Post.destroyByAuthor(options)
models.Accesstoken.destroyByUser(options),
models.Refreshtoken.destroyByUser(options),
models.Post.destroyByAuthor(options)
]).then(function () {
return dataProvider.User.destroy(options);
return models.User.destroy(options);
}).return(null);
}).catch(function (err) {
return Promise.reject(new errors.NoPermissionError({
@ -269,9 +269,9 @@ users = {
// Push all of our tasks into a `tasks` array in the correct order
tasks = [
utils.validate(docName, {opts: utils.idDefaultOptions}),
apiUtils.validate(docName, {opts: apiUtils.idDefaultOptions}),
handlePermissions,
utils.convertOptions(allowedIncludes),
apiUtils.convertOptions(allowedIncludes),
deleteUser
];
@ -289,7 +289,7 @@ users = {
var tasks;
function validateRequest() {
return utils.validate('password')(object, options)
return apiUtils.validate('password')(object, options)
.then(function (options) {
var data = options.data.password[0];
@ -327,7 +327,7 @@ users = {
* @returns {Object} options
*/
function doQuery(options) {
return dataProvider.User.changePassword(
return models.User.changePassword(
options.data.password[0],
_.omit(options, ['data'])
);
@ -337,7 +337,7 @@ users = {
tasks = [
validateRequest,
handlePermissions,
utils.convertOptions(allowedIncludes),
apiUtils.convertOptions(allowedIncludes),
doQuery
];
@ -363,7 +363,7 @@ users = {
* @returns {Object} options
*/
function handlePermissions(options) {
return dataProvider.Role.findOne({name: 'Owner'}).then(function (ownerRole) {
return models.Role.findOne({name: 'Owner'}).then(function (ownerRole) {
return canThis(options.context).assign.role(ownerRole);
}).then(function () {
return options;
@ -377,14 +377,14 @@ users = {
* @returns {Object} options
*/
function doQuery(options) {
return dataProvider.User.transferOwnership(options.data.owner[0], _.omit(options, ['data']));
return models.User.transferOwnership(options.data.owner[0], _.omit(options, ['data']));
}
// Push all of our tasks into a `tasks` array in the correct order
tasks = [
utils.validate('owner'),
apiUtils.validate('owner'),
handlePermissions,
utils.convertOptions(allowedIncludes),
apiUtils.convertOptions(allowedIncludes),
doQuery
];

View File

@ -3,11 +3,10 @@
var Promise = require('bluebird'),
_ = require('lodash'),
path = require('path'),
errors = require('../errors'),
permissions = require('../permissions'),
validation = require('../data/validation'),
errors = require('../errors'),
i18n = require('../i18n'),
utils;
utils = {

View File

@ -14,6 +14,7 @@ var path = require('path'),
function controller(req, res, next) {
var templateName = 'amp',
defaultTemplate = path.resolve(__dirname, 'views', templateName + '.hbs'),
view = templates.pickTemplate(templateName, defaultTemplate),
data = req.body || {};
if (res.error) {
@ -22,12 +23,14 @@ function controller(req, res, next) {
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')) {
return res.render(templates.pickTemplate(templateName, defaultTemplate), data);
// Context check:
// Our context must be ['post', 'amp'], otherwise we won't render the template
// This prevents AMP from being rendered for pages
if (_.intersection(res.locals.context, ['post', 'amp']).length < 2) {
return next();
}
return next();
return res.render(view, data);
}
function getPostData(req, res, next) {

View File

@ -11,6 +11,7 @@ var path = require('path'),
function controller(req, res) {
var templateName = 'private',
defaultTemplate = path.resolve(__dirname, 'views', templateName + '.hbs'),
view = templates.pickTemplate(templateName, defaultTemplate),
data = {};
if (res.error) {
@ -19,7 +20,7 @@ function controller(req, res) {
setResponseContext(req, res);
return res.render(templates.pickTemplate(templateName, defaultTemplate), data);
return res.render(view, data);
}
// password-protected frontend route

View File

@ -9,17 +9,18 @@ var path = require('path'),
errors = require('../../../errors'),
validator = require('../../../data/validation').validator,
templates = require('../../../controllers/frontend/templates'),
postlookup = require('../../../controllers/frontend/post-lookup'),
postLookup = require('../../../controllers/frontend/post-lookup'),
setResponseContext = require('../../../controllers/frontend/context');
function controller(req, res) {
var templateName = 'subscribe',
defaultTemplate = path.resolve(__dirname, 'views', templateName + '.hbs'),
view = templates.pickTemplate(templateName, defaultTemplate),
data = req.body;
setResponseContext(req, res);
return res.render(templates.pickTemplate(templateName, defaultTemplate), data);
return res.render(view, data);
}
/**
@ -60,7 +61,7 @@ function handleSource(req, res, next) {
delete req.body.location;
delete req.body.referrer;
postlookup(req.body.subscribed_url)
postLookup(req.body.subscribed_url)
.then(function (result) {
if (result && result.post) {
req.body.post_id = result.post.id;

View File

@ -45,6 +45,7 @@ function renderChannel(req, res, next) {
// Do final data formatting and then render
result.posts = posts;
result = formatResponse.channel(result);
setResponseContext(req, res);
debug('Rendering view: ' + view);
res.render(view, result);

View File

@ -17,16 +17,9 @@ function getImageDimensions(metaData) {
logo: getCachedImageSizeFromUrl(metaData.blog.logo.url)
};
return Promise.props(fetch).then(function (resolve) {
var imageObj = {};
imageObj = {
coverImage: resolve.coverImage,
authorImage: resolve.authorImage,
ogImage: resolve.ogImage,
logo: resolve.logo
};
return Promise
.props(fetch)
.then(function (imageObj) {
_.forEach(imageObj, function (key, value) {
if (_.has(key, 'width') && _.has(key, 'height')) {
// We have some restrictions for publisher.logo: