Fixed "no-shadow" linting error in server modules (#12287)

refs 143921948d

- Continuation of changes started in referenced commit
This commit is contained in:
naz 2020-10-20 12:02:56 +13:00 committed by GitHub
parent 38b7f8e311
commit 8ddf83f3c5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
41 changed files with 164 additions and 187 deletions

View File

@ -30,7 +30,7 @@ module.exports = function authors(options = {}) {
from = from ? parseInt(from, 10) : from;
to = to ? parseInt(to, 10) : to;
function createAuthorsList(authors) {
function createAuthorsList(authorsList) {
function processAuthor(author) {
return autolink ? templates.link({
url: urlService.getUrlByResourceId(author.id, {withSubdirectory: true}),
@ -38,7 +38,7 @@ module.exports = function authors(options = {}) {
}) : _.escape(author.name);
}
return ghostHelperUtils.visibility.filter(authors, visibility, processAuthor);
return ghostHelperUtils.visibility.filter(authorsList, visibility, processAuthor);
}
if (this.authors && this.authors.length) {

View File

@ -73,7 +73,7 @@ module.exports = function foreach(items, options) {
// For each post, if it is a post number that fits within the from and to
// send the key to execIteration to set to be added to the page
_.each(context, (_, key) => {
_.each(context, (value, key) => {
if (current < from) {
current += 1;
return;

View File

@ -15,12 +15,12 @@ function writeMetaTag(property, content, type) {
return '<meta ' + type + '="' + property + '" content="' + content + '" />';
}
function finaliseStructuredData(metaData) {
function finaliseStructuredData(meta) {
const head = [];
_.each(metaData.structuredData, function (content, property) {
_.each(meta.structuredData, function (content, property) {
if (property === 'article:tag') {
_.each(metaData.keywords, function (keyword) {
_.each(meta.keywords, function (keyword) {
if (keyword !== '') {
keyword = escapeExpression(keyword);
head.push(writeMetaTag(property,
@ -120,13 +120,13 @@ module.exports = function ghost_head(options) { // eslint-disable-line camelcase
* - it should not break anything
*/
return getMetaData(dataRoot, dataRoot)
.then(function handleMetaData(metaData) {
.then(function handleMetaData(meta) {
debug('end fetch');
if (context) {
// head is our main array that holds our meta data
if (metaData.metaDescription && metaData.metaDescription.length > 0) {
head.push('<meta name="description" content="' + escapeExpression(metaData.metaDescription) + '" />');
if (meta.metaDescription && meta.metaDescription.length > 0) {
head.push('<meta name="description" content="' + escapeExpression(meta.metaDescription) + '" />');
}
// no output in head if a publication icon is not set
@ -135,7 +135,7 @@ module.exports = function ghost_head(options) { // eslint-disable-line camelcase
}
head.push('<link rel="canonical" href="' +
escapeExpression(metaData.canonicalUrl) + '" />');
escapeExpression(meta.canonicalUrl) + '" />');
head.push('<meta name="referrer" content="' + referrerPolicy + '" />');
// don't allow indexing of preview URLs!
@ -146,27 +146,27 @@ module.exports = function ghost_head(options) { // eslint-disable-line camelcase
// show amp link in post when 1. we are not on the amp page and 2. amp is enabled
if (_.includes(context, 'post') && !_.includes(context, 'amp') && settingsCache.get('amp')) {
head.push('<link rel="amphtml" href="' +
escapeExpression(metaData.ampUrl) + '" />');
escapeExpression(meta.ampUrl) + '" />');
}
if (metaData.previousUrl) {
if (meta.previousUrl) {
head.push('<link rel="prev" href="' +
escapeExpression(metaData.previousUrl) + '" />');
escapeExpression(meta.previousUrl) + '" />');
}
if (metaData.nextUrl) {
if (meta.nextUrl) {
head.push('<link rel="next" href="' +
escapeExpression(metaData.nextUrl) + '" />');
escapeExpression(meta.nextUrl) + '" />');
}
if (!_.includes(context, 'paged') && useStructuredData) {
head.push('');
head.push.apply(head, finaliseStructuredData(metaData));
head.push.apply(head, finaliseStructuredData(meta));
head.push('');
if (metaData.schema) {
if (meta.schema) {
head.push('<script type="application/ld+json">\n' +
JSON.stringify(metaData.schema, null, ' ') +
JSON.stringify(meta.schema, null, ' ') +
'\n </script>\n');
}
}
@ -180,8 +180,8 @@ module.exports = function ghost_head(options) { // eslint-disable-line camelcase
escapeExpression(safeVersion) + '" />');
head.push('<link rel="alternate" type="application/rss+xml" title="' +
escapeExpression(metaData.site.title) + '" href="' +
escapeExpression(metaData.rssUrl) + '" />');
escapeExpression(meta.site.title) + '" href="' +
escapeExpression(meta.rssUrl) + '" />');
// no code injection for amp context!!!
if (!_.includes(context, 'amp')) {

View File

@ -48,13 +48,13 @@ module.exports = function navigation(options) {
}
// strips trailing slashes and compares urls
function _isCurrentUrl(href, currentUrl) {
if (!currentUrl) {
function _isCurrentUrl(href, url) {
if (!url) {
return false;
}
const strippedHref = href.replace(/\/+$/, '');
const strippedCurrentUrl = currentUrl.replace(/\/+$/, '');
const strippedCurrentUrl = url.replace(/\/+$/, '');
return strippedHref === strippedCurrentUrl;
}

View File

@ -22,7 +22,7 @@ module.exports = function tags(options) {
let from = options.hash.from ? parseInt(options.hash.from, 10) : 1;
let to = options.hash.to ? parseInt(options.hash.to, 10) : undefined;
function createTagList(tags) {
function createTagList(tagsList) {
function processTag(tag) {
return autolink ? templates.link({
url: urlService.getUrlByResourceId(tag.id, {withSubdirectory: true}),
@ -30,7 +30,7 @@ module.exports = function tags(options) {
}) : _.escape(tag.name);
}
return ghostHelperUtils.visibility.filter(tags, options.hash.visibility, processTag);
return ghostHelperUtils.visibility.filter(tagsList, options.hash.visibility, processTag);
}
if (this.tags && this.tags.length) {

View File

@ -42,14 +42,14 @@ const setFromFilePath = (filePath) => {
const backupRedirectsPath = path.join(config.getContentPath('data'), `redirects-${moment().format('YYYY-MM-DD-HH-mm-ss')}.json`);
return fs.pathExists(redirectsPath)
.then((exists) => {
if (!exists) {
.then((redirectExists) => {
if (!redirectExists) {
return null;
}
return fs.pathExists(backupRedirectsPath)
.then((exists) => {
if (!exists) {
.then((backupExists) => {
if (!backupExists) {
return null;
}

View File

@ -1,10 +1,10 @@
/**
* @description Centralised error handling for API requests.
* @param {Function} next
* @returns {Closure} handleError
* @returns {Function} handleErrorClosure
*/
function handleError(next) {
return function handleError(err) {
return function handleErrorClosure(err) {
// CASE: if we've thrown an error message of type: 'NotFound' then we found no path match, try next router!
if (err.errorType === 'NotFoundError') {
return next();

View File

@ -11,7 +11,7 @@ const renderer = require('./renderer');
*/
module.exports = function renderEntries(req, res) {
debug('renderEntries called');
return function renderEntries(result) {
return function renderEntriesClosure(result) {
// Format data 2
// Render
return renderer(req, res, formatResponse.entries(result));

View File

@ -10,7 +10,7 @@ const renderer = require('./renderer');
*/
module.exports = function renderEntry(req, res) {
debug('renderEntry called');
return function renderEntry(entry) {
return function renderEntryClosure(entry) {
// Format data 2 - 1 is in preview/entry
// Render
return renderer(req, res, formatResponse.entry(entry));

View File

@ -119,12 +119,12 @@ _private.pickTemplate = function pickTemplate(templateList, fallback) {
if (!themes.getActive()) {
template = fallback;
} else {
template = _.find(templateList, function (template) {
if (!template) {
template = _.find(templateList, function (templateName) {
if (!templateName) {
return;
}
return themes.getActive().hasTemplate(template);
return themes.getActive().hasTemplate(templateName);
});
}

View File

@ -4,11 +4,8 @@ const cheerio = require('cheerio');
const RSS = require('rss');
const urlUtils = require('../../../shared/url-utils');
const urlService = require('../url');
let generateFeed;
let generateItem;
let generateTags;
generateTags = function generateTags(data) {
const generateTags = function generateTags(data) {
if (data.tags) {
return data.tags.reduce(function (tags, tag) {
if (tag.visibility !== 'internal') {
@ -21,7 +18,7 @@ generateTags = function generateTags(data) {
return [];
};
generateItem = function generateItem(post, secure) {
const generateItem = function generateItem(post, secure) {
const itemUrl = urlService.getUrlByResourceId(post.id, {secure, absolute: true});
const htmlContent = cheerio.load(urlUtils.htmlRelativeToAbsolute(post.html, itemUrl, {secure}) || '', {decodeEntities: false});
const item = {
@ -71,7 +68,7 @@ generateItem = function generateItem(post, secure) {
* @param {string} baseUrl
* @param {{title, description, safeVersion, secure, posts}} data
*/
generateFeed = function generateFeed(baseUrl, data) {
const generateFeed = function generateFeed(baseUrl, data) {
const {secure} = data;
const feed = new RSS({

View File

@ -115,11 +115,11 @@ _private.validateData = function validateData(object) {
const longForm = shortToLongForm(object.data[key], {resourceKey: key});
data.query = _.merge(data.query, longForm.query);
_.each(Object.keys(longForm.router), (key) => {
if (data.router[key]) {
data.router[key] = data.router[key].concat(longForm.router[key]);
_.each(Object.keys(longForm.router), (routerKey) => {
if (data.router[routerKey]) {
data.router[routerKey] = data.router[routerKey].concat(longForm.router[routerKey]);
} else {
data.router[key] = longForm.router[key];
data.router[routerKey] = longForm.router[routerKey];
}
});

View File

@ -3,9 +3,7 @@ const coreHelpers = require('../../../helpers');
const registerThemeHelper = register.registerThemeHelper;
const registerAsyncThemeHelper = register.registerAsyncThemeHelper;
let registerAllCoreHelpers;
registerAllCoreHelpers = function registerAllCoreHelpers() {
const registerAllCoreHelpers = function registerAllCoreHelpers() {
// Register theme helpers
registerThemeHelper('asset', coreHelpers.asset);
registerThemeHelper('author', coreHelpers.author);

View File

@ -5,8 +5,8 @@ const config = require('../../../../shared/config');
const logging = require('../../../../shared/logging');
// Register an async handlebars helper for a given handlebars instance
function asyncHelperWrapper(hbs, name, fn) {
hbs.registerAsyncHelper(name, function returnAsync(context, options, cb) {
function asyncHelperWrapper(hbsInstance, name, fn) {
hbsInstance.registerAsyncHelper(name, function returnAsync(context, options, cb) {
// Handle the case where we only get context and cb
if (!cb) {
cb = options;
@ -29,7 +29,7 @@ function asyncHelperWrapper(hbs, name, fn) {
logging.error(wrappedErr);
cb(new hbs.SafeString(result));
cb(new hbsInstance.SafeString(result));
});
});
}

View File

@ -2,10 +2,8 @@ const debug = require('ghost-ignition').debug('themes:loader');
const config = require('../../../shared/config');
const packageJSON = require('../../../server/lib/fs/package-json');
const themeList = require('./list');
let loadAllThemes;
let loadOneTheme;
loadAllThemes = function loadAllThemes() {
const loadAllThemes = function loadAllThemes() {
return packageJSON.read
.all(config.getContentPath('themes'))
.then(function updateThemeList(themes) {
@ -15,7 +13,7 @@ loadAllThemes = function loadAllThemes() {
});
};
loadOneTheme = function loadOneTheme(themeName) {
const loadOneTheme = function loadOneTheme(themeName) {
return packageJSON.read
.one(config.getContentPath('themes'), themeName)
.then(function (readThemes) {

View File

@ -346,7 +346,7 @@ class Resources {
return this._fetchSingle(resourceConfig, model.id);
})
.then(([dbResource]) => {
const resource = this.data[type].find(resource => (resource.data.id === model.id));
const resource = this.data[type].find(r => (r.data.id === model.id));
// CASE: cached resource exists, API conditions matched with the data in the db
if (resource && dbResource) {

View File

@ -101,7 +101,6 @@ SchedulingDefault.prototype.unschedule = function (object, options = {bootstrap:
SchedulingDefault.prototype.run = function () {
const self = this;
let timeout = null;
let recursiveRun;
// NOTE: Ensure the scheduler never runs twice.
if (this.isRunning) {
@ -110,7 +109,7 @@ SchedulingDefault.prototype.run = function () {
this.isRunning = true;
recursiveRun = function recursiveRun() {
let recursiveRun = function recursiveRun() {
timeout = setTimeout(function () {
const times = Object.keys(self.allJobs);
const nextJobs = {};

View File

@ -116,18 +116,18 @@ module.exports = {
// CASE: ensure we destroy the invite before
return models.Invite.findOne({email: frame.data.invites[0].email}, frame.options)
.then((invite) => {
if (!invite) {
.then((existingInvite) => {
if (!existingInvite) {
return;
}
return invite.destroy(frame.options);
return existingInvite.destroy(frame.options);
})
.then(() => {
return models.Invite.add(frame.data.invites[0], frame.options);
})
.then((_invite) => {
invite = _invite;
.then((createdInvite) => {
invite = createdInvite;
const adminUrl = urlUtils.urlFor('admin', true);
@ -163,8 +163,8 @@ module.exports = {
status: 'sent'
}, Object.assign({id: invite.id}, frame.options));
})
.then((invite) => {
return invite;
.then((editedInvite) => {
return editedInvite;
})
.catch((err) => {
if (err && err.errorType === 'EmailError') {

View File

@ -18,9 +18,9 @@ module.exports = {
.catch(() => {});
}), (value) => {
return value && (value.name !== 'Owner');
}).then((roles) => {
}).then((filteredRoles) => {
return frame.response = {
roles: roles
roles: filteredRoles
};
});
}

View File

@ -59,8 +59,8 @@ const validate = (config, attrs) => {
}
const valuesAsArray = Array.isArray(value) ? value : value.trim().toLowerCase().split(',');
const unallowedValues = _.filter(valuesAsArray, (value) => {
return !allowedValues.includes(value);
const unallowedValues = _.filter(valuesAsArray, (valueToFilter) => {
return !allowedValues.includes(valueToFilter);
});
if (unallowedValues.length) {

View File

@ -116,12 +116,12 @@ module.exports = {
// CASE: ensure we destroy the invite before
return models.Invite.findOne({email: frame.data.invites[0].email}, frame.options)
.then((invite) => {
if (!invite) {
.then((existingInvite) => {
if (!existingInvite) {
return;
}
return invite.destroy(frame.options);
return existingInvite.destroy(frame.options);
})
.then(() => {
return models.Invite.add(frame.data.invites[0], frame.options);
@ -163,8 +163,8 @@ module.exports = {
status: 'sent'
}, Object.assign({id: invite.id}, frame.options));
})
.then((invite) => {
return invite;
.then((editedInvite) => {
return editedInvite;
})
.catch((err) => {
if (err && err.errorType === 'EmailError') {

View File

@ -18,9 +18,9 @@ module.exports = {
.catch(() => {});
}), (value) => {
return value && (value.name !== 'Owner');
}).then((roles) => {
}).then((filteredRoles) => {
return frame.response = {
roles: roles
roles: filteredRoles
};
});
}

View File

@ -39,15 +39,15 @@ class I18n {
/**
* Helper method to find and compile the given data context with a proper string resource.
*
* @param {string} path Path with in the JSON language file to desired string (ie: "errors.init.jsNotBuilt")
* @param {string} translationPath Path within the JSON language file to desired string (ie: "errors.init.jsNotBuilt")
* @param {object} [bindings]
* @returns {string}
*/
t(path, bindings) {
t(translationPath, bindings) {
let string;
let msg;
string = this._findString(path);
string = this._findString(translationPath);
// If the path returns an array (as in the case with anything that has multiple paragraphs such as emails), then
// loop through them and return an array of translated/formatted strings. Otherwise, just return the normal
@ -101,8 +101,8 @@ class I18n {
// While bracket-notation allows any Unicode characters in keys for themes,
// dot-notation allows only word characters in keys for backend messages
// (that is \w or [A-Za-z0-9_] in RegExp)
let path = `$.${msgPath}`;
return jp.value(this._strings, path);
let jsonPath = `$.${msgPath}`;
return jp.value(this._strings, jsonPath);
}
/**

View File

@ -1,6 +1,5 @@
const _ = require('lodash');
const notAPackageRegex = /^\.|_messages|README.md/i;
let filterPackages;
/**
* ### Filter Packages
@ -19,7 +18,7 @@ let filterPackages;
* @param {array/string} active as read from the settings object
* @returns {Array} of objects with useful info about themes
*/
filterPackages = function filterPackages(packages, active) {
const filterPackages = function filterPackages(packages, active) {
// turn active into an array if it isn't one, so this function can deal with lists and one-offs
if (!Array.isArray(active)) {
active = [active];

View File

@ -10,14 +10,11 @@ const parsePackageJson = require('./parse');
const errors = require('@tryghost/errors');
const notAPackageRegex = /^\.|_messages|README.md|node_modules|bower_components/i;
const packageJSONPath = 'package.json';
let readPackage;
let readPackages;
let processPackage;
/**
* Recursively read directory and find the packages in it
*/
processPackage = function processPackage(absolutePath, packageName) {
const processPackage = function processPackage(absolutePath, packageName) {
const pkg = {
name: packageName,
path: absolutePath
@ -37,7 +34,7 @@ processPackage = function processPackage(absolutePath, packageName) {
});
};
readPackage = function readPackage(packagePath, packageName) {
const readPackage = function readPackage(packagePath, packageName) {
const absolutePath = join(packagePath, packageName);
return fs.stat(absolutePath)
.then(function (stat) {
@ -62,7 +59,7 @@ readPackage = function readPackage(packagePath, packageName) {
});
};
readPackages = function readPackages(packagePath) {
const readPackages = function readPackages(packagePath) {
return fs.readdir(packagePath)
.filter(function (packageName) {
// Filter out things which are not packages by regex

View File

@ -8,11 +8,6 @@ const errors = require('@tryghost/errors');
const urlUtils = require('../../../shared/url-utils');
const settingsCache = require('../../services/settings/cache');
const storageUtils = require('../../adapters/storage/utils');
let getIconDimensions;
let isIcoImageType;
let getIconType;
let getIconUrl;
let getIconPath;
/**
* Get dimensions for ico file from its real file storage path
@ -21,12 +16,12 @@ let getIconPath;
* @returns {Promise<Object>} getIconDimensions
* @description Takes a file path and returns ico width and height.
*/
getIconDimensions = function getIconDimensions(path) {
const getIconDimensions = function getIconDimensions(storagePath) {
return new Promise(function getIconSize(resolve, reject) {
let dimensions;
try {
dimensions = sizeOf(path);
dimensions = sizeOf(storagePath);
if (dimensions.images) {
dimensions.width = _.maxBy(dimensions.images, function (w) {
@ -44,7 +39,7 @@ getIconDimensions = function getIconDimensions(path) {
} catch (err) {
return reject(new errors.ValidationError({
message: i18n.t('errors.utils.blogIcon.error', {
file: path,
file: storagePath,
error: err.message
})
}));
@ -59,7 +54,7 @@ getIconDimensions = function getIconDimensions(path) {
* @returns {Boolean} true if submitted path is .ico file
* @description Takes a path and returns boolean value.
*/
isIcoImageType = function isIcoImageType(icon) {
const isIcoImageType = function isIcoImageType(icon) {
const blogIcon = icon || settingsCache.get('icon');
return blogIcon.match(/.ico$/i) ? true : false;
@ -72,7 +67,7 @@ isIcoImageType = function isIcoImageType(icon) {
* @returns {Boolean} true if submitted path is .ico file
* @description Takes a path and returns boolean value.
*/
getIconType = function getIconType(icon) {
const getIconType = function getIconType(icon) {
const blogIcon = icon || settingsCache.get('icon');
return isIcoImageType(blogIcon) ? 'x-icon' : 'png';
@ -85,7 +80,7 @@ getIconType = function getIconType(icon) {
* @description Checks if we have a custom uploaded icon and the extension of it. If no custom uploaded icon
* exists, we're returning the default `favicon.ico`
*/
getIconUrl = function getIconUrl(absolut) {
const getIconUrl = function getIconUrl(absolut) {
const blogIcon = settingsCache.get('icon');
if (absolut) {
@ -110,7 +105,7 @@ getIconUrl = function getIconUrl(absolut) {
* @description Checks if we have a custom uploaded icon. If no custom uploaded icon
* exists, we're returning the default `favicon.ico`
*/
getIconPath = function getIconPath() {
const getIconPath = function getIconPath() {
const blogIcon = settingsCache.get('icon');
if (blogIcon) {

View File

@ -39,10 +39,10 @@ const addAction = (model, event, options) => {
return;
}
const action = model.getAction(event, options);
const existingAction = model.getAction(event, options);
// CASE: model does not support action for target event
if (!action) {
if (!existingAction) {
return;
}
@ -66,10 +66,10 @@ const addAction = (model, event, options) => {
return;
}
insert(action);
insert(existingAction);
});
} else {
insert(action);
insert(existingAction);
}
};

View File

@ -124,10 +124,10 @@ const addAction = (model, event, options) => {
return;
}
const action = model.getAction(event, options);
const existingAction = model.getAction(event, options);
// CASE: model does not support action for target event
if (!action) {
if (!existingAction) {
return;
}
@ -151,10 +151,10 @@ const addAction = (model, event, options) => {
return;
}
insert(action);
insert(existingAction);
});
} else {
insert(action);
insert(existingAction);
}
};
@ -193,15 +193,15 @@ ghostBookshelf.Model = ghostBookshelf.Model.extend({
* If the query runs in a txn, `_previousAttributes` will be empty.
*/
emitChange: function (model, event, options) {
const _emit = (ghostEvent, model, opts) => {
if (!model.wasChanged()) {
const _emit = (ghostEvent, _model, opts) => {
if (!_model.wasChanged()) {
return;
}
debug(model.tableName, ghostEvent);
debug(_model.tableName, ghostEvent);
// @NOTE: Internal Ghost events. These are very granular e.g. post.published
events.emit(ghostEvent, model, opts);
events.emit(ghostEvent, _model, opts);
};
if (!options.transacting) {
@ -781,13 +781,13 @@ ghostBookshelf.Model = ghostBookshelf.Model.extend({
relations = [data[property]];
}
_.each(relations, (relation, indexInArr) => {
_.each(relation, (value, relationProperty) => {
if (value !== null
_.each(relation, (relationValue, relationProperty) => {
if (relationValue !== null
&& Object.prototype.hasOwnProperty.call(schema.tables[this.prototype.relationshipBelongsTo[property]], relationProperty)
&& schema.tables[this.prototype.relationshipBelongsTo[property]][relationProperty].type === 'dateTime'
&& typeof value === 'string'
&& typeof relationValue === 'string'
) {
date = new Date(value);
date = new Date(relationValue);
// CASE: client sends `0000-00-00 00:00:00`
if (isNaN(date)) {
@ -797,7 +797,7 @@ ghostBookshelf.Model = ghostBookshelf.Model.extend({
});
}
data[property][indexInArr][relationProperty] = moment(value).toDate();
data[property][indexInArr][relationProperty] = moment(relationValue).toDate();
}
});
});
@ -1107,12 +1107,10 @@ ghostBookshelf.Model = ghostBookshelf.Model.extend({
let slugTryCount = 1;
const baseName = Model.prototype.tableName.replace(/s$/, '');
// Look for a matching slug, append an incrementing number if so
let checkIfSlugExists;
let longSlug;
checkIfSlugExists = function checkIfSlugExists(slugToFind) {
// Look for a matching slug, append an incrementing number if so
const checkIfSlugExists = function checkIfSlugExists(slugToFind) {
const args = {slug: slugToFind};
// status is needed for posts
@ -1306,34 +1304,34 @@ ghostBookshelf.Model = ghostBookshelf.Model.extend({
props[relation.name] = (() => {
debug('fetch withRelated', relation.name);
let query = db.knex(relation.targetTable);
let relationQuery = db.knex(relation.targetTable);
// default fields to select
_.each(relation.select, (fieldToSelect) => {
query.select(fieldToSelect);
relationQuery.select(fieldToSelect);
});
// custom fields to select
_.each(withRelatedFields[withRelatedKey], (toSelect) => {
query.select(toSelect);
relationQuery.select(toSelect);
});
query.innerJoin(
relationQuery.innerJoin(
relation.innerJoin.relation,
relation.innerJoin.condition[0],
relation.innerJoin.condition[1],
relation.innerJoin.condition[2]
);
query.whereIn(relation.whereIn, _.map(objects, 'id'));
query.orderBy(relation.orderBy);
relationQuery.whereIn(relation.whereIn, _.map(objects, 'id'));
relationQuery.orderBy(relation.orderBy);
return query
.then((relations) => {
return relationQuery
.then((queryRelations) => {
debug('fetched withRelated', relation.name);
// arr => obj[post_id] = [...] (faster access)
return relations.reduce((obj, item) => {
return queryRelations.reduce((obj, item) => {
if (!obj[item[relation.whereInKey]]) {
obj[item[relation.whereInKey]] = [];
}
@ -1346,23 +1344,23 @@ ghostBookshelf.Model = ghostBookshelf.Model.extend({
});
return Promise.props(props)
.then((relations) => {
.then((relationsToAttach) => {
debug('attach relations', modelName);
objects = _.map(objects, (object) => {
_.each(Object.keys(relations), (relation) => {
if (!relations[relation][object.id]) {
_.each(Object.keys(relationsToAttach), (relation) => {
if (!relationsToAttach[relation][object.id]) {
object[relation] = [];
return;
}
object[relation] = relations[relation][object.id];
object[relation] = relationsToAttach[relation][object.id];
});
object = ghostBookshelf._models[modelName].prototype.toJSON.bind({
attributes: object,
_originalOptions: {
withRelated: Object.keys(relations)
withRelated: Object.keys(relationsToAttach)
},
related: function (key) {
return object[key];

View File

@ -7,8 +7,6 @@ const _ = require('lodash');
const Promise = require('bluebird');
const ObjectId = require('bson-objectid');
const errors = require('@tryghost/errors');
let attach;
let detach;
/**
* Attach wrapper (please never call attach manual!)
@ -23,7 +21,7 @@ let detach;
* roles [{role_id: 1}]
* roles [BookshelfModel]
*/
attach = function attach(Model, effectedModelId, relation, modelsToAttach, options) {
const attach = function attach(Model, effectedModelId, relation, modelsToAttach, options) {
options = options || {};
let fetchedModel;
@ -65,7 +63,7 @@ attach = function attach(Model, effectedModelId, relation, modelsToAttach, optio
});
};
detach = function detach(Model, effectedModelId, relation, modelsToAttach, options) {
const detach = function detach(Model, effectedModelId, relation, modelsToAttach, options) {
options = options || {};
let fetchedModel;

View File

@ -142,14 +142,14 @@ const Member = ghostBookshelf.Model.extend({
* For the reason above, `detached` handler is using the scope of `detaching`
* to access the models that are not present in `detached`.
*/
model.related('labels').once('detaching', function onDetached(collection, label) {
model.related('labels').once('detaching', function onDetaching(collection, label) {
model.related('labels').once('detached', function onDetached(detachedCollection, response, options) {
label.emitChange('detached', options);
model.emitChange('label.detached', options);
});
});
model.related('labels').once('attaching', function onDetached(collection, labels) {
model.related('labels').once('attaching', function onDetaching(collection, labels) {
model.related('labels').once('attached', function onDetached(detachedCollection, response, options) {
labels.forEach((label) => {
label.emitChange('attached', options);

View File

@ -7,7 +7,6 @@ const {i18n} = require('../../lib/common');
const errors = require('@tryghost/errors');
let defaults;
let paginationUtils;
let pagination;
/**
* ### Default pagination values
@ -147,7 +146,7 @@ paginationUtils = {
* Extends `bookshelf.Model` with `fetchPage`
* @param {Bookshelf} bookshelf \- the instance to plug into
*/
pagination = function pagination(bookshelf) {
const pagination = function pagination(bookshelf) {
// Extend updates the first object passed to it, no need for an assignment
_.extend(bookshelf.Model.prototype, {
/**

View File

@ -17,7 +17,7 @@ const doBlock = fn => fn();
const getMembersKey = doBlock(() => {
let UNO_KEYPAIRINO;
return function getMembersKey(type) {
return function getKey(type) {
if (!UNO_KEYPAIRINO) {
UNO_KEYPAIRINO = keypair({bits: 1024});
}
@ -27,7 +27,7 @@ const getMembersKey = doBlock(() => {
const getGhostKey = doBlock(() => {
let UNO_KEYPAIRINO;
return function getGhostKey(type) {
return function getKey(type) {
if (!UNO_KEYPAIRINO) {
UNO_KEYPAIRINO = keypair({bits: 1024});
}

View File

@ -245,7 +245,7 @@ User = ghostBookshelf.Model.extend({
return this.belongsToMany('Role');
},
permissions: function permissions() {
permissions: function permissionsFn() {
return this.belongsToMany('Permission');
},

View File

@ -5,7 +5,7 @@ const errors = require('@tryghost/errors');
const {i18n} = require('../../../lib/common');
const _ = require('lodash');
let JWT_OPTIONS = {
let JWT_OPTIONS_DEFAULTS = {
algorithms: ['HS256'],
maxAge: '5m'
};
@ -49,7 +49,7 @@ const authenticate = (req, res, next) => {
}));
}
return authenticateWithToken(req, res, next, {token, JWT_OPTIONS});
return authenticateWithToken(req, res, next, {token, JWT_OPTIONS: JWT_OPTIONS_DEFAULTS});
};
const authenticateWithUrl = (req, res, next) => {
@ -61,7 +61,7 @@ const authenticateWithUrl = (req, res, next) => {
}));
}
// CASE: Scheduler publish URLs can have long maxAge but controllerd by expiry and neverBefore
return authenticateWithToken(req, res, next, {token, JWT_OPTIONS: _.omit(JWT_OPTIONS, 'maxAge')});
return authenticateWithToken(req, res, next, {token, JWT_OPTIONS: _.omit(JWT_OPTIONS_DEFAULTS, 'maxAge')});
};
/**

View File

@ -4,9 +4,8 @@
const models = require('../../models');
const actionsMap = require('./actions-map-cache');
let init;
init = function init(options) {
const init = function init(options) {
options = options || {};
// Load all the permissions

View File

@ -64,13 +64,13 @@ const response = {
module.exports = (event, model) => {
webhooks.getAll(event)
.then((webhooks) => {
debug(`${webhooks.models.length} webhooks found for ${event}.`);
.then((hooks) => {
debug(`${hooks.models.length} webhooks found for ${event}.`);
_.each(webhooks.models, (webhook) => {
_.each(hooks.models, (webhook) => {
payload(webhook.get('event'), model)
.then((payload) => {
const reqPayload = JSON.stringify(payload);
.then((hookPayload) => {
const reqPayload = JSON.stringify(hookPayload);
const url = webhook.get('target_url');
const opts = {
body: reqPayload,

View File

@ -12,8 +12,8 @@ module.exports = {
globalBlock(req, res, next) {
return spamPrevention.globalBlock().getMiddleware({
ignoreIP: false,
key: function (req, res, next) {
next(url.parse(req.url).pathname);
key: function (_req, _res, _next) {
_next(url.parse(_req.url).pathname);
}
})(req, res, next);
},
@ -23,8 +23,8 @@ module.exports = {
globalReset(req, res, next) {
return spamPrevention.globalReset().getMiddleware({
ignoreIP: false,
key(req, res, next) {
next(url.parse(req.url).pathname);
key(_req, _res, _next) {
_next(url.parse(_req.url).pathname);
}
})(req, res, next);
},
@ -35,20 +35,20 @@ module.exports = {
userLogin(req, res, next) {
return spamPrevention.userLogin().getMiddleware({
ignoreIP: false,
key(req, res, next) {
if (req.body.username) {
return next(`${req.body.username}login`);
key(_req, _res, _next) {
if (_req.body.username) {
return _next(`${_req.body.username}login`);
}
if (req.body.authorizationCode) {
return next(`${req.body.authorizationCode}login`);
if (_req.body.authorizationCode) {
return _next(`${_req.body.authorizationCode}login`);
}
if (req.body.refresh_token) {
return next(`${req.body.refresh_token}login`);
if (_req.body.refresh_token) {
return _next(`${_req.body.refresh_token}login`);
}
return next();
return _next();
}
})(req, res, next);
},
@ -58,8 +58,8 @@ module.exports = {
userReset(req, res, next) {
return spamPrevention.userReset().getMiddleware({
ignoreIP: false,
key(req, res, next) {
next(`${req.body.username}reset`);
key(_req, _res, _next) {
_next(`${_req.body.username}reset`);
}
})(req, res, next);
},
@ -69,8 +69,8 @@ module.exports = {
privateBlog(req, res, next) {
return spamPrevention.privateBlog().getMiddleware({
ignoreIP: false,
key(req, res, next) {
next('privateblog');
key(_req, _res, _next) {
_next('privateblog');
}
})(req, res, next);
},

View File

@ -187,17 +187,17 @@ _private.ThemeErrorRenderer = (err, req, res, next) => {
// @TODO use renderer here?!
// Render Call - featuring an error handler for what happens if rendering fails
res.render(res._template, data, (err, html) => {
if (!err) {
res.render(res._template, data, (_err, html) => {
if (!_err) {
return res.send(html);
}
// re-attach new error e.g. error template has syntax error or misusage
req.err = err;
req.err = _err;
// And then try to explain things to the user...
// Cheat and output the error using handlebars escapeExpression
return res.status(500).send(_private.ErrorFallbackMessage(err));
return res.status(500).send(_private.ErrorFallbackMessage(_err));
});
};
@ -218,17 +218,17 @@ _private.HTMLErrorRenderer = (err, req, res, next) => { // eslint-disable-line n
req.app.set('views', config.get('paths').defaultViews);
}
res.render('error', data, (err, html) => {
if (!err) {
res.render('error', data, (_err, html) => {
if (!_err) {
return res.send(html);
}
// re-attach new error e.g. error template has syntax error or misusage
req.err = err;
req.err = _err;
// And then try to explain things to the user...
// Cheat and output the error using handlebars escapeExpression
return res.status(500).send(_private.ErrorFallbackMessage(err));
return res.status(500).send(_private.ErrorFallbackMessage(_err));
});
};

View File

@ -96,8 +96,8 @@ module.exports = function (req, res, next) {
}
return imagePath;
})
.then((path) => {
return storageInstance.read({path});
.then((storagePath) => {
return storageInstance.read({path: storagePath});
})
.then((originalImageBuffer) => {
return imageTransform.resizeFromBuffer(originalImageBuffer, imageDimensionConfig);

View File

@ -29,7 +29,7 @@ function serveFavicon() {
let iconType;
let filePath;
return function serveFavicon(req, res, next) {
return function serveFaviconMiddleware(req, res, next) {
if (req.path.match(/^\/favicon\.(ico|png)/i)) {
// CASE: favicon is default
// confusing: if you upload an icon, it's same logic as storing images

View File

@ -12,7 +12,7 @@ function createPublicFileMiddleware(file, type, maxAge) {
const filePath = file.match(/^public/) ? path.join(publicFilePath, file.replace(/^public/, '')) : path.join(publicFilePath, file);
const blogRegex = /(\{\{blog-url\}\})/g;
return function servePublicFile(req, res, next) {
return function servePublicFileMiddleware(req, res, next) {
if (content) {
res.writeHead(200, content.headers);
return res.end(content.body);
@ -68,7 +68,7 @@ function createPublicFileMiddleware(file, type, maxAge) {
function servePublicFile(file, type, maxAge) {
const publicFileMiddleware = createPublicFileMiddleware(file, type, maxAge);
return function servePublicFile(req, res, next) {
return function servePublicFileMiddleware(req, res, next) {
if (req.path === '/' + file) {
return publicFileMiddleware(req, res, next);
} else {