diff --git a/.eslintrc.json b/.eslintrc.json index a838276139..d02a0310a7 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -8,5 +8,9 @@ ], "extends": [ "plugin:ghost/node" - ] + ], + "rules": { + "no-var": "error", + "one-var": [2, "never"] + } } diff --git a/Gruntfile.js b/Gruntfile.js index 8d63495395..9319668049 100644 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -48,7 +48,7 @@ const configureGrunt = function (grunt) { grunt.loadNpmTasks('grunt-subgrunt'); grunt.loadNpmTasks('grunt-update-submodules'); - var cfg = { + const cfg = { // #### Common paths used by tasks paths: { build: buildDirectory, @@ -163,7 +163,7 @@ const configureGrunt = function (grunt) { bg: grunt.option('client') ? false : true, stdout: function (chunk) { // hide certain output to prevent confusion when running alongside server - var filter = grunt.option('client') ? false : [ + const filter = grunt.option('client') ? false : [ /> ghost-admin/, /^Livereload/, /^Serving on/ @@ -208,7 +208,7 @@ const configureGrunt = function (grunt) { }, master: { command: function () { - var upstream = grunt.option('upstream') || process.env.GHOST_UPSTREAM || 'upstream'; + const upstream = grunt.option('upstream') || process.env.GHOST_UPSTREAM || 'upstream'; grunt.log.writeln('Pulling down the latest master from ' + upstream); return ` git submodule sync @@ -425,7 +425,7 @@ const configureGrunt = function (grunt) { // so that the test environments do not need to build out the client files grunt.registerTask('stubClientFiles', function () { _.each(cfg.clientFiles, function (file) { - var filePath = path.resolve(cwd + '/core/' + file); + const filePath = path.resolve(cwd + '/core/' + file); fs.ensureFileSync(filePath); }); }); diff --git a/MigratorConfig.js b/MigratorConfig.js index 13c4b24502..1a5de8487e 100644 --- a/MigratorConfig.js +++ b/MigratorConfig.js @@ -1,5 +1,5 @@ -var config = require('./core/server/config'), - ghostVersion = require('./core/server/lib/ghost-version'); +const config = require('./core/server/config'); +const ghostVersion = require('./core/server/lib/ghost-version'); /** * knex-migrator can be used via CLI or within the application diff --git a/core/frontend/apps/amp/lib/helpers/amp_components.js b/core/frontend/apps/amp/lib/helpers/amp_components.js index 335c69c138..88fb22e3df 100644 --- a/core/frontend/apps/amp/lib/helpers/amp_components.js +++ b/core/frontend/apps/amp/lib/helpers/amp_components.js @@ -8,12 +8,13 @@ // By default supported AMP HTML tags (no additional script tag necessary): // amp-img, amp-ad, amp-embed, amp-video and amp-pixel. // (less) dirty requires -const proxy = require('../../../../services/proxy'), - SafeString = proxy.SafeString; +const proxy = require('../../../../services/proxy'); + +const SafeString = proxy.SafeString; function ampComponents() { - let components = [], - html = this.post && this.post.html || this.html; + let components = []; + let html = this.post && this.post.html || this.html; if (!html) { return; @@ -23,8 +24,8 @@ function ampComponents() { components.push(''); } - let iframeCount = (html.match(/()/gi) || []).length, - youtubeCount = (html.match(/()/gi) || []).length; + let iframeCount = (html.match(/()/gi) || []).length; + let youtubeCount = (html.match(/()/gi) || []).length; if (youtubeCount) { components.push(''); diff --git a/core/frontend/apps/amp/lib/helpers/amp_content.js b/core/frontend/apps/amp/lib/helpers/amp_content.js index fbad616522..78eef2ec7a 100644 --- a/core/frontend/apps/amp/lib/helpers/amp_content.js +++ b/core/frontend/apps/amp/lib/helpers/amp_content.js @@ -6,21 +6,21 @@ // // Converts normal HTML into AMP HTML with Amperize module and uses a cache to return it from // there if available. The cacheId is a combination of `updated_at` and the `slug`. -const Promise = require('bluebird'), - moment = require('moment'), - proxy = require('../../../../services/proxy'), - SafeString = proxy.SafeString, - logging = proxy.logging, - i18n = proxy.i18n, - errors = proxy.errors, - urlUtils = proxy.urlUtils, - amperizeCache = {}; +const Promise = require('bluebird'); -let allowedAMPTags = [], - allowedAMPAttributes = {}, - amperize = null, - ampHTML = '', - cleanHTML = ''; +const moment = require('moment'); +const proxy = require('../../../../services/proxy'); +const SafeString = proxy.SafeString; +const logging = proxy.logging; +const i18n = proxy.i18n; +const errors = proxy.errors; +const urlUtils = proxy.urlUtils; +const amperizeCache = {}; +let allowedAMPTags = []; +let allowedAMPAttributes = {}; +let amperize = null; +let ampHTML = ''; +let cleanHTML = ''; allowedAMPTags = ['html', 'body', 'article', 'section', 'nav', 'aside', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'footer', 'address', 'p', 'hr', @@ -119,8 +119,8 @@ function getAmperizeHTML(html, post) { return; } - let Amperize = require('amperize'), - startedAtMoment = moment(); + let Amperize = require('amperize'); + let startedAtMoment = moment(); amperize = amperize || new Amperize(); @@ -163,11 +163,12 @@ function getAmperizeHTML(html, post) { } function ampContent() { - let sanitizeHtml = require('sanitize-html'), - cheerio = require('cheerio'), - amperizeHTML = { - amperize: getAmperizeHTML(this.html, this) - }; + let sanitizeHtml = require('sanitize-html'); + let cheerio = require('cheerio'); + + let amperizeHTML = { + amperize: getAmperizeHTML(this.html, this) + }; return Promise.props(amperizeHTML).then((result) => { let $ = null; diff --git a/core/frontend/apps/amp/lib/router.js b/core/frontend/apps/amp/lib/router.js index 765e684cdd..444fce2c2f 100644 --- a/core/frontend/apps/amp/lib/router.js +++ b/core/frontend/apps/amp/lib/router.js @@ -1,12 +1,13 @@ -const path = require('path'), - express = require('express'), - ampRouter = express.Router(), +const path = require('path'); +const express = require('express'); +const ampRouter = express.Router(); - // Dirty requires - common = require('../../../../server/lib/common'), - urlService = require('../../../services/url'), - helpers = require('../../../services/routing/helpers'), - templateName = 'amp'; +// Dirty requires +const common = require('../../../../server/lib/common'); + +const urlService = require('../../../services/url'); +const helpers = require('../../../services/routing/helpers'); +const templateName = 'amp'; function _renderer(req, res, next) { res.routerOptions = { diff --git a/core/frontend/apps/private-blogging/index.js b/core/frontend/apps/private-blogging/index.js index 6c8fac8c4e..e1ec1708c4 100644 --- a/core/frontend/apps/private-blogging/index.js +++ b/core/frontend/apps/private-blogging/index.js @@ -1,10 +1,11 @@ -const urlUtils = require('../../../server/lib/url-utils'), - common = require('../../../server/lib/common'), - middleware = require('./lib/middleware'), - router = require('./lib/router'), - registerHelpers = require('./lib/helpers'), - // routeKeywords.private: 'private' - PRIVATE_KEYWORD = 'private'; +const urlUtils = require('../../../server/lib/url-utils'); +const common = require('../../../server/lib/common'); +const middleware = require('./lib/middleware'); +const router = require('./lib/router'); +const registerHelpers = require('./lib/helpers'); + +// routeKeywords.private: 'private' +const PRIVATE_KEYWORD = 'private'; let checkSubdir = function checkSubdir() { let paths = ''; diff --git a/core/frontend/apps/private-blogging/lib/helpers/input_password.js b/core/frontend/apps/private-blogging/lib/helpers/input_password.js index 99a6626189..dad5acefc6 100644 --- a/core/frontend/apps/private-blogging/lib/helpers/input_password.js +++ b/core/frontend/apps/private-blogging/lib/helpers/input_password.js @@ -4,24 +4,24 @@ // Password input used on private.hbs for password-protected blogs // (less) dirty requires -const proxy = require('../../../../services/proxy'), - SafeString = proxy.SafeString, - templates = proxy.templates; +const proxy = require('../../../../services/proxy'); + +const SafeString = proxy.SafeString; +const templates = proxy.templates; // We use the name input_password to match the helper for consistency: module.exports = function input_password(options) { // eslint-disable-line camelcase options = options || {}; options.hash = options.hash || {}; - let className = (options.hash.class) ? options.hash.class : 'private-login-password', - extras = 'autofocus="autofocus"', - output; + const className = (options.hash.class) ? options.hash.class : 'private-login-password'; + let extras = 'autofocus="autofocus"'; if (options.hash.placeholder) { extras += ` placeholder="${options.hash.placeholder}"`; } - output = templates.input({ + const output = templates.input({ type: 'password', name: 'password', className, diff --git a/core/frontend/apps/private-blogging/lib/middleware.js b/core/frontend/apps/private-blogging/lib/middleware.js index 734e04d05a..328686cd5c 100644 --- a/core/frontend/apps/private-blogging/lib/middleware.js +++ b/core/frontend/apps/private-blogging/lib/middleware.js @@ -91,10 +91,10 @@ const privateBlogging = { }, authenticatePrivateSession: function authenticatePrivateSession(req, res, next) { - let hash = req.session.token || '', - salt = req.session.salt || '', - isVerified = verifySessionHash(salt, hash), - url; + const hash = req.session.token || ''; + const salt = req.session.salt || ''; + const isVerified = verifySessionHash(salt, hash); + let url; if (isVerified) { return next(); @@ -111,9 +111,9 @@ const privateBlogging = { return res.redirect(urlUtils.urlFor('home', true)); } - let hash = req.session.token || '', - salt = req.session.salt || '', - isVerified = verifySessionHash(salt, hash); + const hash = req.session.token || ''; + const salt = req.session.salt || ''; + const isVerified = verifySessionHash(salt, hash); if (isVerified) { // redirect to home if user is already authenticated diff --git a/core/frontend/apps/private-blogging/lib/router.js b/core/frontend/apps/private-blogging/lib/router.js index 313b46d1d3..0d65112cad 100644 --- a/core/frontend/apps/private-blogging/lib/router.js +++ b/core/frontend/apps/private-blogging/lib/router.js @@ -1,11 +1,11 @@ -const path = require('path'), - express = require('express'), - middleware = require('./middleware'), - bodyParser = require('body-parser'), - routing = require('../../../services/routing'), - web = require('../../../../server/web'), - templateName = 'private', - privateRouter = express.Router(); +const path = require('path'); +const express = require('express'); +const middleware = require('./middleware'); +const bodyParser = require('body-parser'); +const routing = require('../../../services/routing'); +const web = require('../../../../server/web'); +const templateName = 'private'; +const privateRouter = express.Router(); function _renderer(req, res) { res.routerOptions = { diff --git a/core/frontend/helpers/get.js b/core/frontend/helpers/get.js index 3f1ae72106..af1122a796 100644 --- a/core/frontend/helpers/get.js +++ b/core/frontend/helpers/get.js @@ -37,7 +37,7 @@ const pathAliases = { * @returns {boolean} */ function isBrowse(options) { - var browse = true; + let browse = true; if (options.id || options.slug) { browse = false; @@ -55,10 +55,10 @@ function isBrowse(options) { * @returns {String} */ function resolvePaths(globals, data, value) { - var regex = /\{\{(.*?)\}\}/g; + const regex = /\{\{(.*?)\}\}/g; value = value.replace(regex, function (match, path) { - var result; + let result; // Handle aliases path = pathAliases[path] ? pathAliases[path] : path; @@ -141,7 +141,7 @@ module.exports = function get(resource, options) { // @TODO: https://github.com/TryGhost/Ghost/issues/10548 return controller[action](apiOptions).then(function success(result) { - var blockParams; + let blockParams; // used for logging details of slow requests returnedRowsCount = result[resource] && result[resource].length; diff --git a/core/frontend/helpers/ghost_foot.js b/core/frontend/helpers/ghost_foot.js index 832a2bd037..e84a2b4e19 100644 --- a/core/frontend/helpers/ghost_foot.js +++ b/core/frontend/helpers/ghost_foot.js @@ -7,9 +7,10 @@ const _ = require('lodash'); // We use the name ghost_foot to match the helper for consistency: module.exports = function ghost_foot(options) { // eslint-disable-line camelcase - var foot = [], - globalCodeinjection = settingsCache.get('ghost_foot'), - postCodeinjection = options.data.root && options.data.root.post ? options.data.root.post.codeinjection_foot : null; + const foot = []; + + const globalCodeinjection = settingsCache.get('ghost_foot'); + const postCodeinjection = options.data.root && options.data.root.post ? options.data.root.post.codeinjection_foot : null; if (!_.isEmpty(globalCodeinjection)) { foot.push(globalCodeinjection); diff --git a/core/frontend/helpers/ghost_head.js b/core/frontend/helpers/ghost_head.js index fb05b5da15..9eef48ebee 100644 --- a/core/frontend/helpers/ghost_head.js +++ b/core/frontend/helpers/ghost_head.js @@ -15,7 +15,7 @@ function writeMetaTag(property, content, type) { } function finaliseStructuredData(metaData) { - var head = []; + const head = []; _.each(metaData.structuredData, function (content, property) { if (property === 'article:tag') { @@ -93,16 +93,16 @@ module.exports = function ghost_head(options) { // eslint-disable-line camelcase return; } - var head = [], - dataRoot = options.data.root, - context = dataRoot._locals.context ? dataRoot._locals.context : null, - safeVersion = dataRoot._locals.safeVersion, - postCodeInjection = dataRoot && dataRoot.post ? dataRoot.post.codeinjection_head : null, - globalCodeinjection = settingsCache.get('ghost_head'), - useStructuredData = !config.isPrivacyDisabled('useStructuredData'), - referrerPolicy = config.get('referrerPolicy') ? config.get('referrerPolicy') : 'no-referrer-when-downgrade', - favicon = blogIcon.getIconUrl(), - iconType = blogIcon.getIconType(favicon); + const head = []; + const dataRoot = options.data.root; + const context = dataRoot._locals.context ? dataRoot._locals.context : null; + const safeVersion = dataRoot._locals.safeVersion; + const postCodeInjection = dataRoot && dataRoot.post ? dataRoot.post.codeinjection_head : null; + const globalCodeinjection = settingsCache.get('ghost_head'); + const useStructuredData = !config.isPrivacyDisabled('useStructuredData'); + const referrerPolicy = config.get('referrerPolicy') ? config.get('referrerPolicy') : 'no-referrer-when-downgrade'; + const favicon = blogIcon.getIconUrl(); + const iconType = blogIcon.getIconType(favicon); debug('preparation complete, begin fetch'); diff --git a/core/frontend/helpers/has.js b/core/frontend/helpers/has.js index 01739258b7..fb9eb1447d 100644 --- a/core/frontend/helpers/has.js +++ b/core/frontend/helpers/has.js @@ -54,7 +54,7 @@ function handleTag(data, attrs) { } function evaluateAuthorList(expr, authors) { - var authorList = expr.split(',').map(function (v) { + const authorList = expr.split(',').map(function (v) { return v.trim().toLocaleLowerCase(); }); @@ -76,7 +76,7 @@ function handleAuthor(data, attrs) { } function evaluateIntegerMatch(expr, integer) { - var nthMatch = expr.match(/^nth:(\d+)/); + const nthMatch = expr.match(/^nth:(\d+)/); if (nthMatch) { return integer % parseInt(nthMatch[1], 10) === 0; } @@ -118,39 +118,41 @@ module.exports = function has(options) { options.hash = options.hash || {}; options.data = options.data || {}; - var self = this, - attrs = _.pick(options.hash, validAttrs), - data = _.pick(options.data, ['site', 'config', 'labs']), - checks = { - tag: function () { - return handleTag(self, attrs); - }, - author: function () { - return handleAuthor(self, attrs); - }, - number: function () { - return attrs.number && evaluateIntegerMatch(attrs.number, options.data.number) || false; - }, - index: function () { - return attrs.index && evaluateIntegerMatch(attrs.index, options.data.index) || false; - }, - visibility: function () { - return attrs.visibility && evaluateStringMatch(attrs.visibility, self.visibility, true) || false; - }, - slug: function () { - return attrs.slug && evaluateStringMatch(attrs.slug, self.slug, true) || false; - }, - id: function () { - return attrs.id && evaluateStringMatch(attrs.id, self.id, true) || false; - }, - any: function () { - return attrs.any && evaluateList('some', attrs.any, self, data) || false; - }, - all: function () { - return attrs.all && evaluateList('every', attrs.all, self, data) || false; - } + const self = this; + const attrs = _.pick(options.hash, validAttrs); + const data = _.pick(options.data, ['site', 'config', 'labs']); + + const checks = { + tag: function () { + return handleTag(self, attrs); }, - result; + author: function () { + return handleAuthor(self, attrs); + }, + number: function () { + return attrs.number && evaluateIntegerMatch(attrs.number, options.data.number) || false; + }, + index: function () { + return attrs.index && evaluateIntegerMatch(attrs.index, options.data.index) || false; + }, + visibility: function () { + return attrs.visibility && evaluateStringMatch(attrs.visibility, self.visibility, true) || false; + }, + slug: function () { + return attrs.slug && evaluateStringMatch(attrs.slug, self.slug, true) || false; + }, + id: function () { + return attrs.id && evaluateStringMatch(attrs.id, self.id, true) || false; + }, + any: function () { + return attrs.any && evaluateList('some', attrs.any, self, data) || false; + }, + all: function () { + return attrs.all && evaluateList('every', attrs.all, self, data) || false; + } + }; + + let result; if (_.isEmpty(attrs)) { logging.warn(i18n.t('warnings.helpers.has.invalidAttribute')); diff --git a/core/frontend/helpers/is.js b/core/frontend/helpers/is.js index 819db46b26..78695eb3fc 100644 --- a/core/frontend/helpers/is.js +++ b/core/frontend/helpers/is.js @@ -7,7 +7,7 @@ const _ = require('lodash'); module.exports = function is(context, options) { options = options || {}; - var currentContext = options.data.root.context; + const currentContext = options.data.root.context; if (!_.isString(context)) { logging.warn(i18n.t('warnings.helpers.is.invalidAttribute')); diff --git a/core/frontend/helpers/navigation.js b/core/frontend/helpers/navigation.js index ababd9b266..8111c6e844 100644 --- a/core/frontend/helpers/navigation.js +++ b/core/frontend/helpers/navigation.js @@ -16,10 +16,10 @@ module.exports = function navigation(options) { options.hash.isSecondary = options.hash.type && options.hash.type === 'secondary'; delete options.hash.type; - var navigationData = options.data.site[key], - currentUrl = options.data.root.relativeUrl, - self = this, - output; + const navigationData = options.data.site[key]; + const currentUrl = options.data.root.relativeUrl; + const self = this; + let output; if (!_.isObject(navigationData) || _.isFunction(navigationData)) { throw new errors.IncorrectUsageError({ @@ -51,8 +51,8 @@ module.exports = function navigation(options) { return false; } - var strippedHref = href.replace(/\/+$/, ''), - strippedCurrentUrl = currentUrl.replace(/\/+$/, ''); + const strippedHref = href.replace(/\/+$/, ''); + const strippedCurrentUrl = currentUrl.replace(/\/+$/, ''); return strippedHref === strippedCurrentUrl; } @@ -62,7 +62,7 @@ module.exports = function navigation(options) { } output = navigationData.map(function (e) { - var out = {}; + const out = {}; out.current = _isCurrentUrl(e.url, currentUrl); out.label = e.label; out.slug = slugify(e.label); diff --git a/core/frontend/helpers/post_class.js b/core/frontend/helpers/post_class.js index 251e74e373..edee02e0e8 100644 --- a/core/frontend/helpers/post_class.js +++ b/core/frontend/helpers/post_class.js @@ -6,11 +6,12 @@ const {SafeString} = require('../services/proxy'); // We use the name post_class to match the helper for consistency: module.exports = function post_class() { // eslint-disable-line camelcase - var classes = ['post'], - tags = this.post && this.post.tags ? this.post.tags : this.tags || [], - featured = this.post && this.post.featured ? this.post.featured : this.featured || false, - image = this.post && this.post.feature_image ? this.post.feature_image : this.feature_image || false, - page = this.post && this.post.page ? this.post.page : this.page || false; + let classes = ['post']; + + const tags = this.post && this.post.tags ? this.post.tags : this.tags || []; + const featured = this.post && this.post.featured ? this.post.featured : this.featured || false; + const image = this.post && this.post.feature_image ? this.post.feature_image : this.feature_image || false; + const page = this.post && this.post.page ? this.post.page : this.page || false; if (tags) { classes = classes.concat(tags.map(function (tag) { diff --git a/core/frontend/helpers/prev_post.js b/core/frontend/helpers/prev_post.js index ededfd6647..16cdf29935 100644 --- a/core/frontend/helpers/prev_post.js +++ b/core/frontend/helpers/prev_post.js @@ -11,21 +11,22 @@ const moment = require('moment'); const createFrame = hbs.handlebars.createFrame; const buildApiOptions = function buildApiOptions(options, post) { - var publishedAt = moment(post.published_at).format('YYYY-MM-DD HH:mm:ss'), - slug = post.slug, - op = options.name === 'prev_post' ? '<=' : '>', - order = options.name === 'prev_post' ? 'desc' : 'asc', - apiOptions = { - /** - * @deprecated: `author`, will be removed in Ghost 3.0 - */ - include: 'author,authors,tags', - order: 'published_at ' + order, - limit: 1, - // This line deliberately uses double quotes because GQL cannot handle either double quotes - // or escaped singles, see TryGhost/GQL#34 - filter: "slug:-" + slug + "+published_at:" + op + "'" + publishedAt + "'" // eslint-disable-line quotes - }; + const publishedAt = moment(post.published_at).format('YYYY-MM-DD HH:mm:ss'); + const slug = post.slug; + const op = options.name === 'prev_post' ? '<=' : '>'; + const order = options.name === 'prev_post' ? 'desc' : 'asc'; + + const apiOptions = { + /** + * @deprecated: `author`, will be removed in Ghost 3.0 + */ + include: 'author,authors,tags', + order: 'published_at ' + order, + limit: 1, + // This line deliberately uses double quotes because GQL cannot handle either double quotes + // or escaped singles, see TryGhost/GQL#34 + filter: "slug:-" + slug + "+published_at:" + op + "'" + publishedAt + "'" // eslint-disable-line quotes + }; if (get(options, 'hash.in')) { if (options.hash.in === 'primary_tag' && get(post, 'primary_tag.slug')) { @@ -51,7 +52,7 @@ const fetch = function fetch(options, data) { return controller .browse(apiOptions) .then(function handleSuccess(result) { - var related = result.posts[0]; + const related = result.posts[0]; if (related) { return options.fn(related, {data: data}); diff --git a/core/frontend/helpers/t.js b/core/frontend/helpers/t.js index de94e44458..5f73e6eff2 100644 --- a/core/frontend/helpers/t.js +++ b/core/frontend/helpers/t.js @@ -13,8 +13,8 @@ const {themeI18n} = require('../services/proxy'); module.exports = function t(text, options) { - var bindings = {}, - prop; + const bindings = {}; + let prop; for (prop in options.hash) { if (Object.prototype.hasOwnProperty.call(options.hash, prop)) { bindings[prop] = options.hash[prop]; diff --git a/core/frontend/helpers/tags.js b/core/frontend/helpers/tags.js index 85f510eee3..d241c23383 100644 --- a/core/frontend/helpers/tags.js +++ b/core/frontend/helpers/tags.js @@ -13,15 +13,14 @@ module.exports = function tags(options) { options = options || {}; options.hash = options.hash || {}; - const autolink = !(_.isString(options.hash.autolink) && options.hash.autolink === 'false'), - separator = _.isString(options.hash.separator) ? options.hash.separator : ', ', - prefix = _.isString(options.hash.prefix) ? options.hash.prefix : '', - suffix = _.isString(options.hash.suffix) ? options.hash.suffix : '', - limit = options.hash.limit ? parseInt(options.hash.limit, 10) : undefined; - - let output = '', - from = options.hash.from ? parseInt(options.hash.from, 10) : 1, - to = options.hash.to ? parseInt(options.hash.to, 10) : undefined; + const autolink = !(_.isString(options.hash.autolink) && options.hash.autolink === 'false'); + const separator = _.isString(options.hash.separator) ? options.hash.separator : ', '; + const prefix = _.isString(options.hash.prefix) ? options.hash.prefix : ''; + const suffix = _.isString(options.hash.suffix) ? options.hash.suffix : ''; + const limit = options.hash.limit ? parseInt(options.hash.limit, 10) : undefined; + let output = ''; + 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 processTag(tag) { diff --git a/core/frontend/helpers/url.js b/core/frontend/helpers/url.js index becd5efbbe..36fa631e8f 100644 --- a/core/frontend/helpers/url.js +++ b/core/frontend/helpers/url.js @@ -8,8 +8,8 @@ const {SafeString, metaData} = require('../services/proxy'); const {getMetaDataUrl} = metaData; module.exports = function url(options) { - var absolute = options && options.hash.absolute && options.hash.absolute !== 'false', - outputUrl = getMetaDataUrl(this, absolute); + const absolute = options && options.hash.absolute && options.hash.absolute !== 'false'; + let outputUrl = getMetaDataUrl(this, absolute); outputUrl = encodeURI(decodeURI(outputUrl)); diff --git a/core/frontend/meta/amp_url.js b/core/frontend/meta/amp_url.js index 021463f6ce..f1e22c2020 100644 --- a/core/frontend/meta/amp_url.js +++ b/core/frontend/meta/amp_url.js @@ -1,9 +1,9 @@ -var urlUtils = require('../../server/lib/url-utils'), - getUrl = require('./url'), - _ = require('lodash'); +const urlUtils = require('../../server/lib/url-utils'); +const getUrl = require('./url'); +const _ = require('lodash'); function getAmplUrl(data) { - var context = data.context ? data.context : null; + const context = data.context ? data.context : null; if (_.includes(context, 'post') && !_.includes(context, 'amp')) { return urlUtils.urlJoin(urlUtils.urlFor('home', true), getUrl(data, false), 'amp/'); diff --git a/core/frontend/meta/asset_url.js b/core/frontend/meta/asset_url.js index 4d0ab800fa..4e5295c6e3 100644 --- a/core/frontend/meta/asset_url.js +++ b/core/frontend/meta/asset_url.js @@ -1,7 +1,7 @@ -const crypto = require('crypto'), - config = require('../../server/config'), - imageLib = require('../../server/lib/image'), - urlUtils = require('../../server/lib/url-utils'); +const crypto = require('crypto'); +const config = require('../../server/config'); +const imageLib = require('../../server/lib/image'); +const urlUtils = require('../../server/lib/url-utils'); /** * Serve either uploaded favicon or default @@ -20,7 +20,7 @@ function getAssetUrl(path, hasMinFile) { // CASE: Build the output URL // Add subdirectory... - var output = urlUtils.urlJoin(urlUtils.getSubdir(), '/'); + let output = urlUtils.urlJoin(urlUtils.getSubdir(), '/'); // Optionally add /assets/ if (!path.match(/^public/) && !path.match(/^asset/)) { diff --git a/core/frontend/meta/author_fb_url.js b/core/frontend/meta/author_fb_url.js index 13b4a1909e..8d9c29a9c9 100644 --- a/core/frontend/meta/author_fb_url.js +++ b/core/frontend/meta/author_fb_url.js @@ -1,9 +1,9 @@ -var getContextObject = require('./context_object.js'), - _ = require('lodash'); +const getContextObject = require('./context_object.js'); +const _ = require('lodash'); function getAuthorFacebookUrl(data) { - var context = data.context ? data.context : null, - contextObject = getContextObject(data, context); + const context = data.context ? data.context : null; + const contextObject = getContextObject(data, context); if ((_.includes(context, 'post') || _.includes(context, 'page')) && contextObject.primary_author && contextObject.primary_author.facebook) { return contextObject.primary_author.facebook; diff --git a/core/frontend/meta/author_image.js b/core/frontend/meta/author_image.js index 22edb94a5b..d92568dbbf 100644 --- a/core/frontend/meta/author_image.js +++ b/core/frontend/meta/author_image.js @@ -1,10 +1,10 @@ -var urlUtils = require('../../server/lib/url-utils'), - getContextObject = require('./context_object.js'), - _ = require('lodash'); +const urlUtils = require('../../server/lib/url-utils'); +const getContextObject = require('./context_object.js'); +const _ = require('lodash'); function getAuthorImage(data, absolute) { - var context = data.context ? data.context : null, - contextObject = getContextObject(data, context); + const context = data.context ? data.context : null; + const contextObject = getContextObject(data, context); if ((_.includes(context, 'post') || _.includes(context, 'page')) && contextObject.primary_author && contextObject.primary_author.profile_image) { return urlUtils.urlFor('image', {image: contextObject.primary_author.profile_image}, absolute); diff --git a/core/frontend/meta/author_url.js b/core/frontend/meta/author_url.js index 41a42b8a67..6e1cb11501 100644 --- a/core/frontend/meta/author_url.js +++ b/core/frontend/meta/author_url.js @@ -1,7 +1,7 @@ -var urlService = require('../services/url'); +const urlService = require('../services/url'); function getAuthorUrl(data, absolute) { - var context = data.context ? data.context[0] : null; + let context = data.context ? data.context[0] : null; context = context === 'amp' ? 'post' : context; diff --git a/core/frontend/meta/blog_logo.js b/core/frontend/meta/blog_logo.js index 43d296b431..95ac9cd9ec 100644 --- a/core/frontend/meta/blog_logo.js +++ b/core/frontend/meta/blog_logo.js @@ -1,9 +1,9 @@ -var urlUtils = require('../../server/lib/url-utils'), - settingsCache = require('../../server/services/settings/cache'), - imageLib = require('../../server/lib/image'); +const urlUtils = require('../../server/lib/url-utils'); +const settingsCache = require('../../server/services/settings/cache'); +const imageLib = require('../../server/lib/image'); function getBlogLogo() { - var logo = {}; + const logo = {}; if (settingsCache.get('logo')) { logo.url = urlUtils.urlFor('image', {image: settingsCache.get('logo')}, true); diff --git a/core/frontend/meta/context_object.js b/core/frontend/meta/context_object.js index 428ff65120..d8a4f1c597 100644 --- a/core/frontend/meta/context_object.js +++ b/core/frontend/meta/context_object.js @@ -1,5 +1,5 @@ -var settingsCache = require('../../server/services/settings/cache'), - _ = require('lodash'); +const settingsCache = require('../../server/services/settings/cache'); +const _ = require('lodash'); function getContextObject(data, context) { /** diff --git a/core/frontend/meta/cover_image.js b/core/frontend/meta/cover_image.js index 1863b95503..4cf0505c85 100644 --- a/core/frontend/meta/cover_image.js +++ b/core/frontend/meta/cover_image.js @@ -1,10 +1,10 @@ -var urlUtils = require('../../server/lib/url-utils'), - getContextObject = require('./context_object.js'), - _ = require('lodash'); +const urlUtils = require('../../server/lib/url-utils'); +const getContextObject = require('./context_object.js'); +const _ = require('lodash'); function getCoverImage(data) { - var context = data.context ? data.context : null, - contextObject = getContextObject(data, context); + const context = data.context ? data.context : null; + const contextObject = getContextObject(data, context); if (_.includes(context, 'home') || _.includes(context, 'author')) { if (contextObject.cover_image) { diff --git a/core/frontend/meta/creator_url.js b/core/frontend/meta/creator_url.js index bdf1fd9948..2fc6a4343b 100644 --- a/core/frontend/meta/creator_url.js +++ b/core/frontend/meta/creator_url.js @@ -1,9 +1,9 @@ -var getContextObject = require('./context_object.js'), - _ = require('lodash'); +const getContextObject = require('./context_object.js'); +const _ = require('lodash'); function getCreatorTwitterUrl(data) { - var context = data.context ? data.context : null, - contextObject = getContextObject(data, context); + const context = data.context ? data.context : null; + const contextObject = getContextObject(data, context); if ((_.includes(context, 'post') || _.includes(context, 'page')) && contextObject.primary_author && contextObject.primary_author.twitter) { return contextObject.primary_author.twitter; diff --git a/core/frontend/meta/excerpt.js b/core/frontend/meta/excerpt.js index f194ed3e85..32fef0a916 100644 --- a/core/frontend/meta/excerpt.js +++ b/core/frontend/meta/excerpt.js @@ -1,9 +1,9 @@ -var downsize = require('downsize'); +const downsize = require('downsize'); function getExcerpt(html, truncateOptions) { truncateOptions = truncateOptions || {}; // Strip inline and bottom footnotes - var excerpt = html.replace(/.*?<\/a>/gi, ''); + let excerpt = html.replace(/.*?<\/a>/gi, ''); excerpt = excerpt.replace(/
    .*?<\/ol><\/div>/, ''); // Make sure to have space between paragraphs and new lines diff --git a/core/frontend/meta/image-dimensions.js b/core/frontend/meta/image-dimensions.js index d453c07eb8..b77fa3c2d9 100644 --- a/core/frontend/meta/image-dimensions.js +++ b/core/frontend/meta/image-dimensions.js @@ -1,6 +1,6 @@ -var Promise = require('bluebird'), - _ = require('lodash'), - imageLib = require('../../server/lib/image'); +const Promise = require('bluebird'); +const _ = require('lodash'); +const imageLib = require('../../server/lib/image'); /** * Get Image dimensions @@ -10,7 +10,7 @@ var Promise = require('bluebird'), * called to receive image width and height */ function getImageDimensions(metaData) { - var fetch = { + const fetch = { coverImage: imageLib.imageSizeCache(metaData.coverImage.url), authorImage: imageLib.imageSizeCache(metaData.authorImage.url), ogImage: imageLib.imageSizeCache(metaData.ogImage.url), diff --git a/core/frontend/meta/index.js b/core/frontend/meta/index.js index 31d84360aa..92ad2be665 100644 --- a/core/frontend/meta/index.js +++ b/core/frontend/meta/index.js @@ -1,80 +1,81 @@ -var Promise = require('bluebird'), - settingsCache = require('../../server/services/settings/cache'), - urlUtils = require('../../server/lib/url-utils'), - common = require('../../server/lib/common'), - getUrl = require('./url'), - getImageDimensions = require('./image-dimensions'), - getCanonicalUrl = require('./canonical_url'), - getAmpUrl = require('./amp_url'), - getPaginatedUrl = require('./paginated_url'), - getAuthorUrl = require('./author_url'), - getBlogLogo = require('./blog_logo'), - getRssUrl = require('./rss_url'), - getTitle = require('./title'), - getDescription = require('./description'), - getCoverImage = require('./cover_image'), - getAuthorImage = require('./author_image'), - getAuthorFacebook = require('./author_fb_url'), - getCreatorTwitter = require('./creator_url'), - getKeywords = require('./keywords'), - getPublishedDate = require('./published_date'), - getModifiedDate = require('./modified_date'), - getOgType = require('./og_type'), - getOgImage = require('./og_image'), - getTwitterImage = require('./twitter_image'), - getStructuredData = require('./structured_data'), - getSchema = require('./schema'), - getExcerpt = require('./excerpt'); +const Promise = require('bluebird'); +const settingsCache = require('../../server/services/settings/cache'); +const urlUtils = require('../../server/lib/url-utils'); +const common = require('../../server/lib/common'); +const getUrl = require('./url'); +const getImageDimensions = require('./image-dimensions'); +const getCanonicalUrl = require('./canonical_url'); +const getAmpUrl = require('./amp_url'); +const getPaginatedUrl = require('./paginated_url'); +const getAuthorUrl = require('./author_url'); +const getBlogLogo = require('./blog_logo'); +const getRssUrl = require('./rss_url'); +const getTitle = require('./title'); +const getDescription = require('./description'); +const getCoverImage = require('./cover_image'); +const getAuthorImage = require('./author_image'); +const getAuthorFacebook = require('./author_fb_url'); +const getCreatorTwitter = require('./creator_url'); +const getKeywords = require('./keywords'); +const getPublishedDate = require('./published_date'); +const getModifiedDate = require('./modified_date'); +const getOgType = require('./og_type'); +const getOgImage = require('./og_image'); +const getTwitterImage = require('./twitter_image'); +const getStructuredData = require('./structured_data'); +const getSchema = require('./schema'); +const getExcerpt = require('./excerpt'); function getMetaData(data, root) { - var metaData = { - url: getUrl(data, true), - canonicalUrl: getCanonicalUrl(data), - ampUrl: getAmpUrl(data), - previousUrl: getPaginatedUrl('prev', data, true), - nextUrl: getPaginatedUrl('next', data, true), - authorUrl: getAuthorUrl(data, true), - rssUrl: getRssUrl(data, true), - metaTitle: getTitle(data, root), - metaDescription: getDescription(data, root) || null, - coverImage: { - url: getCoverImage(data, true) - }, - authorImage: { - url: getAuthorImage(data, true) - }, - ogImage: { - url: getOgImage(data) - }, - ogTitle: getTitle(data, root, {property: 'og'}), - ogDescription: getDescription(data, root, {property: 'og'}), - twitterImage: getTwitterImage(data, true), - twitterTitle: getTitle(data, root, {property: 'twitter'}), - twitterDescription: getDescription(data, root, {property: 'twitter'}), - authorFacebook: getAuthorFacebook(data), - creatorTwitter: getCreatorTwitter(data), - keywords: getKeywords(data), - publishedDate: getPublishedDate(data), - modifiedDate: getModifiedDate(data), - ogType: getOgType(data), - // @TODO: pass into each meta helper - wrap each helper - site: { - title: settingsCache.get('title'), - description: settingsCache.get('description'), - url: urlUtils.urlFor('home', true), - facebook: settingsCache.get('facebook'), - twitter: settingsCache.get('twitter'), - timezone: settingsCache.get('active_timezone'), - navigation: settingsCache.get('navigation'), - icon: settingsCache.get('icon'), - cover_image: settingsCache.get('cover_image'), - logo: getBlogLogo(), - amp: settingsCache.get('amp') - } + const metaData = { + url: getUrl(data, true), + canonicalUrl: getCanonicalUrl(data), + ampUrl: getAmpUrl(data), + previousUrl: getPaginatedUrl('prev', data, true), + nextUrl: getPaginatedUrl('next', data, true), + authorUrl: getAuthorUrl(data, true), + rssUrl: getRssUrl(data, true), + metaTitle: getTitle(data, root), + metaDescription: getDescription(data, root) || null, + coverImage: { + url: getCoverImage(data, true) }, - customExcerpt, - metaDescription, - fallbackExcerpt; + authorImage: { + url: getAuthorImage(data, true) + }, + ogImage: { + url: getOgImage(data) + }, + ogTitle: getTitle(data, root, {property: 'og'}), + ogDescription: getDescription(data, root, {property: 'og'}), + twitterImage: getTwitterImage(data, true), + twitterTitle: getTitle(data, root, {property: 'twitter'}), + twitterDescription: getDescription(data, root, {property: 'twitter'}), + authorFacebook: getAuthorFacebook(data), + creatorTwitter: getCreatorTwitter(data), + keywords: getKeywords(data), + publishedDate: getPublishedDate(data), + modifiedDate: getModifiedDate(data), + ogType: getOgType(data), + // @TODO: pass into each meta helper - wrap each helper + site: { + title: settingsCache.get('title'), + description: settingsCache.get('description'), + url: urlUtils.urlFor('home', true), + facebook: settingsCache.get('facebook'), + twitter: settingsCache.get('twitter'), + timezone: settingsCache.get('active_timezone'), + navigation: settingsCache.get('navigation'), + icon: settingsCache.get('icon'), + cover_image: settingsCache.get('cover_image'), + logo: getBlogLogo(), + amp: settingsCache.get('amp') + } + }; + + let customExcerpt; + let metaDescription; + let fallbackExcerpt; // TODO: cleanup these if statements // NOTE: should use 'post' OR 'page' once https://github.com/TryGhost/Ghost/issues/10042 is resolved diff --git a/core/frontend/meta/modified_date.js b/core/frontend/meta/modified_date.js index b4efcef7f7..93432b1b4b 100644 --- a/core/frontend/meta/modified_date.js +++ b/core/frontend/meta/modified_date.js @@ -1,8 +1,8 @@ -var _ = require('lodash'); +const _ = require('lodash'); function getModifiedDate(data) { - var context = data.context ? data.context : null, - modDate; + let context = data.context ? data.context : null; + let modDate; context = _.includes(context, 'amp') ? 'post' : context; diff --git a/core/frontend/meta/og_type.js b/core/frontend/meta/og_type.js index 2ccb056efd..673c187022 100644 --- a/core/frontend/meta/og_type.js +++ b/core/frontend/meta/og_type.js @@ -1,5 +1,5 @@ function getOgType(data) { - var context = data.context ? data.context[0] : null; + let context = data.context ? data.context[0] : null; context = context === 'amp' ? 'post' : context; diff --git a/core/frontend/meta/paginated_url.js b/core/frontend/meta/paginated_url.js index ac9bf5a3ba..437173021e 100644 --- a/core/frontend/meta/paginated_url.js +++ b/core/frontend/meta/paginated_url.js @@ -1,20 +1,25 @@ -var _ = require('lodash'), - urlUtils = require('../../server/lib/url-utils'); +const _ = require('lodash'); +const urlUtils = require('../../server/lib/url-utils'); function getPaginatedUrl(page, data, absolute) { // If we don't have enough information, return null right away if (!data || !data.relativeUrl || !data.pagination) { return null; } + // routeKeywords.page: 'page' - var pagePath = urlUtils.urlJoin('/page/'), - // Try to match the base url, as whatever precedes the pagePath - // routeKeywords.page: 'page' - baseUrlPattern = new RegExp('(.+)?(/page/\\d+/)'), - baseUrlMatch = data.relativeUrl.match(baseUrlPattern), - // If there is no match for pagePath, use the original url, without the trailing slash - baseUrl = baseUrlMatch ? baseUrlMatch[1] : data.relativeUrl.slice(0, -1), - newRelativeUrl; + const pagePath = urlUtils.urlJoin('/page/'); + + // Try to match the base url, as whatever precedes the pagePath + // routeKeywords.page: 'page' + const baseUrlPattern = new RegExp('(.+)?(/page/\\d+/)'); + + const baseUrlMatch = data.relativeUrl.match(baseUrlPattern); + + // If there is no match for pagePath, use the original url, without the trailing slash + const baseUrl = baseUrlMatch ? baseUrlMatch[1] : data.relativeUrl.slice(0, -1); + + let newRelativeUrl; if (page === 'next' && data.pagination.next) { newRelativeUrl = urlUtils.urlJoin(pagePath, data.pagination.next, '/'); diff --git a/core/frontend/meta/published_date.js b/core/frontend/meta/published_date.js index f1cc1c1b15..044e2ef418 100644 --- a/core/frontend/meta/published_date.js +++ b/core/frontend/meta/published_date.js @@ -1,5 +1,5 @@ function getPublishedDate(data) { - var context = data.context ? data.context[0] : null; + let context = data.context ? data.context[0] : null; context = context === 'amp' ? 'post' : context; diff --git a/core/frontend/meta/schema.js b/core/frontend/meta/schema.js index 6c9cbfc555..f67741f06d 100644 --- a/core/frontend/meta/schema.js +++ b/core/frontend/meta/schema.js @@ -1,10 +1,10 @@ -var config = require('../../server/config'), - escapeExpression = require('../services/themes/engine').escapeExpression, - socialUrls = require('@tryghost/social-urls'), - _ = require('lodash'); +const config = require('../../server/config'); +const escapeExpression = require('../services/themes/engine').escapeExpression; +const socialUrls = require('@tryghost/social-urls'); +const _ = require('lodash'); function schemaImageObject(metaDataVal) { - var imageObject; + let imageObject; if (!metaDataVal) { return null; } @@ -23,7 +23,7 @@ function schemaImageObject(metaDataVal) { } function schemaPublisherObject(metaDataVal) { - var publisherObject; + let publisherObject; publisherObject = { '@type': 'Organization', @@ -37,7 +37,7 @@ function schemaPublisherObject(metaDataVal) { // Creates the final schema object with values that are not null function trimSchema(schema) { - var schemaObject = {}; + const schemaObject = {}; _.each(schema, function (value, key) { if (value !== null && typeof value !== 'undefined') { @@ -49,7 +49,7 @@ function trimSchema(schema) { } function trimSameAs(data, context) { - var sameAs = []; + const sameAs = []; if (context === 'post' || context === 'page') { if (data[context].primary_author.website) { @@ -79,8 +79,9 @@ function trimSameAs(data, context) { function getPostSchema(metaData, data) { // CASE: metaData.excerpt for post context is populated by either the custom excerpt, the meta description, // or the automated excerpt of 50 words. It is empty for any other context. - var description = metaData.excerpt ? escapeExpression(metaData.excerpt) : null, - schema; + const description = metaData.excerpt ? escapeExpression(metaData.excerpt) : null; + + let schema; const context = data.page ? 'page' : 'post'; @@ -116,7 +117,7 @@ function getPostSchema(metaData, data) { } function getHomeSchema(metaData) { - var schema = { + const schema = { '@context': 'https://schema.org', '@type': 'WebSite', publisher: schemaPublisherObject(metaData), @@ -134,7 +135,7 @@ function getHomeSchema(metaData) { } function getTagSchema(metaData, data) { - var schema = { + const schema = { '@context': 'https://schema.org', '@type': 'Series', publisher: schemaPublisherObject(metaData), @@ -154,7 +155,7 @@ function getTagSchema(metaData, data) { } function getAuthorSchema(metaData, data) { - var schema = { + const schema = { '@context': 'https://schema.org', '@type': 'Person', sameAs: trimSameAs(data, 'author'), @@ -175,7 +176,7 @@ function getAuthorSchema(metaData, data) { function getSchema(metaData, data) { if (!config.isPrivacyDisabled('useStructuredData')) { - var context = data.context ? data.context : null; + const context = data.context ? data.context : null; if (_.includes(context, 'post') || _.includes(context, 'page') || _.includes(context, 'amp')) { return getPostSchema(metaData, data); } else if (_.includes(context, 'home')) { diff --git a/core/frontend/meta/structured_data.js b/core/frontend/meta/structured_data.js index e2a24df897..d6ac7f369a 100644 --- a/core/frontend/meta/structured_data.js +++ b/core/frontend/meta/structured_data.js @@ -1,8 +1,8 @@ -var socialUrls = require('@tryghost/social-urls'); +const socialUrls = require('@tryghost/social-urls'); function getStructuredData(metaData) { - var structuredData, - card = 'summary'; + let structuredData; + let card = 'summary'; if (metaData.twitterImage || metaData.coverImage.url) { card = 'summary_large_image'; @@ -46,7 +46,7 @@ function getStructuredData(metaData) { // return structured data removing null or undefined keys return Object.keys(structuredData).reduce(function (data, key) { - var content = structuredData[key]; + const content = structuredData[key]; if (content !== null && typeof content !== 'undefined') { data[key] = content; } diff --git a/core/frontend/meta/url.js b/core/frontend/meta/url.js index 2fccd86502..deb54ffe4e 100644 --- a/core/frontend/meta/url.js +++ b/core/frontend/meta/url.js @@ -1,6 +1,6 @@ -var schema = require('../../server/data/schema').checks, - urlUtils = require('../../server/lib/url-utils'), - urlService = require('../services/url'); +const schema = require('../../server/data/schema').checks; +const urlUtils = require('../../server/lib/url-utils'); +const urlService = require('../services/url'); // This cleans the url from any `/amp` postfixes, so we'll never // output a url with `/amp` in the end, except for the needed `amphtml` diff --git a/core/frontend/services/proxy.js b/core/frontend/services/proxy.js index d4d46ea29c..014d15fdb8 100644 --- a/core/frontend/services/proxy.js +++ b/core/frontend/services/proxy.js @@ -1,9 +1,10 @@ // This file defines everything that helpers "require" // With the exception of modules like lodash, Bluebird // We can later refactor to enforce this something like we did in apps -var hbs = require('./themes/engine'), - settingsCache = require('../../server/services/settings/cache'), - config = require('../../server/config'); +const hbs = require('./themes/engine'); + +const settingsCache = require('../../server/services/settings/cache'); +const config = require('../../server/config'); // Direct requires: // - lodash diff --git a/core/frontend/services/routing/CollectionRouter.js b/core/frontend/services/routing/CollectionRouter.js index d1d12f580a..28da81e173 100644 --- a/core/frontend/services/routing/CollectionRouter.js +++ b/core/frontend/services/routing/CollectionRouter.js @@ -147,8 +147,8 @@ class CollectionRouter extends ParentRouter { * @private */ _onTimezoneEdited(settingModel) { - const newTimezone = settingModel.attributes.value, - previousTimezone = settingModel._previousAttributes.value; + const newTimezone = settingModel.attributes.value; + const previousTimezone = settingModel._previousAttributes.value; if (newTimezone === previousTimezone) { return; diff --git a/core/frontend/services/routing/ParentRouter.js b/core/frontend/services/routing/ParentRouter.js index ded60743d8..1aef782132 100644 --- a/core/frontend/services/routing/ParentRouter.js +++ b/core/frontend/services/routing/ParentRouter.js @@ -7,14 +7,15 @@ * Only allows for .use and .get at the moment - we don't have clear use-cases for anything else yet. */ -const debug = require('ghost-ignition').debug('services:routing:ParentRouter'), - EventEmitter = require('events').EventEmitter, - express = require('express'), - _ = require('lodash'), - url = require('url'), - security = require('../../../server/lib/security'), - urlUtils = require('../../../server/lib/url-utils'), - registry = require('./registry'); +const debug = require('ghost-ignition').debug('services:routing:ParentRouter'); + +const EventEmitter = require('events').EventEmitter; +const express = require('express'); +const _ = require('lodash'); +const url = require('url'); +const security = require('../../../server/lib/security'); +const urlUtils = require('../../../server/lib/url-utils'); +const registry = require('./registry'); /** * @description Inherited express router, which gives control to us. diff --git a/core/frontend/services/routing/controllers/channel.js b/core/frontend/services/routing/controllers/channel.js index 1f9601e276..165d9c8853 100644 --- a/core/frontend/services/routing/controllers/channel.js +++ b/core/frontend/services/routing/controllers/channel.js @@ -1,9 +1,9 @@ -const _ = require('lodash'), - debug = require('ghost-ignition').debug('services:routing:controllers:channel'), - common = require('../../../../server/lib/common'), - security = require('../../../../server/lib/security'), - themes = require('../../themes'), - helpers = require('../helpers'); +const _ = require('lodash'); +const debug = require('ghost-ignition').debug('services:routing:controllers:channel'); +const common = require('../../../../server/lib/common'); +const security = require('../../../../server/lib/security'); +const themes = require('../../themes'); +const helpers = require('../helpers'); /** * @description Channel controller. diff --git a/core/frontend/services/routing/controllers/collection.js b/core/frontend/services/routing/controllers/collection.js index d0d67a2d41..892de33066 100644 --- a/core/frontend/services/routing/controllers/collection.js +++ b/core/frontend/services/routing/controllers/collection.js @@ -1,10 +1,10 @@ -const _ = require('lodash'), - debug = require('ghost-ignition').debug('services:routing:controllers:collection'), - common = require('../../../../server/lib/common'), - security = require('../../../../server/lib/security'), - urlService = require('../../url'), - themes = require('../../themes'), - helpers = require('../helpers'); +const _ = require('lodash'); +const debug = require('ghost-ignition').debug('services:routing:controllers:collection'); +const common = require('../../../../server/lib/common'); +const security = require('../../../../server/lib/security'); +const urlService = require('../../url'); +const themes = require('../../themes'); +const helpers = require('../helpers'); /** * @description Collection controller. diff --git a/core/frontend/services/routing/controllers/rss.js b/core/frontend/services/routing/controllers/rss.js index b00249bf34..0bfec1f0dd 100644 --- a/core/frontend/services/routing/controllers/rss.js +++ b/core/frontend/services/routing/controllers/rss.js @@ -1,15 +1,15 @@ -const _ = require('lodash'), - debug = require('ghost-ignition').debug('services:routing:controllers:rss'), - url = require('url'), - security = require('../../../../server/lib/security'), - settingsCache = require('../../../../server/services/settings/cache'), - rssService = require('../../rss'), - helpers = require('../helpers'); +const _ = require('lodash'); +const debug = require('ghost-ignition').debug('services:routing:controllers:rss'); +const url = require('url'); +const security = require('../../../../server/lib/security'); +const settingsCache = require('../../../../server/services/settings/cache'); +const rssService = require('../../rss'); +const helpers = require('../helpers'); // @TODO: is this really correct? Should we be using meta data title? function getTitle(relatedData) { relatedData = relatedData || {}; - var titleStart = _.get(relatedData, 'author[0].name') || _.get(relatedData, 'tag[0].name') || ''; + let titleStart = _.get(relatedData, 'author[0].name') || _.get(relatedData, 'tag[0].name') || ''; titleStart += titleStart ? ' - ' : ''; return titleStart + settingsCache.get('title'); diff --git a/core/frontend/services/routing/controllers/static.js b/core/frontend/services/routing/controllers/static.js index 38430518d5..f113d3e5b7 100644 --- a/core/frontend/services/routing/controllers/static.js +++ b/core/frontend/services/routing/controllers/static.js @@ -1,7 +1,7 @@ -const _ = require('lodash'), - Promise = require('bluebird'), - debug = require('ghost-ignition').debug('services:routing:controllers:static'), - helpers = require('../helpers'); +const _ = require('lodash'); +const Promise = require('bluebird'); +const debug = require('ghost-ignition').debug('services:routing:controllers:static'); +const helpers = require('../helpers'); function processQuery(query, locals) { const api = require('../../../../server/api')[locals.apiVersion]; diff --git a/core/frontend/services/routing/helpers/context.js b/core/frontend/services/routing/helpers/context.js index 0e387eaa9a..8894866615 100644 --- a/core/frontend/services/routing/helpers/context.js +++ b/core/frontend/services/routing/helpers/context.js @@ -10,15 +10,17 @@ * 2. req.params.page - always has the page parameter, regardless of if the URL contains a keyword * 3. data - used for telling the difference between posts and pages */ -const // @TODO: fix this!! These regexes are app specific and should be dynamic. They should not belong here.... - // routeKeywords.private: 'private' - privatePattern = new RegExp('^\\/private\\/'), - // routeKeywords.amp: 'amp' - ampPattern = new RegExp('\\/amp\\/$'), - homePattern = new RegExp('^\\/$'); +// @TODO: fix this!! These regexes are app specific and should be dynamic. They should not belong here.... +// routeKeywords.private: 'private' +const privatePattern = new RegExp('^\\/private\\/'); + +// routeKeywords.amp: 'amp' +const ampPattern = new RegExp('\\/amp\\/$'); + +const homePattern = new RegExp('^\\/$'); function setResponseContext(req, res, data) { - var pageParam = req.params && req.params.page !== undefined ? parseInt(req.params.page, 10) : 1; + const pageParam = req.params && req.params.page !== undefined ? parseInt(req.params.page, 10) : 1; res.locals = res.locals || {}; res.locals.context = []; diff --git a/core/frontend/services/routing/helpers/fetch-data.js b/core/frontend/services/routing/helpers/fetch-data.js index df09c1f97c..f642542f83 100644 --- a/core/frontend/services/routing/helpers/fetch-data.js +++ b/core/frontend/services/routing/helpers/fetch-data.js @@ -72,8 +72,8 @@ function fetchData(pathOptions, routerOptions, locals) { pathOptions = pathOptions || {}; routerOptions = routerOptions || {}; - let postQuery = _.cloneDeep(defaultPostQuery), - props = {}; + let postQuery = _.cloneDeep(defaultPostQuery); + let props = {}; if (routerOptions.filter) { postQuery.options.filter = routerOptions.filter; diff --git a/core/frontend/services/routing/helpers/format-response.js b/core/frontend/services/routing/helpers/format-response.js index 77fbf5e1b9..349cb9eeed 100644 --- a/core/frontend/services/routing/helpers/format-response.js +++ b/core/frontend/services/routing/helpers/format-response.js @@ -6,7 +6,7 @@ const _ = require('lodash'); * @return {Object} containing page variables */ function formatPageResponse(result) { - var response = {}; + const response = {}; if (result.posts) { response.posts = result.posts; diff --git a/core/frontend/services/routing/helpers/render-entries.js b/core/frontend/services/routing/helpers/render-entries.js index bd3d1e4750..ef96fb7e2c 100644 --- a/core/frontend/services/routing/helpers/render-entries.js +++ b/core/frontend/services/routing/helpers/render-entries.js @@ -1,6 +1,6 @@ -const debug = require('ghost-ignition').debug('services:routing:helpers:render-entries'), - formatResponse = require('./format-response'), - renderer = require('./renderer'); +const debug = require('ghost-ignition').debug('services:routing:helpers:render-entries'); +const formatResponse = require('./format-response'); +const renderer = require('./renderer'); /** * @description Helper to handle rendering multiple resources. diff --git a/core/frontend/services/routing/helpers/render-entry.js b/core/frontend/services/routing/helpers/render-entry.js index 2c684bdd38..d25daa417e 100644 --- a/core/frontend/services/routing/helpers/render-entry.js +++ b/core/frontend/services/routing/helpers/render-entry.js @@ -1,6 +1,6 @@ -const debug = require('ghost-ignition').debug('services:routing:helpers:render-post'), - formatResponse = require('./format-response'), - renderer = require('./renderer'); +const debug = require('ghost-ignition').debug('services:routing:helpers:render-post'); +const formatResponse = require('./format-response'); +const renderer = require('./renderer'); /** * @description Helper to handle rendering multiple resources. * diff --git a/core/frontend/services/routing/helpers/renderer.js b/core/frontend/services/routing/helpers/renderer.js index 2515638c0d..3b057a07a7 100644 --- a/core/frontend/services/routing/helpers/renderer.js +++ b/core/frontend/services/routing/helpers/renderer.js @@ -1,6 +1,6 @@ -const debug = require('ghost-ignition').debug('services:routing:helpers:renderer'), - setContext = require('./context'), - templates = require('./templates'); +const debug = require('ghost-ignition').debug('services:routing:helpers:renderer'); +const setContext = require('./context'); +const templates = require('./templates'); /** * @description Helper function to finally render the data. diff --git a/core/frontend/services/routing/helpers/templates.js b/core/frontend/services/routing/helpers/templates.js index 60f0410e80..709370a755 100644 --- a/core/frontend/services/routing/helpers/templates.js +++ b/core/frontend/services/routing/helpers/templates.js @@ -2,12 +2,13 @@ // // Figure out which template should be used to render a request // based on the templates which are allowed, and what is available in the theme -const _ = require('lodash'), - path = require('path'), - url = require('url'), - config = require('../../../../server/config'), - themes = require('../../themes'), - _private = {}; +const _ = require('lodash'); + +const path = require('path'); +const url = require('url'); +const config = require('../../../../server/config'); +const themes = require('../../themes'); +const _private = {}; /** * @description Get Error Template Hierarchy @@ -20,8 +21,8 @@ const _ = require('lodash'), * @returns {String[]} */ _private.getErrorTemplateHierarchy = function getErrorTemplateHierarchy(statusCode) { - const errorCode = _.toString(statusCode), - templateList = ['error']; + const errorCode = _.toString(statusCode); + const templateList = ['error']; // Add error class template: E.g. error-4xx.hbs or error-5xx.hbs templateList.unshift('error-' + errorCode[0] + 'xx'); @@ -141,20 +142,20 @@ _private.pickTemplate = function pickTemplate(templateList, fallback) { }; _private.getTemplateForEntry = function getTemplateForEntry(postObject) { - const templateList = _private.getEntryTemplateHierarchy(postObject), - fallback = templateList[templateList.length - 1]; + const templateList = _private.getEntryTemplateHierarchy(postObject); + const fallback = templateList[templateList.length - 1]; return _private.pickTemplate(templateList, fallback); }; _private.getTemplateForEntries = function getTemplateForEntries(routerOptions, requestOptions) { - const templateList = _private.getEntriesTemplateHierarchy(routerOptions, requestOptions), - fallback = templateList[templateList.length - 1]; + const templateList = _private.getEntriesTemplateHierarchy(routerOptions, requestOptions); + const fallback = templateList[templateList.length - 1]; return _private.pickTemplate(templateList, fallback); }; _private.getTemplateForError = function getTemplateForError(statusCode) { - const templateList = _private.getErrorTemplateHierarchy(statusCode), - fallback = path.resolve(config.get('paths').defaultViews, 'error.hbs'); + const templateList = _private.getErrorTemplateHierarchy(statusCode); + const fallback = path.resolve(config.get('paths').defaultViews, 'error.hbs'); return _private.pickTemplate(templateList, fallback); }; diff --git a/core/frontend/services/routing/middlewares/page-param.js b/core/frontend/services/routing/middlewares/page-param.js index 68d3c80e7c..74dd16bf9b 100644 --- a/core/frontend/services/routing/middlewares/page-param.js +++ b/core/frontend/services/routing/middlewares/page-param.js @@ -1,5 +1,5 @@ -const common = require('../../../../server/lib/common'), - urlUtils = require('../../../../server/lib/url-utils'); +const common = require('../../../../server/lib/common'); +const urlUtils = require('../../../../server/lib/url-utils'); /** * @description Middleware, which validates and interprets the page param e.g. /page/1 diff --git a/core/frontend/services/rss/cache.js b/core/frontend/services/rss/cache.js index 5e1a7bf772..531881b978 100644 --- a/core/frontend/services/rss/cache.js +++ b/core/frontend/services/rss/cache.js @@ -1,9 +1,9 @@ -var crypto = require('crypto'), - generateFeed = require('./generate-feed'), - feedCache = {}; +const crypto = require('crypto'); +const generateFeed = require('./generate-feed'); +const feedCache = {}; module.exports.getXML = function getFeedXml(baseUrl, data) { - var dataHash = crypto.createHash('md5').update(JSON.stringify(data)).digest('hex'); + const dataHash = crypto.createHash('md5').update(JSON.stringify(data)).digest('hex'); if (!feedCache[baseUrl] || feedCache[baseUrl].hash !== dataHash) { // We need to regenerate feedCache[baseUrl] = { diff --git a/core/frontend/services/rss/generate-feed.js b/core/frontend/services/rss/generate-feed.js index 2d499a7fe8..d3cc407032 100644 --- a/core/frontend/services/rss/generate-feed.js +++ b/core/frontend/services/rss/generate-feed.js @@ -1,12 +1,12 @@ -var downsize = require('downsize'), - Promise = require('bluebird'), - cheerio = require('cheerio'), - RSS = require('rss'), - urlUtils = require('../../../server/lib/url-utils'), - urlService = require('../url'), - generateFeed, - generateItem, - generateTags; +const downsize = require('downsize'); +const Promise = require('bluebird'); +const cheerio = require('cheerio'); +const RSS = require('rss'); +const urlUtils = require('../../../server/lib/url-utils'); +const urlService = require('../url'); +let generateFeed; +let generateItem; +let generateTags; generateTags = function generateTags(data) { if (data.tags) { diff --git a/core/frontend/services/rss/renderer.js b/core/frontend/services/rss/renderer.js index 4be8bd4efd..9a15afc918 100644 --- a/core/frontend/services/rss/renderer.js +++ b/core/frontend/services/rss/renderer.js @@ -1,9 +1,9 @@ -var _ = require('lodash'), - rssCache = require('./cache'); +const _ = require('lodash'); +const rssCache = require('./cache'); module.exports.render = function render(res, baseUrl, data) { // Format data - this is the same as what Express does - var rssData = _.merge({}, res.locals, data); + const rssData = _.merge({}, res.locals, data); // Fetch RSS from the cache return rssCache diff --git a/core/frontend/services/settings/ensure-settings.js b/core/frontend/services/settings/ensure-settings.js index 2e87ff1a75..a8e83be1fe 100644 --- a/core/frontend/services/settings/ensure-settings.js +++ b/core/frontend/services/settings/ensure-settings.js @@ -1,9 +1,9 @@ -const fs = require('fs-extra'), - Promise = require('bluebird'), - path = require('path'), - debug = require('ghost-ignition').debug('frontend:services:settings:ensure-settings'), - common = require('../../../server/lib/common'), - config = require('../../../server/config'); +const fs = require('fs-extra'); +const Promise = require('bluebird'); +const path = require('path'); +const debug = require('ghost-ignition').debug('frontend:services:settings:ensure-settings'); +const common = require('../../../server/lib/common'); +const config = require('../../../server/config'); /** * Makes sure that all supported settings files are in the @@ -16,13 +16,13 @@ const fs = require('fs-extra'), * copy the default yaml file over. */ module.exports = function ensureSettingsFiles(knownSettings) { - const contentPath = config.getContentPath('settings'), - defaultSettingsPath = config.get('paths').defaultSettings; + const contentPath = config.getContentPath('settings'); + const defaultSettingsPath = config.get('paths').defaultSettings; return Promise.each(knownSettings, function (setting) { - const fileName = `${setting}.yaml`, - defaultFileName = `default-${fileName}`, - filePath = path.join(contentPath, fileName); + const fileName = `${setting}.yaml`; + const defaultFileName = `default-${fileName}`; + const filePath = path.join(contentPath, fileName); return fs.readFile(filePath, 'utf8') .catch({code: 'ENOENT'}, () => { diff --git a/core/frontend/services/settings/index.js b/core/frontend/services/settings/index.js index 589c1cda08..f9b2032a2f 100644 --- a/core/frontend/services/settings/index.js +++ b/core/frontend/services/settings/index.js @@ -68,8 +68,8 @@ module.exports = { * `/content/settings` directory. */ getAll: function getAll() { - const knownSettings = this.knownSettings(), - settingsToReturn = {}; + const knownSettings = this.knownSettings(); + const settingsToReturn = {}; _.each(knownSettings, function (setting) { settingsToReturn[setting] = SettingsLoader(setting); diff --git a/core/frontend/services/settings/loader.js b/core/frontend/services/settings/loader.js index 9a9d8ccc11..3eda489c56 100644 --- a/core/frontend/services/settings/loader.js +++ b/core/frontend/services/settings/loader.js @@ -1,10 +1,10 @@ -const fs = require('fs-extra'), - path = require('path'), - debug = require('ghost-ignition').debug('frontend:services:settings:settings-loader'), - common = require('../../../server/lib/common'), - config = require('../../../server/config'), - yamlParser = require('./yaml-parser'), - validate = require('./validate'); +const fs = require('fs-extra'); +const path = require('path'); +const debug = require('ghost-ignition').debug('frontend:services:settings:settings-loader'); +const common = require('../../../server/lib/common'); +const config = require('../../../server/config'); +const yamlParser = require('./yaml-parser'); +const validate = require('./validate'); /** * Reads the desired settings YAML file and passes the diff --git a/core/frontend/services/settings/yaml-parser.js b/core/frontend/services/settings/yaml-parser.js index c8bc335a0f..0c1c0cfbff 100644 --- a/core/frontend/services/settings/yaml-parser.js +++ b/core/frontend/services/settings/yaml-parser.js @@ -1,6 +1,6 @@ -const yaml = require('js-yaml'), - debug = require('ghost-ignition').debug('frontend:services:settings:yaml-parser'), - common = require('../../../server/lib/common'); +const yaml = require('js-yaml'); +const debug = require('ghost-ignition').debug('frontend:services:settings:yaml-parser'); +const common = require('../../../server/lib/common'); /** * Takes a YAML file, parses it and returns a JSON Object diff --git a/core/frontend/services/sitemap/base-generator.js b/core/frontend/services/sitemap/base-generator.js index 4f023762c5..1cdcb659e3 100644 --- a/core/frontend/services/sitemap/base-generator.js +++ b/core/frontend/services/sitemap/base-generator.js @@ -1,9 +1,9 @@ -const _ = require('lodash'), - xml = require('xml'), - moment = require('moment'), - path = require('path'), - urlUtils = require('../../../server/lib/url-utils'), - localUtils = require('./utils'); +const _ = require('lodash'); +const xml = require('xml'); +const moment = require('moment'); +const path = require('path'); +const urlUtils = require('../../../server/lib/url-utils'); +const localUtils = require('./utils'); // Sitemap specific xml namespace declarations that should not change const XMLNS_DECLS = { @@ -22,24 +22,28 @@ class BaseSiteMapGenerator { } generateXmlFromNodes() { - var self = this, - // Get a mapping of node to timestamp - timedNodes = _.map(this.nodeLookup, function (node, id) { - return { - id: id, - // Using negative here to sort newest to oldest - ts: -(self.nodeTimeLookup[id] || 0), - node: node - }; - }, []), - // Sort nodes by timestamp - sortedNodes = _.sortBy(timedNodes, 'ts'), - // Grab just the nodes - urlElements = _.map(sortedNodes, 'node'), - data = { - // Concat the elements to the _attr declaration - urlset: [XMLNS_DECLS].concat(urlElements) + const self = this; + + // Get a mapping of node to timestamp + const timedNodes = _.map(this.nodeLookup, function (node, id) { + return { + id: id, + // Using negative here to sort newest to oldest + ts: -(self.nodeTimeLookup[id] || 0), + node: node }; + }, []); + + // Sort nodes by timestamp + const sortedNodes = _.sortBy(timedNodes, 'ts'); + + // Grab just the nodes + const urlElements = _.map(sortedNodes, 'node'); + + const data = { + // Concat the elements to the _attr declaration + urlset: [XMLNS_DECLS].concat(urlElements) + }; // Return the xml return localUtils.getDeclarations() + xml(data); @@ -83,7 +87,8 @@ class BaseSiteMapGenerator { } createUrlNodeFromDatum(url, datum) { - let node, imgNode; + let node; + let imgNode; node = { url: [ @@ -103,9 +108,10 @@ class BaseSiteMapGenerator { createImageNodeFromDatum(datum) { // Check for cover first because user has cover but the rest only have image - var image = datum.cover_image || datum.profile_image || datum.feature_image, - imageUrl, - imageEl; + const image = datum.cover_image || datum.profile_image || datum.feature_image; + + let imageUrl; + let imageEl; if (!image) { return; diff --git a/core/frontend/services/sitemap/handler.js b/core/frontend/services/sitemap/handler.js index e0434e1a4e..da131f1f57 100644 --- a/core/frontend/services/sitemap/handler.js +++ b/core/frontend/services/sitemap/handler.js @@ -1,6 +1,6 @@ -const config = require('../../../server/config'), - Manager = require('./manager'), - manager = new Manager(); +const config = require('../../../server/config'); +const Manager = require('./manager'); +const manager = new Manager(); // Responsible for handling requests for sitemap files module.exports = function handler(siteApp) { @@ -22,8 +22,8 @@ module.exports = function handler(siteApp) { }); siteApp.get('/sitemap-:resource.xml', verifyResourceType, function sitemapResourceXML(req, res) { - var type = req.params.resource, - page = 1; + const type = req.params.resource; + const page = 1; res.set({ 'Cache-Control': 'public, max-age=' + config.get('caching:sitemap:maxAge'), diff --git a/core/frontend/services/sitemap/index-generator.js b/core/frontend/services/sitemap/index-generator.js index bce7a3f33d..a08a20e365 100644 --- a/core/frontend/services/sitemap/index-generator.js +++ b/core/frontend/services/sitemap/index-generator.js @@ -1,8 +1,8 @@ -const _ = require('lodash'), - xml = require('xml'), - moment = require('moment'), - urlUtils = require('../../../server/lib/url-utils'), - localUtils = require('./utils'); +const _ = require('lodash'); +const xml = require('xml'); +const moment = require('moment'); +const urlUtils = require('../../../server/lib/url-utils'); +const localUtils = require('./utils'); const XMLNS_DECLS = { _attr: { @@ -17,11 +17,12 @@ class SiteMapIndexGenerator { } getXml() { - const urlElements = this.generateSiteMapUrlElements(), - data = { - // Concat the elements to the _attr declaration - sitemapindex: [XMLNS_DECLS].concat(urlElements) - }; + const urlElements = this.generateSiteMapUrlElements(); + + const data = { + // Concat the elements to the _attr declaration + sitemapindex: [XMLNS_DECLS].concat(urlElements) + }; // Return the xml return localUtils.getDeclarations() + xml(data); @@ -29,8 +30,8 @@ class SiteMapIndexGenerator { generateSiteMapUrlElements() { return _.map(this.types, (resourceType) => { - var url = urlUtils.urlFor({relativeUrl: '/sitemap-' + resourceType.name + '.xml'}, true), - lastModified = resourceType.lastModified; + const url = urlUtils.urlFor({relativeUrl: '/sitemap-' + resourceType.name + '.xml'}, true); + const lastModified = resourceType.lastModified; return { sitemap: [ diff --git a/core/frontend/services/sitemap/manager.js b/core/frontend/services/sitemap/manager.js index ec63b6f5f2..52c45eb96e 100644 --- a/core/frontend/services/sitemap/manager.js +++ b/core/frontend/services/sitemap/manager.js @@ -1,9 +1,9 @@ -const common = require('../../../server/lib/common'), - IndexMapGenerator = require('./index-generator'), - PagesMapGenerator = require('./page-generator'), - PostsMapGenerator = require('./post-generator'), - UsersMapGenerator = require('./user-generator'), - TagsMapGenerator = require('./tag-generator'); +const common = require('../../../server/lib/common'); +const IndexMapGenerator = require('./index-generator'); +const PagesMapGenerator = require('./page-generator'); +const PostsMapGenerator = require('./post-generator'); +const UsersMapGenerator = require('./user-generator'); +const TagsMapGenerator = require('./tag-generator'); class SiteMapManager { constructor(options) { diff --git a/core/frontend/services/sitemap/page-generator.js b/core/frontend/services/sitemap/page-generator.js index bf4dc98e73..3ac496591c 100644 --- a/core/frontend/services/sitemap/page-generator.js +++ b/core/frontend/services/sitemap/page-generator.js @@ -1,5 +1,5 @@ -const _ = require('lodash'), - BaseMapGenerator = require('./base-generator'); +const _ = require('lodash'); +const BaseMapGenerator = require('./base-generator'); class PageMapGenerator extends BaseMapGenerator { constructor(opts) { diff --git a/core/frontend/services/sitemap/post-generator.js b/core/frontend/services/sitemap/post-generator.js index 75b34fc837..20d7018495 100644 --- a/core/frontend/services/sitemap/post-generator.js +++ b/core/frontend/services/sitemap/post-generator.js @@ -1,5 +1,5 @@ -const _ = require('lodash'), - BaseMapGenerator = require('./base-generator'); +const _ = require('lodash'); +const BaseMapGenerator = require('./base-generator'); class PostMapGenerator extends BaseMapGenerator { constructor(opts) { diff --git a/core/frontend/services/sitemap/tag-generator.js b/core/frontend/services/sitemap/tag-generator.js index 618b3b3983..9707e77c3a 100644 --- a/core/frontend/services/sitemap/tag-generator.js +++ b/core/frontend/services/sitemap/tag-generator.js @@ -1,5 +1,5 @@ -const _ = require('lodash'), - BaseMapGenerator = require('./base-generator'); +const _ = require('lodash'); +const BaseMapGenerator = require('./base-generator'); class TagsMapGenerator extends BaseMapGenerator { constructor(opts) { diff --git a/core/frontend/services/sitemap/user-generator.js b/core/frontend/services/sitemap/user-generator.js index 840d1d82ff..20535ed388 100644 --- a/core/frontend/services/sitemap/user-generator.js +++ b/core/frontend/services/sitemap/user-generator.js @@ -1,6 +1,6 @@ -const _ = require('lodash'), - validator = require('validator'), - BaseMapGenerator = require('./base-generator'); +const _ = require('lodash'); +const validator = require('validator'); +const BaseMapGenerator = require('./base-generator'); class UserMapGenerator extends BaseMapGenerator { constructor(opts) { diff --git a/core/frontend/services/sitemap/utils.js b/core/frontend/services/sitemap/utils.js index 86fff4b386..e0bd5fcaee 100644 --- a/core/frontend/services/sitemap/utils.js +++ b/core/frontend/services/sitemap/utils.js @@ -1,9 +1,9 @@ -var urlUtils = require('../../../server/lib/url-utils'), - sitemapsUtils; +const urlUtils = require('../../../server/lib/url-utils'); +let sitemapsUtils; sitemapsUtils = { getDeclarations: function () { - var baseUrl = urlUtils.urlFor('sitemap_xsl', true); + let baseUrl = urlUtils.urlFor('sitemap_xsl', true); baseUrl = baseUrl.replace(/^(http:|https:)/, ''); return '' + ''; diff --git a/core/frontend/services/themes/ThemeStorage.js b/core/frontend/services/themes/ThemeStorage.js index 9250d5f30d..0cfc3eb33b 100644 --- a/core/frontend/services/themes/ThemeStorage.js +++ b/core/frontend/services/themes/ThemeStorage.js @@ -1,10 +1,10 @@ -var fs = require('fs-extra'), - os = require('os'), - path = require('path'), - config = require('../../../server/config'), - security = require('../../../server/lib/security'), - {compress} = require('@tryghost/zip'), - LocalFileStorage = require('../../../server/adapters/storage/LocalFileStorage'); +const fs = require('fs-extra'); +const os = require('os'); +const path = require('path'); +const config = require('../../../server/config'); +const security = require('../../../server/lib/security'); +const {compress} = require('@tryghost/zip'); +const LocalFileStorage = require('../../../server/adapters/storage/LocalFileStorage'); /** * @TODO: combine with loader.js? @@ -21,16 +21,18 @@ class ThemeStorage extends LocalFileStorage { } serve(options) { - var self = this; + const self = this; return function downloadTheme(req, res, next) { - var themeName = options.name, - themePath = path.join(self.storagePath, themeName), - zipName = themeName + '.zip', - // store this in a unique temporary folder - zipBasePath = path.join(os.tmpdir(), security.identifier.uid(10)), - zipPath = path.join(zipBasePath, zipName), - stream; + const themeName = options.name; + const themePath = path.join(self.storagePath, themeName); + const zipName = themeName + '.zip'; + + // store this in a unique temporary folder + const zipBasePath = path.join(os.tmpdir(), security.identifier.uid(10)); + + const zipPath = path.join(zipBasePath, zipName); + let stream; fs.ensureDir(zipBasePath) .then(function () { diff --git a/core/frontend/services/themes/active.js b/core/frontend/services/themes/active.js index 4a98a3a015..f15d2cd3d1 100644 --- a/core/frontend/services/themes/active.js +++ b/core/frontend/services/themes/active.js @@ -11,14 +11,16 @@ * No properties marked with an _ should be used directly. * */ -var join = require('path').join, - _ = require('lodash'), - themeConfig = require('./config'), - themeEngines = require('./engines'), - config = require('../../../server/config'), - engine = require('./engine'), - // Current instance of ActiveTheme - currentActiveTheme; +const join = require('path').join; + +const _ = require('lodash'); +const themeConfig = require('./config'); +const themeEngines = require('./engines'); +const config = require('../../../server/config'); +const engine = require('./engine'); + +// Current instance of ActiveTheme +let currentActiveTheme; class ActiveTheme { /** diff --git a/core/frontend/services/themes/config/index.js b/core/frontend/services/themes/config/index.js index 946a5cb7b1..c55d0db9e4 100644 --- a/core/frontend/services/themes/config/index.js +++ b/core/frontend/services/themes/config/index.js @@ -1,9 +1,9 @@ -var _ = require('lodash'), - defaultConfig = require('./defaults'), - allowedKeys = ['posts_per_page', 'image_sizes']; +const _ = require('lodash'); +const defaultConfig = require('./defaults'); +const allowedKeys = ['posts_per_page', 'image_sizes']; module.exports.create = function configLoader(packageJson) { - var config = _.cloneDeep(defaultConfig); + let config = _.cloneDeep(defaultConfig); if (packageJson && Object.prototype.hasOwnProperty.call(packageJson, 'config')) { config = _.assign(config, _.pick(packageJson.config, allowedKeys)); diff --git a/core/frontend/services/themes/engine.js b/core/frontend/services/themes/engine.js index 0d8b58c5d9..5addd79c79 100644 --- a/core/frontend/services/themes/engine.js +++ b/core/frontend/services/themes/engine.js @@ -1,6 +1,6 @@ -var hbs = require('express-hbs'), - config = require('../../../server/config'), - instance = hbs.create(); +const hbs = require('express-hbs'); +const config = require('../../../server/config'); +const instance = hbs.create(); // @TODO think about a config option for this e.g. theme.devmode? if (config.get('env') !== 'production') { @@ -10,7 +10,7 @@ if (config.get('env') !== 'production') { instance.escapeExpression = instance.handlebars.Utils.escapeExpression; instance.configure = function configure(partialsPath) { - var hbsOptions = { + const hbsOptions = { partialsDir: [config.get('paths').helperTemplates], onCompile: function onCompile(exhbs, source) { return exhbs.handlebars.compile(source, {preventIndent: true}); diff --git a/core/frontend/services/themes/handlebars/register.js b/core/frontend/services/themes/handlebars/register.js index 67e67fc4a7..2d5fab0ebf 100644 --- a/core/frontend/services/themes/handlebars/register.js +++ b/core/frontend/services/themes/handlebars/register.js @@ -16,14 +16,15 @@ function asyncHelperWrapper(hbs, name, fn) { Promise.resolve(fn.call(this, context, options)).then(function asyncHelperSuccess(result) { cb(result); }).catch(function asyncHelperError(err) { - var wrappedErr = err instanceof errors.GhostError ? err : new errors.IncorrectUsageError({ - err: err, - context: 'registerAsyncThemeHelper: ' + name, - errorDetails: { - originalError: err - } - }), - result = config.get('env') === 'development' ? wrappedErr : ''; + const wrappedErr = err instanceof errors.GhostError ? err : new errors.IncorrectUsageError({ + err: err, + context: 'registerAsyncThemeHelper: ' + name, + errorDetails: { + originalError: err + } + }); + + const result = config.get('env') === 'development' ? wrappedErr : ''; logging.error(wrappedErr); diff --git a/core/frontend/services/themes/handlebars/template.js b/core/frontend/services/themes/handlebars/template.js index 9dd922f882..99e1413032 100644 --- a/core/frontend/services/themes/handlebars/template.js +++ b/core/frontend/services/themes/handlebars/template.js @@ -8,7 +8,7 @@ const {i18n} = require('../../../../server/lib/common'); // Execute a template helper // All template helpers are register as partial view. templates.execute = function execute(name, context, data) { - var partial = hbs.handlebars.partials[name]; + const partial = hbs.handlebars.partials[name]; if (partial === undefined) { throw new errors.IncorrectUsageError({ diff --git a/core/frontend/services/themes/index.js b/core/frontend/services/themes/index.js index c21084a3fa..bc8d3eb8a7 100644 --- a/core/frontend/services/themes/index.js +++ b/core/frontend/services/themes/index.js @@ -14,7 +14,7 @@ module.exports = { // Init themes module // TODO: move this once we're clear what needs to happen here init: function initThemes() { - var activeThemeName = settingsCache.get('active_theme'); + const activeThemeName = settingsCache.get('active_theme'); i18n.init(); diff --git a/core/frontend/services/themes/list.js b/core/frontend/services/themes/list.js index 287cdea27c..a0a9841564 100644 --- a/core/frontend/services/themes/list.js +++ b/core/frontend/services/themes/list.js @@ -1,8 +1,9 @@ /** * Store themes after loading them from the file system */ -var _ = require('lodash'), - themeListCache = {}; +const _ = require('lodash'); + +let themeListCache = {}; module.exports = { get: function get(key) { @@ -23,7 +24,7 @@ module.exports = { }, init: function init(themes) { - var self = this; + const self = this; // First, reset the cache themeListCache = {}; // For each theme, call set. Allows us to do processing on set later. diff --git a/core/frontend/services/themes/loader.js b/core/frontend/services/themes/loader.js index 7c2b530973..99c15ddd14 100644 --- a/core/frontend/services/themes/loader.js +++ b/core/frontend/services/themes/loader.js @@ -1,9 +1,9 @@ -var debug = require('ghost-ignition').debug('themes:loader'), - config = require('../../../server/config'), - packageJSON = require('../../../server/lib/fs/package-json'), - themeList = require('./list'), - loadAllThemes, - loadOneTheme; +const debug = require('ghost-ignition').debug('themes:loader'); +const config = require('../../../server/config'); +const packageJSON = require('../../../server/lib/fs/package-json'); +const themeList = require('./list'); +let loadAllThemes; +let loadOneTheme; loadAllThemes = function loadAllThemes() { return packageJSON.read diff --git a/core/frontend/services/themes/to-json.js b/core/frontend/services/themes/to-json.js index 894b2c7385..71b072c372 100644 --- a/core/frontend/services/themes/to-json.js +++ b/core/frontend/services/themes/to-json.js @@ -1,8 +1,8 @@ -var _ = require('lodash'), - themeList = require('./list'), - active = require('./active'), - packageJSON = require('../../../server/lib/fs/package-json'), - settingsCache = require('../../../server/services/settings/cache'); +const _ = require('lodash'); +const themeList = require('./list'); +const active = require('./active'); +const packageJSON = require('../../../server/lib/fs/package-json'); +const settingsCache = require('../../../server/services/settings/cache'); /** * @@ -17,7 +17,8 @@ var _ = require('lodash'), * @return {*} */ module.exports = function toJSON(name, checkedTheme) { - var themeResult, toFilter; + let themeResult; + let toFilter; if (!name) { toFilter = themeList.getAll(); diff --git a/core/frontend/services/url/Queue.js b/core/frontend/services/url/Queue.js index cd8d17cfb6..3568bce691 100644 --- a/core/frontend/services/url/Queue.js +++ b/core/frontend/services/url/Queue.js @@ -1,7 +1,7 @@ -const debug = require('ghost-ignition').debug('services:url:queue'), - EventEmitter = require('events').EventEmitter, - _ = require('lodash'), - common = require('../../../server/lib/common'); +const debug = require('ghost-ignition').debug('services:url:queue'); +const EventEmitter = require('events').EventEmitter; +const _ = require('lodash'); +const common = require('../../../server/lib/common'); /** * ### Purpose of this queue @@ -102,9 +102,9 @@ class Queue extends EventEmitter { * @param {Object} options */ run(options) { - const event = options.event, - action = options.action, - eventData = options.eventData; + const event = options.event; + const action = options.action; + const eventData = options.eventData; clearTimeout(this.toNotify[action].timeout); this.toNotify[action].timeout = null; diff --git a/core/frontend/services/url/Resource.js b/core/frontend/services/url/Resource.js index f7ac08fe17..039d2c114a 100644 --- a/core/frontend/services/url/Resource.js +++ b/core/frontend/services/url/Resource.js @@ -1,5 +1,5 @@ -const EventEmitter = require('events').EventEmitter, - common = require('../../../server/lib/common'); +const EventEmitter = require('events').EventEmitter; +const common = require('../../../server/lib/common'); /** * Resource cache. diff --git a/core/frontend/services/url/UrlGenerator.js b/core/frontend/services/url/UrlGenerator.js index 3b44966bdf..246727c71e 100644 --- a/core/frontend/services/url/UrlGenerator.js +++ b/core/frontend/services/url/UrlGenerator.js @@ -1,27 +1,28 @@ -const _ = require('lodash'), - nql = require('@nexes/nql'), - debug = require('ghost-ignition').debug('services:url:generator'), - localUtils = require('../../../server/lib/url-utils'), - // @TODO: merge with filter plugin - EXPANSIONS = [{ - key: 'author', - replacement: 'authors.slug' - }, { - key: 'tags', - replacement: 'tags.slug' - }, { - key: 'tag', - replacement: 'tags.slug' - }, { - key: 'authors', - replacement: 'authors.slug' - }, { - key: 'primary_tag', - replacement: 'primary_tag.slug' - }, { - key: 'primary_author', - replacement: 'primary_author.slug' - }]; +const _ = require('lodash'); +const nql = require('@nexes/nql'); +const debug = require('ghost-ignition').debug('services:url:generator'); +const localUtils = require('../../../server/lib/url-utils'); + +// @TODO: merge with filter plugin +const EXPANSIONS = [{ + key: 'author', + replacement: 'authors.slug' +}, { + key: 'tags', + replacement: 'tags.slug' +}, { + key: 'tag', + replacement: 'tags.slug' +}, { + key: 'authors', + replacement: 'authors.slug' +}, { + key: 'primary_tag', + replacement: 'primary_tag.slug' +}, { + key: 'primary_author', + replacement: 'primary_author.slug' +}]; const mapNQLKeyValues = require('../../../shared/nql-map-key-values'); diff --git a/core/frontend/services/url/UrlService.js b/core/frontend/services/url/UrlService.js index 7b0773a5c4..6982542148 100644 --- a/core/frontend/services/url/UrlService.js +++ b/core/frontend/services/url/UrlService.js @@ -1,12 +1,12 @@ -const _debug = require('ghost-ignition').debug._base, - debug = _debug('ghost:services:url:service'), - _ = require('lodash'), - common = require('../../../server/lib/common'), - UrlGenerator = require('./UrlGenerator'), - Queue = require('./Queue'), - Urls = require('./Urls'), - Resources = require('./Resources'), - urlUtils = require('../../../server/lib/url-utils'); +const _debug = require('ghost-ignition').debug._base; +const debug = _debug('ghost:services:url:service'); +const _ = require('lodash'); +const common = require('../../../server/lib/common'); +const UrlGenerator = require('./UrlGenerator'); +const Queue = require('./Queue'); +const Urls = require('./Urls'); +const Resources = require('./Resources'); +const urlUtils = require('../../../server/lib/url-utils'); /** * The url service class holds all instances in a centralised place. diff --git a/core/frontend/services/url/index.js b/core/frontend/services/url/index.js index cd4b29fe23..7f55723216 100644 --- a/core/frontend/services/url/index.js +++ b/core/frontend/services/url/index.js @@ -1,5 +1,5 @@ -const UrlService = require('./UrlService'), - urlService = new UrlService(); +const UrlService = require('./UrlService'); +const urlService = new UrlService(); // Singleton module.exports = urlService; diff --git a/core/server/adapters/scheduling/SchedulingDefault.js b/core/server/adapters/scheduling/SchedulingDefault.js index cf66fea19d..cad990f06f 100644 --- a/core/server/adapters/scheduling/SchedulingDefault.js +++ b/core/server/adapters/scheduling/SchedulingDefault.js @@ -99,8 +99,8 @@ SchedulingDefault.prototype.unschedule = function (object, options = {bootstrap: */ SchedulingDefault.prototype.run = function () { const self = this; - let timeout = null, - recursiveRun; + let timeout = null; + let recursiveRun; // NOTE: Ensure the scheduler never runs twice. if (this.isRunning) { @@ -111,8 +111,8 @@ SchedulingDefault.prototype.run = function () { recursiveRun = function recursiveRun() { timeout = setTimeout(function () { - const times = Object.keys(self.allJobs), - nextJobs = {}; + const times = Object.keys(self.allJobs); + const nextJobs = {}; // CASE: We stop till the offset is too big. We are only interested in jobs which need get executed soon. times.every(function (time) { @@ -142,11 +142,11 @@ SchedulingDefault.prototype.run = function () { * @private */ SchedulingDefault.prototype._addJob = function (object) { - let timestamp = moment(object.time).valueOf(), - keys = [], - sortedJobs = {}, - instantJob = {}, - i = 0; + let timestamp = moment(object.time).valueOf(); + let keys = []; + let sortedJobs = {}; + let instantJob = {}; + let i = 0; // CASE: should have been already pinged or should be pinged soon if (moment(timestamp).diff(moment(), 'minutes') < this.offsetInMinutes) { @@ -218,12 +218,12 @@ SchedulingDefault.prototype._deleteJob = function (object) { * We can't use "process.nextTick" otherwise we will block I/O operations. */ SchedulingDefault.prototype._execute = function (jobs) { - const keys = Object.keys(jobs), - self = this; + const keys = Object.keys(jobs); + const self = this; keys.forEach(function (timestamp) { - let timeout = null, - diff = moment(Number(timestamp)).diff(moment()); + let timeout = null; + let diff = moment(Number(timestamp)).diff(moment()); // NOTE: awake a little before... timeout = setTimeout(function () { diff --git a/core/server/adapters/storage/LocalFileStorage.js b/core/server/adapters/storage/LocalFileStorage.js index cccabbebd0..9b1602751c 100644 --- a/core/server/adapters/storage/LocalFileStorage.js +++ b/core/server/adapters/storage/LocalFileStorage.js @@ -1,16 +1,17 @@ // # Local File System Image Storage module // The (default) module for storing images, using the local file system -const serveStatic = require('express').static, - fs = require('fs-extra'), - path = require('path'), - Promise = require('bluebird'), - moment = require('moment'), - config = require('../../config'), - common = require('../../lib/common'), - constants = require('../../lib/constants'), - urlUtils = require('../../lib/url-utils'), - StorageBase = require('ghost-storage-base'); +const serveStatic = require('express').static; + +const fs = require('fs-extra'); +const path = require('path'); +const Promise = require('bluebird'); +const moment = require('moment'); +const config = require('../../config'); +const common = require('../../lib/common'); +const constants = require('../../lib/constants'); +const urlUtils = require('../../lib/url-utils'); +const StorageBase = require('ghost-storage-base'); class LocalFileStore extends StorageBase { constructor() { diff --git a/core/server/adapters/storage/utils.js b/core/server/adapters/storage/utils.js index 1aa729bee6..8db3b10cba 100644 --- a/core/server/adapters/storage/utils.js +++ b/core/server/adapters/storage/utils.js @@ -15,16 +15,17 @@ const urlUtils = require('../../lib/url-utils'); exports.getLocalFileStoragePath = function getLocalFileStoragePath(imagePath) { // The '/' in urlJoin is necessary to add the '/' to `content/images`, if no subdirectory is setup const urlRegExp = new RegExp(`^${urlUtils.urlJoin( - urlUtils.urlFor('home', true), - urlUtils.getSubdir(), - '/', - urlUtils.STATIC_IMAGE_URL_PREFIX)}` - ), - filePathRegExp = new RegExp(`^${urlUtils.urlJoin( - urlUtils.getSubdir(), - '/', - urlUtils.STATIC_IMAGE_URL_PREFIX)}` - ); + urlUtils.urlFor('home', true), + urlUtils.getSubdir(), + '/', + urlUtils.STATIC_IMAGE_URL_PREFIX)}` + ); + + const filePathRegExp = new RegExp(`^${urlUtils.urlJoin( + urlUtils.getSubdir(), + '/', + urlUtils.STATIC_IMAGE_URL_PREFIX)}` + ); if (imagePath.match(urlRegExp)) { return imagePath.replace(urlRegExp, ''); diff --git a/core/server/analytics-events.js b/core/server/analytics-events.js index 7a8d1533d4..62e5d343a7 100644 --- a/core/server/analytics-events.js +++ b/core/server/analytics-events.js @@ -1,14 +1,14 @@ -var _ = require('lodash'), - Analytics = require('analytics-node'), - config = require('./config'), - common = require('./lib/common'), - analytics; +const _ = require('lodash'); +const Analytics = require('analytics-node'); +const config = require('./config'); +const common = require('./lib/common'); +let analytics; module.exports.init = function () { analytics = new Analytics(config.get('segment:key')); - var toTrack, - trackDefaults = config.get('segment:trackDefaults') || {}, - prefix = config.get('segment:prefix') || ''; + let toTrack; + const trackDefaults = config.get('segment:trackDefaults') || {}; + const prefix = config.get('segment:prefix') || ''; toTrack = [ { diff --git a/core/server/api/canary/notifications.js b/core/server/api/canary/notifications.js index 5fef525113..38486a2b11 100644 --- a/core/server/api/canary/notifications.js +++ b/core/server/api/canary/notifications.js @@ -162,11 +162,12 @@ module.exports = { const allNotifications = _private.fetchAllNotifications(); const notificationToMarkAsSeen = allNotifications.find((notification) => { - return notification.id === frame.options.notification_id; - }), - notificationToMarkAsSeenIndex = allNotifications.findIndex((notification) => { - return notification.id === frame.options.notification_id; - }); + return notification.id === frame.options.notification_id; + }); + + const notificationToMarkAsSeenIndex = allNotifications.findIndex((notification) => { + return notification.id === frame.options.notification_id; + }); if (notificationToMarkAsSeenIndex > -1 && !notificationToMarkAsSeen.dismissible) { return Promise.reject(new common.errors.NoPermissionError({ diff --git a/core/server/api/shared/pipeline.js b/core/server/api/shared/pipeline.js index 66409da1cc..e655968861 100644 --- a/core/server/api/shared/pipeline.js +++ b/core/server/api/shared/pipeline.js @@ -189,7 +189,9 @@ const pipeline = (apiController, apiUtils, apiType) => { obj[key] = function wrapper() { const apiConfig = {docName, method}; - let options, data, frame; + let options; + let data; + let frame; if (arguments.length === 2) { data = arguments[0]; diff --git a/core/server/api/v2/notifications.js b/core/server/api/v2/notifications.js index 5fef525113..38486a2b11 100644 --- a/core/server/api/v2/notifications.js +++ b/core/server/api/v2/notifications.js @@ -162,11 +162,12 @@ module.exports = { const allNotifications = _private.fetchAllNotifications(); const notificationToMarkAsSeen = allNotifications.find((notification) => { - return notification.id === frame.options.notification_id; - }), - notificationToMarkAsSeenIndex = allNotifications.findIndex((notification) => { - return notification.id === frame.options.notification_id; - }); + return notification.id === frame.options.notification_id; + }); + + const notificationToMarkAsSeenIndex = allNotifications.findIndex((notification) => { + return notification.id === frame.options.notification_id; + }); if (notificationToMarkAsSeenIndex > -1 && !notificationToMarkAsSeen.dismissible) { return Promise.reject(new common.errors.NoPermissionError({ diff --git a/core/server/config/index.js b/core/server/config/index.js index 1ed06aebc8..1e8b2e62a7 100644 --- a/core/server/config/index.js +++ b/core/server/config/index.js @@ -1,32 +1,32 @@ -var Nconf = require('nconf'), - path = require('path'), - _debug = require('ghost-ignition').debug._base, - debug = _debug('ghost:config'), - localUtils = require('./utils'), - env = process.env.NODE_ENV || 'development', - _private = {}; +const Nconf = require('nconf'); +const path = require('path'); +const _debug = require('ghost-ignition').debug._base; +const debug = _debug('ghost:config'); +const localUtils = require('./utils'); +const env = process.env.NODE_ENV || 'development'; +const _private = {}; _private.loadNconf = function loadNconf(options) { debug('config start'); options = options || {}; - var baseConfigPath = options.baseConfigPath || __dirname, - customConfigPath = options.customConfigPath || process.cwd(), - nconf = new Nconf.Provider(); + const baseConfigPath = options.baseConfigPath || __dirname; + const customConfigPath = options.customConfigPath || process.cwd(); + const nconf = new Nconf.Provider(); /** - * no channel can override the overrides - */ + * no channel can override the overrides + */ nconf.file('overrides', path.join(baseConfigPath, 'overrides.json')); /** - * command line arguments - */ + * command line arguments + */ nconf.argv(); /** - * env arguments - */ + * env arguments + */ nconf.env({ separator: '__', parseValues: true @@ -38,9 +38,9 @@ _private.loadNconf = function loadNconf(options) { nconf.file('defaults', path.join(baseConfigPath, 'defaults.json')); /** - * transform all relative paths to absolute paths - * transform sqlite filename path for Ghost-CLI - */ + * transform all relative paths to absolute paths + * transform sqlite filename path for Ghost-CLI + */ nconf.makePathsAbsolute = localUtils.makePathsAbsolute.bind(nconf); nconf.isPrivacyDisabled = localUtils.isPrivacyDisabled.bind(nconf); nconf.getContentPath = localUtils.getContentPath.bind(nconf); @@ -53,19 +53,19 @@ _private.loadNconf = function loadNconf(options) { nconf.makePathsAbsolute(nconf.get('database:connection'), 'database:connection'); } /** - * Check if the URL in config has a protocol - */ + * Check if the URL in config has a protocol + */ nconf.checkUrlProtocol = localUtils.checkUrlProtocol.bind(nconf); nconf.checkUrlProtocol(); /** - * Ensure that the content path exists - */ + * Ensure that the content path exists + */ nconf.doesContentPathExist(); /** - * values we have to set manual - */ + * values we have to set manual + */ nconf.set('env', env); // Wrap this in a check, because else nconf.get() is executed unnecessarily diff --git a/core/server/config/utils.js b/core/server/config/utils.js index 4d405508b6..834233e5ca 100644 --- a/core/server/config/utils.js +++ b/core/server/config/utils.js @@ -1,6 +1,6 @@ -var path = require('path'), - fs = require('fs-extra'), - _ = require('lodash'); +const path = require('path'); +const fs = require('fs-extra'); +const _ = require('lodash'); exports.isPrivacyDisabled = function isPrivacyDisabled(privacyFlag) { if (!this.get('privacy')) { @@ -29,7 +29,7 @@ exports.isPrivacyDisabled = function isPrivacyDisabled(privacyFlag) { * Path can be a "." to re-present current folder */ exports.makePathsAbsolute = function makePathsAbsolute(obj, parent) { - var self = this; + const self = this; _.each(obj, function (configValue, pathsKey) { if (_.isObject(configValue)) { @@ -80,7 +80,7 @@ exports.doesContentPathExist = function doesContentPathExist() { * Check if the URL in config has a protocol and sanitise it if not including a warning that it should be changed */ exports.checkUrlProtocol = function checkUrlProtocol() { - var url = this.get('url'); + const url = this.get('url'); if (!url.match(/^https?:\/\//i)) { throw new Error('URL in config must be provided with protocol, eg. "http://my-ghost-blog.com"'); @@ -95,7 +95,7 @@ exports.checkUrlProtocol = function checkUrlProtocol() { * https://github.com/indexzero/nconf/issues/235#issuecomment-257606507 */ exports.sanitizeDatabaseProperties = function sanitizeDatabaseProperties() { - var database = this.get('database'); + const database = this.get('database'); if (this.get('database:client') === 'mysql') { delete database.connection.filename; diff --git a/core/server/data/db/backup.js b/core/server/data/db/backup.js index 3075b94c53..5d2547685b 100644 --- a/core/server/data/db/backup.js +++ b/core/server/data/db/backup.js @@ -1,18 +1,18 @@ // # Backup Database // Provides for backing up the database before making potentially destructive changes -var fs = require('fs-extra'), - path = require('path'), - Promise = require('bluebird'), - config = require('../../config'), - common = require('../../lib/common'), - urlUtils = require('../../lib/url-utils'), - exporter = require('../exporter'), +const fs = require('fs-extra'); - writeExportFile, - backup; +const path = require('path'); +const Promise = require('bluebird'); +const config = require('../../config'); +const common = require('../../lib/common'); +const urlUtils = require('../../lib/url-utils'); +const exporter = require('../exporter'); +let writeExportFile; +let backup; writeExportFile = function writeExportFile(exportResult) { - var filename = path.resolve(urlUtils.urlJoin(config.get('paths').contentPath, 'data', exportResult.filename)); + const filename = path.resolve(urlUtils.urlJoin(config.get('paths').contentPath, 'data', exportResult.filename)); return fs.writeFile(filename, JSON.stringify(exportResult.data)).return(filename); }; @@ -41,7 +41,7 @@ backup = function backup(options) { common.logging.info('Creating database backup'); options = options || {}; - var props = { + const props = { data: exporter.doExport(options), filename: exporter.fileName(options) }; diff --git a/core/server/data/db/connection.js b/core/server/data/db/connection.js index 78f5135375..595e489ab1 100644 --- a/core/server/data/db/connection.js +++ b/core/server/data/db/connection.js @@ -1,14 +1,14 @@ -var knex = require('knex'), - config = require('../../config'), - common = require('../../lib/common'), - knexInstance; +const knex = require('knex'); +const config = require('../../config'); +const common = require('../../lib/common'); +let knexInstance; // @TODO: // - if you require this file before config file was loaded, // - then this file is cached and you have no chance to connect to the db anymore // - bring dynamic into this file (db.connect()) function configure(dbConfig) { - var client = dbConfig.client; + const client = dbConfig.client; if (client === 'sqlite3') { dbConfig.useNullAsDefault = Object.prototype.hasOwnProperty.call(dbConfig, 'useNullAsDefault') ? dbConfig.useNullAsDefault : true; diff --git a/core/server/data/db/index.js b/core/server/data/db/index.js index b1d2d03667..49883ca90e 100644 --- a/core/server/data/db/index.js +++ b/core/server/data/db/index.js @@ -1,4 +1,4 @@ -var connection; +let connection; Object.defineProperty(exports, 'knex', { enumerable: true, diff --git a/core/server/data/db/migrator.js b/core/server/data/db/migrator.js index 623c5d8e33..689768daab 100644 --- a/core/server/data/db/migrator.js +++ b/core/server/data/db/migrator.js @@ -1,12 +1,14 @@ -const KnexMigrator = require('knex-migrator'), - config = require('../../config'), - common = require('../../lib/common'), - knexMigrator = new KnexMigrator({ - knexMigratorFilePath: config.get('paths:appRoot') - }); +const KnexMigrator = require('knex-migrator'); +const config = require('../../config'); +const common = require('../../lib/common'); + +const knexMigrator = new KnexMigrator({ + knexMigratorFilePath: config.get('paths:appRoot') +}); module.exports.getState = () => { - let state, err; + let state; + let err; return knexMigrator.isDatabaseOK() .then(() => { diff --git a/core/server/data/exporter/index.js b/core/server/data/exporter/index.js index 05bcac2218..9aa88da099 100644 --- a/core/server/data/exporter/index.js +++ b/core/server/data/exporter/index.js @@ -1,32 +1,36 @@ -var _ = require('lodash'), - Promise = require('bluebird'), - db = require('../../data/db'), - commands = require('../schema').commands, - ghostVersion = require('../../lib/ghost-version'), - common = require('../../lib/common'), - security = require('../../lib/security'), - models = require('../../models'), - EXCLUDED_TABLES = ['sessions', 'mobiledoc_revisions'], - EXCLUDED_FIELDS_CONDITIONS = { - settings: [{ - operator: 'whereNot', - key: 'key', - value: 'permalinks' - }] - }, - modelOptions = {context: {internal: true}}, +const _ = require('lodash'); +const Promise = require('bluebird'); +const db = require('../../data/db'); +const commands = require('../schema').commands; +const ghostVersion = require('../../lib/ghost-version'); +const common = require('../../lib/common'); +const security = require('../../lib/security'); +const models = require('../../models'); +const EXCLUDED_TABLES = ['sessions', 'mobiledoc_revisions']; - // private - getVersionAndTables, - exportTable, +const EXCLUDED_FIELDS_CONDITIONS = { + settings: [{ + operator: 'whereNot', + key: 'key', + value: 'permalinks' + }] +}; - // public - doExport, - exportFileName; +const modelOptions = {context: {internal: true}}; + +// private +let getVersionAndTables; + +let exportTable; + +// public +let doExport; + +let exportFileName; exportFileName = function exportFileName(options) { - var datetime = require('moment')().format('YYYY-MM-DD-HH-mm-ss'), - title = ''; + const datetime = require('moment')().format('YYYY-MM-DD-HH-mm-ss'); + let title = ''; options = options || {}; @@ -48,7 +52,7 @@ exportFileName = function exportFileName(options) { }; getVersionAndTables = function getVersionAndTables(options) { - var props = { + const props = { version: ghostVersion.full, tables: commands.getTables(options.transacting) }; @@ -74,7 +78,8 @@ exportTable = function exportTable(tableName, options) { doExport = function doExport(options) { options = options || {include: []}; - var tables, version; + let tables; + let version; return getVersionAndTables(options).then(function exportAllTables(result) { tables = result.tables; @@ -84,7 +89,7 @@ doExport = function doExport(options) { return exportTable(tableName, options); }); }).then(function formatData(tableData) { - var exportData = { + const exportData = { meta: { exported_on: new Date().getTime(), version: version diff --git a/core/server/data/importer/handlers/image.js b/core/server/data/importer/handlers/image.js index d9c1fa44d0..3e9ce8ecd8 100644 --- a/core/server/data/importer/handlers/image.js +++ b/core/server/data/importer/handlers/image.js @@ -1,11 +1,10 @@ -var _ = require('lodash'), - Promise = require('bluebird'), - path = require('path'), - config = require('../../../config'), - urlUtils = require('../../../lib/url-utils'), - storage = require('../../../adapters/storage'), - - ImageHandler; +const _ = require('lodash'); +const Promise = require('bluebird'); +const path = require('path'); +const config = require('../../../config'); +const urlUtils = require('../../../lib/url-utils'); +const storage = require('../../../adapters/storage'); +let ImageHandler; ImageHandler = { type: 'images', @@ -14,16 +13,17 @@ ImageHandler = { directories: ['images', 'content'], loadFile: function (files, baseDir) { - var store = storage.getStorage(), - baseDirRegex = baseDir ? new RegExp('^' + baseDir + '/') : new RegExp(''), - imageFolderRegexes = _.map(urlUtils.STATIC_IMAGE_URL_PREFIX.split('/'), function (dir) { - return new RegExp('^' + dir + '/'); - }); + const store = storage.getStorage(); + const baseDirRegex = baseDir ? new RegExp('^' + baseDir + '/') : new RegExp(''); + + const imageFolderRegexes = _.map(urlUtils.STATIC_IMAGE_URL_PREFIX.split('/'), function (dir) { + return new RegExp('^' + dir + '/'); + }); // normalize the directory structure files = _.map(files, function (file) { - var noBaseDir = file.name.replace(baseDirRegex, ''), - noGhostDirs = noBaseDir; + const noBaseDir = file.name.replace(baseDirRegex, ''); + let noGhostDirs = noBaseDir; _.each(imageFolderRegexes, function (regex) { noGhostDirs = noGhostDirs.replace(regex, ''); diff --git a/core/server/data/importer/handlers/json.js b/core/server/data/importer/handlers/json.js index 321d12c7f1..66370ca7e4 100644 --- a/core/server/data/importer/handlers/json.js +++ b/core/server/data/importer/handlers/json.js @@ -1,8 +1,8 @@ -var _ = require('lodash'), - Promise = require('bluebird'), - fs = require('fs-extra'), - common = require('../../../lib/common'), - JSONHandler; +const _ = require('lodash'); +const Promise = require('bluebird'); +const fs = require('fs-extra'); +const common = require('../../../lib/common'); +let JSONHandler; JSONHandler = { type: 'data', @@ -12,10 +12,10 @@ JSONHandler = { loadFile: function (files, startDir) { // eslint-disable-line no-unused-vars // @TODO: Handle multiple JSON files - var filePath = files[0].path; + const filePath = files[0].path; return fs.readFile(filePath).then(function (fileData) { - var importData; + let importData; try { importData = JSON.parse(fileData); diff --git a/core/server/data/importer/handlers/markdown.js b/core/server/data/importer/handlers/markdown.js index e694bfcb77..b39aed18ec 100644 --- a/core/server/data/importer/handlers/markdown.js +++ b/core/server/data/importer/handlers/markdown.js @@ -1,21 +1,19 @@ -var _ = require('lodash'), - Promise = require('bluebird'), - fs = require('fs-extra'), - moment = require('moment'), - - featuredImageRegex = /^(!\[]\(([^)]*?)\)\s+)(?=#)/, - titleRegex = /^#\s?([\w\W]*?)(?=\n)/, - statusRegex = /(published||draft)-/, - dateRegex = /(\d{4}-\d{2}-\d{2})-/, - - processDateTime, - processFileName, - processMarkdownFile, - MarkdownHandler; +const _ = require('lodash'); +const Promise = require('bluebird'); +const fs = require('fs-extra'); +const moment = require('moment'); +const featuredImageRegex = /^(!\[]\(([^)]*?)\)\s+)(?=#)/; +const titleRegex = /^#\s?([\w\W]*?)(?=\n)/; +const statusRegex = /(published||draft)-/; +const dateRegex = /(\d{4}-\d{2}-\d{2})-/; +let processDateTime; +let processFileName; +let processMarkdownFile; +let MarkdownHandler; // Takes a date from the filename in y-m-d-h-m form, and converts it into a Date ready to import processDateTime = function (post, datetime) { - var format = 'YYYY-MM-DD-HH-mm'; + const format = 'YYYY-MM-DD-HH-mm'; datetime = moment.utc(datetime, format).valueOf(); if (post.status && post.status === 'published') { @@ -28,9 +26,9 @@ processDateTime = function (post, datetime) { }; processFileName = function (filename) { - var post = {}, - name = filename.split('.')[0], - match; + let post = {}; + let name = filename.split('.')[0]; + let match; // Parse out the status match = name.match(statusRegex); @@ -54,8 +52,8 @@ processFileName = function (filename) { }; processMarkdownFile = function (filename, content) { - var post = processFileName(filename), - match; + const post = processFileName(filename); + let match; content = content.replace(/\r\n/gm, '\n'); @@ -87,9 +85,9 @@ MarkdownHandler = { directories: [], loadFile: function (files, startDir) { - var startDirRegex = startDir ? new RegExp('^' + startDir + '/') : new RegExp(''), - posts = [], - ops = []; + const startDirRegex = startDir ? new RegExp('^' + startDir + '/') : new RegExp(''); + const posts = []; + const ops = []; _.each(files, function (file) { ops.push(fs.readFile(file.path).then(function (content) { diff --git a/core/server/data/importer/importers/data/base.js b/core/server/data/importer/importers/data/base.js index 8057829dd7..b2c3cc0607 100644 --- a/core/server/data/importer/importers/data/base.js +++ b/core/server/data/importer/importers/data/base.js @@ -1,10 +1,10 @@ -const debug = require('ghost-ignition').debug('importer:base'), - _ = require('lodash'), - Promise = require('bluebird'), - ObjectId = require('bson-objectid'), - common = require('../../../../lib/common'), - sequence = require('../../../../lib/promise/sequence'), - models = require('../../../../models'); +const debug = require('ghost-ignition').debug('importer:base'); +const _ = require('lodash'); +const Promise = require('bluebird'); +const ObjectId = require('bson-objectid'); +const common = require('../../../../lib/common'); +const sequence = require('../../../../lib/promise/sequence'); +const models = require('../../../../models'); class Base { constructor(allDataFromFile, options) { @@ -108,7 +108,8 @@ class Base { } handleError(errs, obj) { - let errorsToReject = [], problems = []; + let errorsToReject = []; + let problems = []; // CASE: validation errors, see models/base/events.js onValidate if (!_.isArray(errs)) { diff --git a/core/server/data/importer/importers/data/index.js b/core/server/data/importer/importers/data/index.js index 3c2af3e0b5..b023c24707 100644 --- a/core/server/data/importer/importers/data/index.js +++ b/core/server/data/importer/importers/data/index.js @@ -1,17 +1,17 @@ -var _ = require('lodash'), - Promise = require('bluebird'), - semver = require('semver'), - common = require('../../../../lib/common'), - debug = require('ghost-ignition').debug('importer:data'), - sequence = require('../../../../lib/promise/sequence'), - models = require('../../../../models'), - PostsImporter = require('./posts'), - TagsImporter = require('./tags'), - SettingsImporter = require('./settings'), - UsersImporter = require('./users'), - RolesImporter = require('./roles'), - importers = {}, - DataImporter; +const _ = require('lodash'); +const Promise = require('bluebird'); +const semver = require('semver'); +const common = require('../../../../lib/common'); +const debug = require('ghost-ignition').debug('importer:data'); +const sequence = require('../../../../lib/promise/sequence'); +const models = require('../../../../models'); +const PostsImporter = require('./posts'); +const TagsImporter = require('./tags'); +const SettingsImporter = require('./settings'); +const UsersImporter = require('./users'); +const RolesImporter = require('./roles'); +let importers = {}; +let DataImporter; DataImporter = { type: 'data', @@ -35,7 +35,11 @@ DataImporter = { doImport: function doImport(importData, importOptions) { importOptions = importOptions || {}; - var ops = [], errors = [], results = [], modelOptions = { + const ops = []; + let errors = []; + let results = []; + + const modelOptions = { importing: true, context: { internal: true @@ -128,7 +132,7 @@ DataImporter = { * originalData: data from the json file * problems: warnings */ - var toReturn = { + const toReturn = { data: {}, originalData: importData.data, problems: [] diff --git a/core/server/data/importer/importers/data/roles.js b/core/server/data/importer/importers/data/roles.js index becd42a166..43103fa9a6 100644 --- a/core/server/data/importer/importers/data/roles.js +++ b/core/server/data/importer/importers/data/roles.js @@ -1,5 +1,5 @@ -const debug = require('ghost-ignition').debug('importer:roles'), - BaseImporter = require('./base'); +const debug = require('ghost-ignition').debug('importer:roles'); +const BaseImporter = require('./base'); class RolesImporter extends BaseImporter { constructor(allDataFromFile) { diff --git a/core/server/data/importer/importers/data/tags.js b/core/server/data/importer/importers/data/tags.js index 98314beba3..b14e27025f 100644 --- a/core/server/data/importer/importers/data/tags.js +++ b/core/server/data/importer/importers/data/tags.js @@ -1,8 +1,8 @@ -const debug = require('ghost-ignition').debug('importer:tags'), - Promise = require('bluebird'), - _ = require('lodash'), - BaseImporter = require('./base'), - models = require('../../../../models'); +const debug = require('ghost-ignition').debug('importer:tags'); +const Promise = require('bluebird'); +const _ = require('lodash'); +const BaseImporter = require('./base'); +const models = require('../../../../models'); class TagsImporter extends BaseImporter { constructor(allDataFromFile) { diff --git a/core/server/data/importer/importers/data/users.js b/core/server/data/importer/importers/data/users.js index 970d754756..0e7d2c223b 100644 --- a/core/server/data/importer/importers/data/users.js +++ b/core/server/data/importer/importers/data/users.js @@ -1,7 +1,7 @@ -const debug = require('ghost-ignition').debug('importer:users'), - _ = require('lodash'), - BaseImporter = require('./base'), - models = require('../../../../models'); +const debug = require('ghost-ignition').debug('importer:users'); +const _ = require('lodash'); +const BaseImporter = require('./base'); +const models = require('../../../../models'); class UsersImporter extends BaseImporter { constructor(allDataFromFile) { @@ -30,7 +30,8 @@ class UsersImporter extends BaseImporter { beforeImport() { debug('beforeImport'); - let role, lookup = {}; + let role; + let lookup = {}; // NOTE: sort out duplicated roles based on incremental id _.each(this.requiredFromFile.roles_users, (attachedRole) => { diff --git a/core/server/data/importer/importers/image.js b/core/server/data/importer/importers/image.js index 4b6f69a1e8..015f9a2066 100644 --- a/core/server/data/importer/importers/image.js +++ b/core/server/data/importer/importers/image.js @@ -1,11 +1,11 @@ -var _ = require('lodash'), - Promise = require('bluebird'), - storage = require('../../../adapters/storage'), - replaceImage, - ImageImporter, - preProcessPosts, - preProcessTags, - preProcessUsers; +const _ = require('lodash'); +const Promise = require('bluebird'); +const storage = require('../../../adapters/storage'); +let replaceImage; +let ImageImporter; +let preProcessPosts; +let preProcessTags; +let preProcessUsers; replaceImage = function (markdown, image) { if (!markdown) { @@ -13,7 +13,7 @@ replaceImage = function (markdown, image) { } // Normalizes to include a trailing slash if there was one - var regex = new RegExp('(/)?' + image.originalPath, 'gm'); + const regex = new RegExp('(/)?' + image.originalPath, 'gm'); return markdown.replace(regex, image.newPath); }; @@ -64,7 +64,7 @@ ImageImporter = { return importData; }, doImport: function (imageData) { - var store = storage.getStorage(); + const store = storage.getStorage(); return Promise.map(imageData, function (image) { return store.save(image, image.targetDir).then(function (result) { diff --git a/core/server/data/importer/index.js b/core/server/data/importer/index.js index 9413333150..957ecf786f 100644 --- a/core/server/data/importer/index.js +++ b/core/server/data/importer/index.js @@ -1,26 +1,26 @@ -var _ = require('lodash'), - Promise = require('bluebird'), - fs = require('fs-extra'), - path = require('path'), - os = require('os'), - glob = require('glob'), - uuid = require('uuid'), - {extract} = require('@tryghost/zip'), - sequence = require('../../lib/promise/sequence'), - pipeline = require('../../lib/promise/pipeline'), - common = require('../../lib/common'), - ImageHandler = require('./handlers/image'), - JSONHandler = require('./handlers/json'), - MarkdownHandler = require('./handlers/markdown'), - ImageImporter = require('./importers/image'), - DataImporter = require('./importers/data'), +const _ = require('lodash'); +const Promise = require('bluebird'); +const fs = require('fs-extra'); +const path = require('path'); +const os = require('os'); +const glob = require('glob'); +const uuid = require('uuid'); +const {extract} = require('@tryghost/zip'); +const sequence = require('../../lib/promise/sequence'); +const pipeline = require('../../lib/promise/pipeline'); +const common = require('../../lib/common'); +const ImageHandler = require('./handlers/image'); +const JSONHandler = require('./handlers/json'); +const MarkdownHandler = require('./handlers/markdown'); +const ImageImporter = require('./importers/image'); +const DataImporter = require('./importers/data'); - // Glob levels - ROOT_ONLY = 0, - ROOT_OR_SINGLE_DIR = 1, - ALL_DIRS = 2, +// Glob levels +const ROOT_ONLY = 0; - defaults; +const ROOT_OR_SINGLE_DIR = 1; +const ALL_DIRS = 2; +let defaults; defaults = { extensions: ['.zip'], @@ -80,7 +80,7 @@ _.extend(ImportManager.prototype, { * @returns {String} */ getExtensionGlob: function (extensions, level) { - var prefix = level === ALL_DIRS ? '**/*' : + const prefix = level === ALL_DIRS ? '**/*' : (level === ROOT_OR_SINGLE_DIR ? '{*/*,*}' : '*'); return prefix + this.getGlobPattern(extensions); @@ -92,7 +92,7 @@ _.extend(ImportManager.prototype, { * @returns {String} */ getDirectoryGlob: function (directories, level) { - var prefix = level === ALL_DIRS ? '**/' : + const prefix = level === ALL_DIRS ? '**/' : (level === ROOT_OR_SINGLE_DIR ? '{*/,}' : ''); return prefix + this.getGlobPattern(directories); @@ -102,7 +102,7 @@ _.extend(ImportManager.prototype, { * @returns {Function} */ cleanUp: function () { - var self = this; + const self = this; if (self.fileToDelete === null) { return; @@ -137,15 +137,18 @@ _.extend(ImportManager.prototype, { */ isValidZip: function (directory) { // Globs match content in the root or inside a single directory - var extMatchesBase = glob.sync(this.getExtensionGlob(this.getExtensions(), ROOT_OR_SINGLE_DIR), {cwd: directory}), - extMatchesAll = glob.sync( - this.getExtensionGlob(this.getExtensions(), ALL_DIRS), {cwd: directory} - ), - dirMatches = glob.sync( - this.getDirectoryGlob(this.getDirectories(), ROOT_OR_SINGLE_DIR), {cwd: directory} - ), - oldRoonMatches = glob.sync(this.getDirectoryGlob(['drafts', 'published', 'deleted'], ROOT_OR_SINGLE_DIR), - {cwd: directory}); + const extMatchesBase = glob.sync(this.getExtensionGlob(this.getExtensions(), ROOT_OR_SINGLE_DIR), {cwd: directory}); + + const extMatchesAll = glob.sync( + this.getExtensionGlob(this.getExtensions(), ALL_DIRS), {cwd: directory} + ); + + const dirMatches = glob.sync( + this.getDirectoryGlob(this.getDirectories(), ROOT_OR_SINGLE_DIR), {cwd: directory} + ); + + const oldRoonMatches = glob.sync(this.getDirectoryGlob(['drafts', 'published', 'deleted'], ROOT_OR_SINGLE_DIR), + {cwd: directory}); // This is a temporary extra message for the old format roon export which doesn't work with Ghost if (oldRoonMatches.length > 0) { @@ -184,7 +187,7 @@ _.extend(ImportManager.prototype, { * @returns [] Files */ getFilesFromZip: function (handler, directory) { - var globPattern = this.getExtensionGlob(handler.extensions, ALL_DIRS); + const globPattern = this.getExtensionGlob(handler.extensions, ALL_DIRS); return _.map(glob.sync(globPattern, {cwd: directory}), function (file) { return {name: file, path: path.join(directory, file)}; }); @@ -196,9 +199,10 @@ _.extend(ImportManager.prototype, { */ getBaseDirectory: function (directory) { // Globs match root level only - var extMatches = glob.sync(this.getExtensionGlob(this.getExtensions(), ROOT_ONLY), {cwd: directory}), - dirMatches = glob.sync(this.getDirectoryGlob(this.getDirectories(), ROOT_ONLY), {cwd: directory}), - extMatchesAll; + const extMatches = glob.sync(this.getExtensionGlob(this.getExtensions(), ROOT_ONLY), {cwd: directory}); + + const dirMatches = glob.sync(this.getDirectoryGlob(this.getDirectories(), ROOT_ONLY), {cwd: directory}); + let extMatchesAll; // There is no base directory if (extMatches.length > 0 || dirMatches.length > 0) { @@ -224,12 +228,12 @@ _.extend(ImportManager.prototype, { * @returns {Promise(ImportData)} */ processZip: function (file) { - var self = this; + const self = this; return this.extractZip(file.path).then(function (zipDirectory) { - var ops = [], - importData = {}, - baseDir; + const ops = []; + const importData = {}; + let baseDir; self.isValidZip(zipDirectory); baseDir = self.getBaseDirectory(zipDirectory); @@ -242,7 +246,7 @@ _.extend(ImportManager.prototype, { })); } - var files = self.getFilesFromZip(handler, zipDirectory); + const files = self.getFilesFromZip(handler, zipDirectory); if (files.length > 0) { ops.push(function () { @@ -274,13 +278,13 @@ _.extend(ImportManager.prototype, { * @returns {Promise(ImportData)} */ processFile: function (file, ext) { - var fileHandler = _.find(this.handlers, function (handler) { + const fileHandler = _.find(this.handlers, function (handler) { return _.includes(handler.extensions, ext); }); return fileHandler.loadFile([_.pick(file, 'name', 'path')]).then(function (loadedData) { // normalize the returned data - var importData = {}; + const importData = {}; importData[fileHandler.type] = loadedData; return importData; }); @@ -293,8 +297,8 @@ _.extend(ImportManager.prototype, { * @returns {Promise} */ loadFile: function (file) { - var self = this, - ext = path.extname(file.name).toLowerCase(); + const self = this; + const ext = path.extname(file.name).toLowerCase(); return this.isZip(ext) ? self.processZip(file) : self.processFile(file, ext); }, /** @@ -305,7 +309,7 @@ _.extend(ImportManager.prototype, { * @returns {Promise(ImportData)} */ preProcess: function (importData) { - var ops = []; + const ops = []; _.each(this.importers, function (importer) { ops.push(function () { return importer.preProcess(importData); @@ -324,7 +328,7 @@ _.extend(ImportManager.prototype, { */ doImport: function (importData, importOptions) { importOptions = importOptions || {}; - var ops = []; + const ops = []; _.each(this.importers, function (importer) { if (Object.prototype.hasOwnProperty.call(importData, importer.type)) { ops.push(function () { @@ -354,7 +358,7 @@ _.extend(ImportManager.prototype, { * @returns {Promise} */ importFromFile: function (file, importOptions = {}) { - var self = this; + const self = this; // Step 1: Handle converting the file to usable data return this.loadFile(file).then(function (importData) { diff --git a/core/server/data/migrations/hooks/init/before.js b/core/server/data/migrations/hooks/init/before.js index 006f4287f9..e47c925f93 100644 --- a/core/server/data/migrations/hooks/init/before.js +++ b/core/server/data/migrations/hooks/init/before.js @@ -1,5 +1,5 @@ -var Promise = require('bluebird'), - models = require('../../../../models'); +const Promise = require('bluebird'); +const models = require('../../../../models'); module.exports = function before() { models.init(); diff --git a/core/server/data/migrations/hooks/init/shutdown.js b/core/server/data/migrations/hooks/init/shutdown.js index 2aaf87f07e..719ef4df31 100644 --- a/core/server/data/migrations/hooks/init/shutdown.js +++ b/core/server/data/migrations/hooks/init/shutdown.js @@ -1,5 +1,5 @@ -const _ = require('lodash'), - database = require('../../../db'); +const _ = require('lodash'); +const database = require('../../../db'); module.exports = function shutdown(options = {}) { if (options.executedFromShell === true) { diff --git a/core/server/data/migrations/hooks/migrate/afterEach.js b/core/server/data/migrations/hooks/migrate/afterEach.js index 385145cabc..25e03f4eaa 100644 --- a/core/server/data/migrations/hooks/migrate/afterEach.js +++ b/core/server/data/migrations/hooks/migrate/afterEach.js @@ -1,4 +1,4 @@ -var Promise = require('bluebird'); +const Promise = require('bluebird'); module.exports = function afterEach() { return Promise.resolve(); diff --git a/core/server/data/migrations/hooks/migrate/before.js b/core/server/data/migrations/hooks/migrate/before.js index 403df18dc6..18feffd03e 100644 --- a/core/server/data/migrations/hooks/migrate/before.js +++ b/core/server/data/migrations/hooks/migrate/before.js @@ -1,5 +1,5 @@ -var dbBackup = require('../../../db/backup'), - models = require('../../../../models'); +const dbBackup = require('../../../db/backup'); +const models = require('../../../../models'); module.exports = function before() { models.init(); diff --git a/core/server/data/migrations/hooks/migrate/beforeEach.js b/core/server/data/migrations/hooks/migrate/beforeEach.js index 050b1103fb..19ac899053 100644 --- a/core/server/data/migrations/hooks/migrate/beforeEach.js +++ b/core/server/data/migrations/hooks/migrate/beforeEach.js @@ -1,4 +1,4 @@ -var Promise = require('bluebird'); +const Promise = require('bluebird'); module.exports = function beforeEach() { return Promise.resolve(); diff --git a/core/server/data/migrations/init/1-create-tables.js b/core/server/data/migrations/init/1-create-tables.js index 5d67926c5e..2aa83e2474 100644 --- a/core/server/data/migrations/init/1-create-tables.js +++ b/core/server/data/migrations/init/1-create-tables.js @@ -1,11 +1,11 @@ -var Promise = require('bluebird'), - commands = require('../../schema').commands, - schema = require('../../schema').tables, - common = require('../../../lib/common'), - schemaTables = Object.keys(schema); +const Promise = require('bluebird'); +const commands = require('../../schema').commands; +const schema = require('../../schema').tables; +const common = require('../../../lib/common'); +const schemaTables = Object.keys(schema); module.exports.up = function createTables(options) { - var connection = options.connection; + const connection = options.connection; return Promise.mapSeries(schemaTables, function createTable(table) { common.logging.info('Creating table: ' + table); diff --git a/core/server/data/migrations/init/2-create-fixtures.js b/core/server/data/migrations/init/2-create-fixtures.js index 13f124823f..18f0b3c019 100644 --- a/core/server/data/migrations/init/2-create-fixtures.js +++ b/core/server/data/migrations/init/2-create-fixtures.js @@ -1,14 +1,14 @@ -var Promise = require('bluebird'), - _ = require('lodash'), - fixtures = require('../../schema/fixtures'), - common = require('../../../lib/common'); +const Promise = require('bluebird'); +const _ = require('lodash'); +const fixtures = require('../../schema/fixtures'); +const common = require('../../../lib/common'); module.exports.config = { transaction: true }; module.exports.up = function insertFixtures(options) { - var localOptions = _.merge({ + const localOptions = _.merge({ context: {internal: true}, migrating: true }, options); diff --git a/core/server/data/migrations/versions/1.13/1-custom-template-post.js b/core/server/data/migrations/versions/1.13/1-custom-template-post.js index 5cf15e0863..754207fd7b 100644 --- a/core/server/data/migrations/versions/1.13/1-custom-template-post.js +++ b/core/server/data/migrations/versions/1.13/1-custom-template-post.js @@ -1,14 +1,14 @@ -const Promise = require('bluebird'), - common = require('../../../../lib/common'), - commands = require('../../../schema').commands, - table = 'posts', - columns = ['custom_template'], - _private = {}; +const Promise = require('bluebird'); +const common = require('../../../../lib/common'); +const commands = require('../../../schema').commands; +const table = 'posts'; +const columns = ['custom_template']; +const _private = {}; _private.handle = function handle(options) { - let type = options.type, - isAdding = type === 'Adding', - operation = isAdding ? commands.addColumn : commands.dropColumn; + let type = options.type; + let isAdding = type === 'Adding'; + let operation = isAdding ? commands.addColumn : commands.dropColumn; return function (options) { let connection = options.connection; diff --git a/core/server/data/migrations/versions/1.13/2-theme-permissions.js b/core/server/data/migrations/versions/1.13/2-theme-permissions.js index 8407729eaa..2a3db50791 100644 --- a/core/server/data/migrations/versions/1.13/2-theme-permissions.js +++ b/core/server/data/migrations/versions/1.13/2-theme-permissions.js @@ -1,9 +1,9 @@ -var _ = require('lodash'), - utils = require('../../../schema/fixtures/utils'), - permissions = require('../../../../services/permissions'), - common = require('../../../../lib/common'), - resource = 'theme', - _private = {}; +const _ = require('lodash'); +const utils = require('../../../schema/fixtures/utils'); +const permissions = require('../../../../services/permissions'); +const common = require('../../../../lib/common'); +const resource = 'theme'; +const _private = {}; _private.getPermissions = function getPermissions() { return utils.findModelFixtures('Permission', {object_type: resource}); @@ -26,11 +26,12 @@ module.exports.config = { }; module.exports.up = function addRedirectsPermissions(options) { - var modelToAdd = _private.getPermissions(), - relationToAdd = _private.getRelations(), - localOptions = _.merge({ - context: {internal: true} - }, options); + const modelToAdd = _private.getPermissions(); + const relationToAdd = _private.getRelations(); + + const localOptions = _.merge({ + context: {internal: true} + }, options); return utils.addFixturesForModel(modelToAdd, localOptions) .then(function (result) { diff --git a/core/server/data/migrations/versions/1.18/1-add-webhooks-table.js b/core/server/data/migrations/versions/1.18/1-add-webhooks-table.js index bc0fefa5e9..7c49891dbd 100644 --- a/core/server/data/migrations/versions/1.18/1-add-webhooks-table.js +++ b/core/server/data/migrations/versions/1.18/1-add-webhooks-table.js @@ -1,9 +1,9 @@ -var Promise = require('bluebird'), - common = require('../../../../lib/common'), - commands = require('../../../schema').commands, - table = 'webhooks', - message1 = 'Adding table: ' + table, - message2 = 'Dropping table: ' + table; +const Promise = require('bluebird'); +const common = require('../../../../lib/common'); +const commands = require('../../../schema').commands; +const table = 'webhooks'; +const message1 = 'Adding table: ' + table; +const message2 = 'Dropping table: ' + table; module.exports.up = function addWebhooksTable(options) { let connection = options.connection; diff --git a/core/server/data/migrations/versions/1.19/1-webhook-permissions.js b/core/server/data/migrations/versions/1.19/1-webhook-permissions.js index 10330f9954..6d785783da 100644 --- a/core/server/data/migrations/versions/1.19/1-webhook-permissions.js +++ b/core/server/data/migrations/versions/1.19/1-webhook-permissions.js @@ -1,9 +1,9 @@ -var _ = require('lodash'), - utils = require('../../../schema/fixtures/utils'), - permissions = require('../../../../services/permissions'), - logging = require('../../../../lib/common/logging'), - resource = 'webhook', - _private = {}; +const _ = require('lodash'); +const utils = require('../../../schema/fixtures/utils'); +const permissions = require('../../../../services/permissions'); +const logging = require('../../../../lib/common/logging'); +const resource = 'webhook'; +const _private = {}; _private.getPermissions = function getPermissions() { return utils.findModelFixtures('Permission', {object_type: resource}); @@ -26,11 +26,12 @@ module.exports.config = { }; module.exports.up = function addRedirectsPermissions(options) { - var modelToAdd = _private.getPermissions(), - relationToAdd = _private.getRelations(), - localOptions = _.merge({ - context: {internal: true} - }, options); + const modelToAdd = _private.getPermissions(); + const relationToAdd = _private.getRelations(); + + const localOptions = _.merge({ + context: {internal: true} + }, options); return utils.addFixturesForModel(modelToAdd, localOptions) .then(function (result) { diff --git a/core/server/data/migrations/versions/1.20/1-remove-settings-keys.js b/core/server/data/migrations/versions/1.20/1-remove-settings-keys.js index 6926e5b3e1..dbd9249c4c 100644 --- a/core/server/data/migrations/versions/1.20/1-remove-settings-keys.js +++ b/core/server/data/migrations/versions/1.20/1-remove-settings-keys.js @@ -1,6 +1,6 @@ -const _ = require('lodash'), - models = require('../../../../models'), - common = require('../../../../lib/common'); +const _ = require('lodash'); +const models = require('../../../../models'); +const common = require('../../../../lib/common'); module.exports.config = { transaction: true diff --git a/core/server/data/migrations/versions/1.21/1-add-contributor-role.js b/core/server/data/migrations/versions/1.21/1-add-contributor-role.js index 5dcf2bf67c..4795f8d9a0 100644 --- a/core/server/data/migrations/versions/1.21/1-add-contributor-role.js +++ b/core/server/data/migrations/versions/1.21/1-add-contributor-role.js @@ -1,13 +1,13 @@ -const merge = require('lodash/merge'), - utils = require('../../../schema/fixtures/utils'), - models = require('../../../../models'), - permissions = require('../../../../services/permissions'), - logging = require('../../../../lib/common/logging'), - _private = {}; +const merge = require('lodash/merge'); +const utils = require('../../../schema/fixtures/utils'); +const models = require('../../../../models'); +const permissions = require('../../../../services/permissions'); +const logging = require('../../../../lib/common/logging'); +const _private = {}; _private.addRole = function addRole(options) { - const contributorRole = utils.findModelFixtureEntry('Role', {name: 'Contributor'}), - message = 'Adding "Contributor" role to roles table'; + const contributorRole = utils.findModelFixtureEntry('Role', {name: 'Contributor'}); + const message = 'Adding "Contributor" role to roles table'; return models.Role.findOne({name: contributorRole.name}, options) .then((role) => { @@ -22,8 +22,8 @@ _private.addRole = function addRole(options) { }; _private.addContributorPermissions = function getPermissions(options) { - const relations = utils.findRelationFixture('Role', 'Permission'), - message = 'Adding permissions_roles fixtures for the contributor role'; + const relations = utils.findRelationFixture('Role', 'Permission'); + const message = 'Adding permissions_roles fixtures for the contributor role'; return utils.addFixturesForRelation({ from: relations.from, @@ -46,7 +46,7 @@ module.exports.config = { }; module.exports.up = function addContributorRole(options) { - var localOptions = merge({ + const localOptions = merge({ context: {internal: true} }, options); diff --git a/core/server/data/migrations/versions/1.22/1-multiple-authors-DDL.js b/core/server/data/migrations/versions/1.22/1-multiple-authors-DDL.js index abdcab25ec..5a68f28e5c 100644 --- a/core/server/data/migrations/versions/1.22/1-multiple-authors-DDL.js +++ b/core/server/data/migrations/versions/1.22/1-multiple-authors-DDL.js @@ -1,9 +1,9 @@ -const Promise = require('bluebird'), - common = require('../../../../lib/common'), - commands = require('../../../schema').commands, - table = 'posts_authors', - message1 = 'Adding table: ' + table, - message2 = 'Dropping table: ' + table; +const Promise = require('bluebird'); +const common = require('../../../../lib/common'); +const commands = require('../../../schema').commands; +const table = 'posts_authors'; +const message1 = 'Adding table: ' + table; +const message2 = 'Dropping table: ' + table; module.exports.up = function addMultipleAuthorsTable(options) { let connection = options.connection; diff --git a/core/server/data/migrations/versions/1.22/1-multiple-authors-DML.js b/core/server/data/migrations/versions/1.22/1-multiple-authors-DML.js index f68292baef..db65fb09e7 100644 --- a/core/server/data/migrations/versions/1.22/1-multiple-authors-DML.js +++ b/core/server/data/migrations/versions/1.22/1-multiple-authors-DML.js @@ -1,16 +1,16 @@ -const _ = require('lodash'), - Promise = require('bluebird'), - ObjectId = require('bson-objectid'), - common = require('../../../../lib/common'), - models = require('../../../../models'); +const _ = require('lodash'); +const Promise = require('bluebird'); +const ObjectId = require('bson-objectid'); +const common = require('../../../../lib/common'); +const models = require('../../../../models'); module.exports.config = { transaction: true }; module.exports.up = function handleMultipleAuthors(options) { - const postAllColumns = ['id', 'author_id'], - userColumns = ['id']; + const postAllColumns = ['id', 'author_id']; + const userColumns = ['id']; let localOptions = _.merge({ context: {internal: true} diff --git a/core/server/data/migrations/versions/1.3/1-post-excerpt.js b/core/server/data/migrations/versions/1.3/1-post-excerpt.js index d6e5510a64..29ba66407d 100644 --- a/core/server/data/migrations/versions/1.3/1-post-excerpt.js +++ b/core/server/data/migrations/versions/1.3/1-post-excerpt.js @@ -1,14 +1,14 @@ -const Promise = require('bluebird'), - common = require('../../../../lib/common'), - commands = require('../../../schema').commands, - table = 'posts', - columns = ['custom_excerpt'], - _private = {}; +const Promise = require('bluebird'); +const common = require('../../../../lib/common'); +const commands = require('../../../schema').commands; +const table = 'posts'; +const columns = ['custom_excerpt']; +const _private = {}; _private.handle = function handle(options) { - let type = options.type, - isAdding = type === 'Adding', - operation = isAdding ? commands.addColumn : commands.dropColumn; + let type = options.type; + let isAdding = type === 'Adding'; + let operation = isAdding ? commands.addColumn : commands.dropColumn; return function (options) { let connection = options.connection; diff --git a/core/server/data/migrations/versions/1.4/1-codeinjection-post.js b/core/server/data/migrations/versions/1.4/1-codeinjection-post.js index d0b3512632..eb64ac3c73 100644 --- a/core/server/data/migrations/versions/1.4/1-codeinjection-post.js +++ b/core/server/data/migrations/versions/1.4/1-codeinjection-post.js @@ -1,14 +1,14 @@ -const Promise = require('bluebird'), - common = require('../../../../lib/common'), - commands = require('../../../schema').commands, - table = 'posts', - columns = ['codeinjection_head', 'codeinjection_foot'], - _private = {}; +const Promise = require('bluebird'); +const common = require('../../../../lib/common'); +const commands = require('../../../schema').commands; +const table = 'posts'; +const columns = ['codeinjection_head', 'codeinjection_foot']; +const _private = {}; _private.handle = function handle(options) { - let type = options.type, - isAdding = type === 'Adding', - operation = isAdding ? commands.addColumn : commands.dropColumn; + let type = options.type; + let isAdding = type === 'Adding'; + let operation = isAdding ? commands.addColumn : commands.dropColumn; return function (options) { let connection = options.connection; diff --git a/core/server/data/migrations/versions/1.5/1-og-twitter-post.js b/core/server/data/migrations/versions/1.5/1-og-twitter-post.js index 0a868a5b3c..bb6b18d27c 100644 --- a/core/server/data/migrations/versions/1.5/1-og-twitter-post.js +++ b/core/server/data/migrations/versions/1.5/1-og-twitter-post.js @@ -1,14 +1,14 @@ -const Promise = require('bluebird'), - common = require('../../../../lib/common'), - commands = require('../../../schema').commands, - table = 'posts', - columns = ['og_image', 'og_title', 'og_description', 'twitter_image', 'twitter_title', 'twitter_description'], - _private = {}; +const Promise = require('bluebird'); +const common = require('../../../../lib/common'); +const commands = require('../../../schema').commands; +const table = 'posts'; +const columns = ['og_image', 'og_title', 'og_description', 'twitter_image', 'twitter_title', 'twitter_description']; +const _private = {}; _private.handle = function handle(options) { - let type = options.type, - isAdding = type === 'Adding', - operation = isAdding ? commands.addColumn : commands.dropColumn; + let type = options.type; + let isAdding = type === 'Adding'; + let operation = isAdding ? commands.addColumn : commands.dropColumn; return function (options) { let connection = options.connection; diff --git a/core/server/data/migrations/versions/1.9/1-add-permissions-redirect.js b/core/server/data/migrations/versions/1.9/1-add-permissions-redirect.js index 0af5fe66c8..7539956b8f 100644 --- a/core/server/data/migrations/versions/1.9/1-add-permissions-redirect.js +++ b/core/server/data/migrations/versions/1.9/1-add-permissions-redirect.js @@ -1,9 +1,9 @@ -var _ = require('lodash'), - utils = require('../../../schema/fixtures/utils'), - permissions = require('../../../../services/permissions'), - common = require('../../../../lib/common'), - resource = 'redirect', - _private = {}; +const _ = require('lodash'); +const utils = require('../../../schema/fixtures/utils'); +const permissions = require('../../../../services/permissions'); +const common = require('../../../../lib/common'); +const resource = 'redirect'; +const _private = {}; _private.getPermissions = function getPermissions() { return utils.findModelFixtures('Permission', {object_type: resource}); @@ -26,11 +26,12 @@ module.exports.config = { }; module.exports.up = function addRedirectsPermissions(options) { - var modelToAdd = _private.getPermissions(), - relationToAdd = _private.getRelations(), - localOptions = _.merge({ - context: {internal: true} - }, options); + const modelToAdd = _private.getPermissions(); + const relationToAdd = _private.getRelations(); + + const localOptions = _.merge({ + context: {internal: true} + }, options); return utils.addFixturesForModel(modelToAdd, localOptions).then(function (result) { _private.printResult(result, 'Adding permissions fixtures for ' + resource + 's'); diff --git a/core/server/data/migrations/versions/2.0/1-rename-amp-column.js b/core/server/data/migrations/versions/2.0/1-rename-amp-column.js index 46679cfc08..1a70ba809d 100644 --- a/core/server/data/migrations/versions/2.0/1-rename-amp-column.js +++ b/core/server/data/migrations/versions/2.0/1-rename-amp-column.js @@ -1,11 +1,11 @@ -const common = require('../../../../lib/common'), - table = 'posts', - columnNameOld = 'amp', - columnNameNew = 'comment_id', - message1 = `Renaming column ${columnNameOld} to ${columnNameNew}`, - message2 = `Rollback: Renaming column ${columnNameNew} to ${columnNameOld}`, - message3 = `Renamed column ${columnNameOld} to ${columnNameNew}`, - message4 = `Rollback: Renamed column ${columnNameNew} to ${columnNameOld}`; +const common = require('../../../../lib/common'); +const table = 'posts'; +const columnNameOld = 'amp'; +const columnNameNew = 'comment_id'; +const message1 = `Renaming column ${columnNameOld} to ${columnNameNew}`; +const message2 = `Rollback: Renaming column ${columnNameNew} to ${columnNameOld}`; +const message3 = `Renamed column ${columnNameOld} to ${columnNameNew}`; +const message4 = `Rollback: Renamed column ${columnNameNew} to ${columnNameOld}`; module.exports.up = (options) => { const connection = options.connection; diff --git a/core/server/data/migrations/versions/2.0/2-update-posts.js b/core/server/data/migrations/versions/2.0/2-update-posts.js index 24bd4ae83e..2d648f6577 100644 --- a/core/server/data/migrations/versions/2.0/2-update-posts.js +++ b/core/server/data/migrations/versions/2.0/2-update-posts.js @@ -1,11 +1,11 @@ -const _ = require('lodash'), - Promise = require('bluebird'), - common = require('../../../../lib/common'), - mobiledocLib = require('../../../../lib/mobiledoc'), - message1 = 'Updating posts: apply new editor format and set comment_id field.', - message2 = 'Updated posts: apply new editor format and set comment_id field.', - message3 = 'Rollback: Updating posts: use old editor format', - message4 = 'Rollback: Updated posts: use old editor format'; +const _ = require('lodash'); +const Promise = require('bluebird'); +const common = require('../../../../lib/common'); +const mobiledocLib = require('../../../../lib/mobiledoc'); +const message1 = 'Updating posts: apply new editor format and set comment_id field.'; +const message2 = 'Updated posts: apply new editor format and set comment_id field.'; +const message3 = 'Rollback: Updating posts: use old editor format'; +const message4 = 'Rollback: Updated posts: use old editor format'; module.exports.config = { transaction: true diff --git a/core/server/data/migrations/versions/2.0/3-remove-koenig-labs.js b/core/server/data/migrations/versions/2.0/3-remove-koenig-labs.js index 0e64239d7c..8075247e86 100644 --- a/core/server/data/migrations/versions/2.0/3-remove-koenig-labs.js +++ b/core/server/data/migrations/versions/2.0/3-remove-koenig-labs.js @@ -1,10 +1,10 @@ -const _ = require('lodash'), - Promise = require('bluebird'), - common = require('../../../../lib/common'), - models = require('../../../../models'), - message1 = 'Removing `koenigEditor` from labs.', - message2 = 'Removed `koenigEditor` from labs.', - message3 = 'Rollback: Please re-enable König Beta if required. We can\'t rollback this change.'; +const _ = require('lodash'); +const Promise = require('bluebird'); +const common = require('../../../../lib/common'); +const models = require('../../../../models'); +const message1 = 'Removing `koenigEditor` from labs.'; +const message2 = 'Removed `koenigEditor` from labs.'; +const message3 = 'Rollback: Please re-enable König Beta if required. We can\'t rollback this change.'; module.exports.config = { transaction: true diff --git a/core/server/data/migrations/versions/2.0/4-permalink-setting.js b/core/server/data/migrations/versions/2.0/4-permalink-setting.js index 4ad1528109..14c5d95c08 100644 --- a/core/server/data/migrations/versions/2.0/4-permalink-setting.js +++ b/core/server/data/migrations/versions/2.0/4-permalink-setting.js @@ -1,13 +1,13 @@ -const path = require('path'), - fs = require('fs-extra'), - config = require('../../../../config'), - common = require('../../../../lib/common'), - models = require('../../../../models'), - message1 = 'Removing `globals.permalinks` from routes.yaml.', - message2 = 'Removed `globals.permalinks` from routes.yaml.', - message3 = 'Skip: Removing `globals.permalinks` from routes.yaml.', - message4 = 'Rollback: Removing `globals.permalink` from routes.yaml. Nothing todo.', - message5 = 'Skip Rollback: Removing `globals.permalinks` from routes.yaml. Nothing todo.'; +const path = require('path'); +const fs = require('fs-extra'); +const config = require('../../../../config'); +const common = require('../../../../lib/common'); +const models = require('../../../../models'); +const message1 = 'Removing `globals.permalinks` from routes.yaml.'; +const message2 = 'Removed `globals.permalinks` from routes.yaml.'; +const message3 = 'Skip: Removing `globals.permalinks` from routes.yaml.'; +const message4 = 'Rollback: Removing `globals.permalink` from routes.yaml. Nothing todo.'; +const message5 = 'Skip Rollback: Removing `globals.permalinks` from routes.yaml. Nothing todo.'; module.exports.up = () => { let localOptions = { diff --git a/core/server/data/migrations/versions/2.0/5-remove-demo-post.js b/core/server/data/migrations/versions/2.0/5-remove-demo-post.js index fb61fac442..20b06f8125 100644 --- a/core/server/data/migrations/versions/2.0/5-remove-demo-post.js +++ b/core/server/data/migrations/versions/2.0/5-remove-demo-post.js @@ -1,10 +1,10 @@ -const _ = require('lodash'), - common = require('../../../../lib/common'), - message1 = 'Removing demo post.', - message2 = 'Removed demo post.', - message3 = 'Rollback: Bring back demo post.', - message4 = 'Skip: Demo post was already removed.', - message5 = 'Skip: Demo post exists.'; +const _ = require('lodash'); +const common = require('../../../../lib/common'); +const message1 = 'Removing demo post.'; +const message2 = 'Removed demo post.'; +const message3 = 'Rollback: Bring back demo post.'; +const message4 = 'Skip: Demo post was already removed.'; +const message5 = 'Skip: Demo post exists.'; const demoPost = { title: 'Koenig Demo Post', diff --git a/core/server/data/migrations/versions/2.17/2-posts-add-canonical-url.js b/core/server/data/migrations/versions/2.17/2-posts-add-canonical-url.js index 26d68f8adb..daefe3254d 100644 --- a/core/server/data/migrations/versions/2.17/2-posts-add-canonical-url.js +++ b/core/server/data/migrations/versions/2.17/2-posts-add-canonical-url.js @@ -1,14 +1,14 @@ -const Promise = require('bluebird'), - common = require('../../../../lib/common'), - commands = require('../../../schema').commands, - table = 'posts', - columns = ['canonical_url'], - _private = {}; +const Promise = require('bluebird'); +const common = require('../../../../lib/common'); +const commands = require('../../../schema').commands; +const table = 'posts'; +const columns = ['canonical_url']; +const _private = {}; _private.handle = function handle(options) { - let type = options.type, - isAdding = type === 'Adding', - operation = isAdding ? commands.addColumn : commands.dropColumn; + let type = options.type; + let isAdding = type === 'Adding'; + let operation = isAdding ? commands.addColumn : commands.dropColumn; return function (options) { let connection = options.connection; diff --git a/core/server/data/schema/clients/index.js b/core/server/data/schema/clients/index.js index d19923a4dc..ae255b0d32 100644 --- a/core/server/data/schema/clients/index.js +++ b/core/server/data/schema/clients/index.js @@ -1,5 +1,5 @@ -var sqlite3 = require('./sqlite3'), - mysql = require('./mysql'); +const sqlite3 = require('./sqlite3'); +const mysql = require('./mysql'); module.exports = { sqlite3: sqlite3, diff --git a/core/server/data/schema/clients/mysql.js b/core/server/data/schema/clients/mysql.js index 9424c4882f..25ef9cfd0f 100644 --- a/core/server/data/schema/clients/mysql.js +++ b/core/server/data/schema/clients/mysql.js @@ -1,14 +1,15 @@ -var _ = require('lodash'), - db = require('../../../data/db'), +const _ = require('lodash'); +const db = require('../../../data/db'); - // private - doRawAndFlatten, +// private +let doRawAndFlatten; - // public - getTables, - getIndexes, - getColumns, - checkPostTable; +// public +let getTables; + +let getIndexes; +let getColumns; +let checkPostTable; doRawAndFlatten = function doRaw(query, transaction, flattenFn) { return (transaction || db.knex).raw(query).then(function (response) { diff --git a/core/server/data/schema/clients/sqlite3.js b/core/server/data/schema/clients/sqlite3.js index f869ee2e4b..6c2ad530d4 100644 --- a/core/server/data/schema/clients/sqlite3.js +++ b/core/server/data/schema/clients/sqlite3.js @@ -1,13 +1,14 @@ -var _ = require('lodash'), - db = require('../../../data/db'), +const _ = require('lodash'); +const db = require('../../../data/db'); - // private - doRaw, +// private +let doRaw; - // public - getTables, - getIndexes, - getColumns; +// public +let getTables; + +let getIndexes; +let getColumns; doRaw = function doRaw(query, transaction, fn) { if (!fn) { diff --git a/core/server/data/schema/commands.js b/core/server/data/schema/commands.js index ddeab13cba..b57950d6d2 100644 --- a/core/server/data/schema/commands.js +++ b/core/server/data/schema/commands.js @@ -1,12 +1,12 @@ -var _ = require('lodash'), - Promise = require('bluebird'), - common = require('../../lib/common'), - db = require('../db'), - schema = require('./schema'), - clients = require('./clients'); +const _ = require('lodash'); +const Promise = require('bluebird'); +const common = require('../../lib/common'); +const db = require('../db'); +const schema = require('./schema'); +const clients = require('./clients'); function addTableColumn(tableName, table, columnName, columnSpec = schema[tableName][columnName]) { - var column; + let column; // creation distinguishes between text with fieldtype, string with maxlength and all others if (columnSpec.type === 'text' && Object.prototype.hasOwnProperty.call(columnSpec, 'fieldtype')) { @@ -83,7 +83,7 @@ function createTable(table, transaction) { } return (transaction || db.knex).schema.createTable(table, function (t) { - var columnKeys = _.keys(schema[table]); + const columnKeys = _.keys(schema[table]); _.each(columnKeys, function (column) { return addTableColumn(table, t, column); }); @@ -96,7 +96,7 @@ function deleteTable(table, transaction) { } function getTables(transaction) { - var client = (transaction || db.knex).client.config.client; + const client = (transaction || db.knex).client.config.client; if (_.includes(_.keys(clients), client)) { return clients[client].getTables(transaction); @@ -106,7 +106,7 @@ function getTables(transaction) { } function getIndexes(table, transaction) { - var client = (transaction || db.knex).client.config.client; + const client = (transaction || db.knex).client.config.client; if (_.includes(_.keys(clients), client)) { return clients[client].getIndexes(table, transaction); @@ -116,7 +116,7 @@ function getIndexes(table, transaction) { } function getColumns(table, transaction) { - var client = (transaction || db.knex).client.config.client; + const client = (transaction || db.knex).client.config.client; if (_.includes(_.keys(clients), client)) { return clients[client].getColumns(table); @@ -126,7 +126,7 @@ function getColumns(table, transaction) { } function checkTables(transaction) { - var client = (transaction || db.knex).client.config.client; + const client = (transaction || db.knex).client.config.client; if (client === 'mysql') { return clients[client].checkPostTable(); diff --git a/core/server/data/schema/fixtures/utils.js b/core/server/data/schema/fixtures/utils.js index 0c7951a4f5..e96ccc5ec9 100644 --- a/core/server/data/schema/fixtures/utils.js +++ b/core/server/data/schema/fixtures/utils.js @@ -1,30 +1,29 @@ // # Fixture Utils // Standalone file which can be required to help with advanced operations on the fixtures.json file -var _ = require('lodash'), - Promise = require('bluebird'), - common = require('../../../lib/common'), - models = require('../../../models'), - baseUtils = require('../../../models/base/utils'), - sequence = require('../../../lib/promise/sequence'), - moment = require('moment'), +const _ = require('lodash'); - fixtures = require('./fixtures'), +const Promise = require('bluebird'); +const common = require('../../../lib/common'); +const models = require('../../../models'); +const baseUtils = require('../../../models/base/utils'); +const sequence = require('../../../lib/promise/sequence'); +const moment = require('moment'); +const fixtures = require('./fixtures'); - // Private - matchFunc, - matchObj, - fetchRelationData, - findRelationFixture, - findModelFixture, +// Private +let matchFunc; - addFixturesForModel, - addFixturesForRelation, - removeFixturesForModel, - removeFixturesForRelation, - - findModelFixtureEntry, - findModelFixtures, - findPermissionRelationsForObject; +let matchObj; +let fetchRelationData; +let findRelationFixture; +let findModelFixture; +let addFixturesForModel; +let addFixturesForRelation; +let removeFixturesForModel; +let removeFixturesForRelation; +let findModelFixtureEntry; +let findModelFixtures; +let findPermissionRelationsForObject; /** * ### Match Func @@ -41,7 +40,7 @@ var _ = require('lodash'), matchFunc = function matchFunc(match, key, value) { if (_.isArray(match)) { return function (item) { - var valueTest = true; + let valueTest = true; if (_.isArray(value)) { valueTest = value.indexOf(item.get(match[1])) > -1; @@ -60,7 +59,7 @@ matchFunc = function matchFunc(match, key, value) { }; matchObj = function matchObj(match, item) { - var matchObj = {}; + const matchObj = {}; if (_.isArray(match)) { _.each(match, function (matchProp) { @@ -82,11 +81,12 @@ matchObj = function matchObj(match, item) { * @returns {Promise<*>} */ fetchRelationData = function fetchRelationData(relation, options) { - var fromOptions = _.extend({}, options, {withRelated: [relation.from.relation]}), - props = { - from: models[relation.from.model].findAll(fromOptions), - to: models[relation.to.model].findAll(options) - }; + const fromOptions = _.extend({}, options, {withRelated: [relation.from.relation]}); + + const props = { + from: models[relation.from.model].findAll(fromOptions), + to: models[relation.to.model].findAll(options) + }; return Promise.props(props); }; @@ -150,11 +150,12 @@ addFixturesForModel = function addFixturesForModel(modelFixture, options = {}) { * @returns {Promise.<*>} */ addFixturesForRelation = function addFixturesForRelation(relationFixture, options) { - var ops = [], max = 0; + const ops = []; + let max = 0; return fetchRelationData(relationFixture, options).then(function getRelationOps(data) { _.each(relationFixture.entries, function processEntries(entry, key) { - var fromItem = data.from.find(matchFunc(relationFixture.from.match, key)); + const fromItem = data.from.find(matchFunc(relationFixture.from.match, key)); // CASE: You add new fixtures e.g. a new role in a new release. // As soon as an **older** migration script wants to add permissions for any resource, it iterates over the @@ -165,7 +166,7 @@ addFixturesForRelation = function addFixturesForRelation(relationFixture, option } _.each(entry, function processEntryValues(value, key) { - var toItems = data.to.filter(matchFunc(relationFixture.to.match, key, value)); + let toItems = data.to.filter(matchFunc(relationFixture.to.match, key, value)); max += toItems.length; // Remove any duplicates that already exist in the collection @@ -227,7 +228,7 @@ findModelFixtureEntry = function findModelFixtureEntry(modelName, matchExpr) { * @returns {Object} model fixture */ findModelFixtures = function findModelFixtures(modelName, matchExpr) { - var foundModel = _.cloneDeep(findModelFixture(modelName)); + const foundModel = _.cloneDeep(findModelFixture(modelName)); foundModel.entries = _.filter(foundModel.entries, matchExpr); return foundModel; }; @@ -254,7 +255,7 @@ findRelationFixture = function findRelationFixture(from, to) { */ findPermissionRelationsForObject = function findPermissionRelationsForObject(objName, role) { // Make a copy and delete any entries we don't want - var foundRelation = _.cloneDeep(findRelationFixture('Role', 'Permission')); + const foundRelation = _.cloneDeep(findRelationFixture('Role', 'Permission')); _.each(foundRelation.entries, function (entry, key) { _.each(entry, function (perm, obj) { diff --git a/core/server/data/validation/index.js b/core/server/data/validation/index.js index dd93ff061e..313e5d3652 100644 --- a/core/server/data/validation/index.js +++ b/core/server/data/validation/index.js @@ -1,17 +1,16 @@ -var schema = require('../schema').tables, - _ = require('lodash'), - validator = require('validator'), - moment = require('moment-timezone'), - assert = require('assert'), - Promise = require('bluebird'), - common = require('../../lib/common'), - settingsCache = require('../../services/settings/cache'), - urlUtils = require('../../lib/url-utils'), - - validatePassword, - validateSchema, - validateSettings, - validate; +const schema = require('../schema').tables; +const _ = require('lodash'); +const validator = require('validator'); +const moment = require('moment-timezone'); +const assert = require('assert'); +const Promise = require('bluebird'); +const common = require('../../lib/common'); +const settingsCache = require('../../services/settings/cache'); +const urlUtils = require('../../lib/url-utils'); +let validatePassword; +let validateSchema; +let validateSettings; +let validate; function assertString(input) { assert(typeof input === 'string', 'Validator js validates strings only'); @@ -24,9 +23,9 @@ function assertString(input) { * @return {Boolean} */ function characterOccurance(stringToTest) { - var chars = {}, - allowedOccurancy, - valid = true; + const chars = {}; + let allowedOccurancy; + let valid = true; stringToTest = _.toString(stringToTest); allowedOccurancy = stringToTest.length / 2; @@ -55,7 +54,7 @@ function characterOccurance(stringToTest) { // @TODO: We modify the global validator dependency here! https://github.com/chriso/validator.js/issues/525#issuecomment-213149570 validator.extend = function (name, fn) { validator[name] = function () { - var args = Array.prototype.slice.call(arguments); + const args = Array.prototype.slice.call(arguments); assertString(args[0]); return fn.apply(validator, args); }; @@ -93,19 +92,20 @@ validator.extend('isSlug', function isSlug(str) { * valid password: `validationResult: {isValid: true}` */ validatePassword = function validatePassword(password, email, blogTitle) { - var validationResult = {isValid: true}, - disallowedPasswords = ['password', 'ghost', 'passw0rd'], - blogUrl = urlUtils.urlFor('home', true), - badPasswords = [ - '1234567890', - 'qwertyuiop', - 'qwertzuiop', - 'asdfghjkl;', - 'abcdefghij', - '0987654321', - '1q2w3e4r5t', - '12345asdfg' - ]; + const validationResult = {isValid: true}; + const disallowedPasswords = ['password', 'ghost', 'passw0rd']; + let blogUrl = urlUtils.urlFor('home', true); + + const badPasswords = [ + '1234567890', + 'qwertyuiop', + 'qwertzuiop', + 'asdfghjkl;', + 'abcdefghij', + '0987654321', + '1q2w3e4r5t', + '12345asdfg' + ]; blogTitle = blogTitle ? blogTitle : settingsCache.get('title'); blogUrl = blogUrl.replace(/^http(s?):\/\//, ''); @@ -178,12 +178,12 @@ validatePassword = function validatePassword(password, email, blogTitle) { validateSchema = function validateSchema(tableName, model, options) { options = options || {}; - var columns = _.keys(schema[tableName]), - validationErrors = []; + const columns = _.keys(schema[tableName]); + let validationErrors = []; _.each(columns, function each(columnKey) { - var message = '', - strVal = _.toString(model.get(columnKey)); // KEEP: Validator.js only validates strings. + let message = ''; // KEEP: Validator.js only validates strings. + const strVal = _.toString(model.get(columnKey)); if (options.method !== 'insert' && !_.has(model.changed, columnKey)) { return; @@ -276,9 +276,9 @@ validateSchema = function validateSchema(tableName, model, options) { // settings are checked against the validation objects // form default-settings.json validateSettings = function validateSettings(defaultSettings, model) { - var values = model.toJSON(), - validationErrors = [], - matchingDefault = defaultSettings[values.key]; + const values = model.toJSON(); + let validationErrors = []; + const matchingDefault = defaultSettings[values.key]; if (matchingDefault && matchingDefault.validations) { validationErrors = validationErrors.concat(validate(values.value, values.key, matchingDefault.validations, 'settings')); @@ -313,11 +313,12 @@ validateSettings = function validateSettings(defaultSettings, model) { * @return {Array} returns an Array including the found validation errors (empty if none found); */ validate = function validate(value, key, validations, tableName) { - var validationErrors = [], translation; + const validationErrors = []; + let translation; value = _.toString(value); _.each(validations, function each(validationOptions, validationName) { - var goodResult = true; + let goodResult = true; if (_.isBoolean(validationOptions)) { goodResult = validationOptions; diff --git a/core/server/ghost-server.js b/core/server/ghost-server.js index 36c221d47b..dbdb062bf3 100644 --- a/core/server/ghost-server.js +++ b/core/server/ghost-server.js @@ -1,14 +1,15 @@ // # Ghost Server // Handles the creation of an HTTP Server for Ghost -var debug = require('ghost-ignition').debug('server'), - Promise = require('bluebird'), - fs = require('fs-extra'), - path = require('path'), - _ = require('lodash'), - config = require('./config'), - urlUtils = require('./lib/url-utils'), - common = require('./lib/common'), - moment = require('moment'); +const debug = require('ghost-ignition').debug('server'); + +const Promise = require('bluebird'); +const fs = require('fs-extra'); +const path = require('path'); +const _ = require('lodash'); +const config = require('./config'); +const urlUtils = require('./lib/url-utils'); +const common = require('./lib/common'); +const moment = require('moment'); /** * ## GhostServer @@ -44,12 +45,14 @@ const debugInfo = { */ GhostServer.prototype.start = function (externalApp) { debug('Starting...'); - var self = this, - rootApp = externalApp ? externalApp : self.rootApp, - socketConfig, socketValues = { - path: path.join(config.get('paths').contentPath, config.get('env') + '.socket'), - permissions: '660' - }; + const self = this; + const rootApp = externalApp ? externalApp : self.rootApp; + let socketConfig; + + const socketValues = { + path: path.join(config.get('paths').contentPath, config.get('env') + '.socket'), + permissions: '660' + }; return new Promise(function (resolve, reject) { if (Object.prototype.hasOwnProperty.call(config.get('server'), 'socket')) { @@ -80,7 +83,7 @@ GhostServer.prototype.start = function (externalApp) { } self.httpServer.on('error', function (error) { - var ghostError; + let ghostError; if (error.errno === 'EADDRINUSE') { ghostError = new common.errors.GhostError({ @@ -118,7 +121,7 @@ GhostServer.prototype.start = function (externalApp) { * @returns {Promise} Resolves once Ghost has stopped */ GhostServer.prototype.stop = function () { - var self = this; + const self = this; return new Promise(function (resolve) { if (self.httpServer === null) { @@ -164,7 +167,7 @@ GhostServer.prototype.hammertime = function () { * @param {Object} socket */ GhostServer.prototype.connection = function (socket) { - var self = this; + const self = this; self.connectionId += 1; socket._ghostId = self.connectionId; @@ -182,10 +185,10 @@ GhostServer.prototype.connection = function (socket) { * httpServer from returning. We need to destroy all connections manually. */ GhostServer.prototype.closeConnections = function () { - var self = this; + const self = this; Object.keys(self.connections).forEach(function (socketId) { - var socket = self.connections[socketId]; + const socket = self.connections[socketId]; if (socket) { socket.destroy(); diff --git a/core/server/index.js b/core/server/index.js index a134bf4290..c5c5f8a582 100644 --- a/core/server/index.js +++ b/core/server/index.js @@ -30,12 +30,12 @@ function initialiseServices() { // We pass the themeService API version here, so that the frontend services are less tightly-coupled routing.bootstrap.start(themeService.getApiVersion()); - const permissions = require('./services/permissions'), - xmlrpc = require('./services/xmlrpc'), - slack = require('./services/slack'), - {mega} = require('./services/mega'), - webhooks = require('./services/webhooks'), - scheduling = require('./adapters/scheduling'); + const permissions = require('./services/permissions'); + const xmlrpc = require('./services/xmlrpc'); + const slack = require('./services/slack'); + const {mega} = require('./services/mega'); + const webhooks = require('./services/webhooks'); + const scheduling = require('./adapters/scheduling'); debug('`initialiseServices` Start...'); diff --git a/core/server/lib/common/errors.js b/core/server/lib/common/errors.js index 3886a852bd..08086fc71c 100644 --- a/core/server/lib/common/errors.js +++ b/core/server/lib/common/errors.js @@ -1,7 +1,7 @@ -const merge = require('lodash/merge'), - each = require('lodash/each'), - util = require('util'), - errors = require('ghost-ignition').errors; +const merge = require('lodash/merge'); +const each = require('lodash/each'); +const util = require('util'); +const errors = require('ghost-ignition').errors; function GhostError(options) { options = options || {}; diff --git a/core/server/lib/common/events.js b/core/server/lib/common/events.js index 4ca28b24f7..5a39b9ad98 100644 --- a/core/server/lib/common/events.js +++ b/core/server/lib/common/events.js @@ -1,7 +1,7 @@ -const events = require('events'), - util = require('util'); -let EventRegistry, - EventRegistryInstance; +const events = require('events'); +const util = require('util'); +let EventRegistry; +let EventRegistryInstance; EventRegistry = function () { events.EventEmitter.call(this); diff --git a/core/server/lib/common/i18n.js b/core/server/lib/common/i18n.js index 197052eebb..19ef972a01 100644 --- a/core/server/lib/common/i18n.js +++ b/core/server/lib/common/i18n.js @@ -43,7 +43,8 @@ class I18n { * @returns {string} */ t(path, bindings) { - let string, msg; + let string; + let msg; string = this._findString(path); @@ -111,7 +112,8 @@ class I18n { */ _findString(msgPath, opts) { const options = merge({log: true}, opts || {}); - let candidateString, matchingString; + let candidateString; + let matchingString; // no path? no string if (msgPath.length === 0 || !isString(msgPath)) { @@ -179,7 +181,8 @@ class I18n { * - Polyfill node.js if it does not have Intl support or support for a particular locale */ _initializeIntl() { - let hasBuiltInLocaleData, IntlPolyfill; + let hasBuiltInLocaleData; + let IntlPolyfill; if (global.Intl) { // Determine if the built-in `Intl` has the locale data we need. diff --git a/core/server/lib/common/logging.js b/core/server/lib/common/logging.js index d3d332a42e..c948cbf416 100644 --- a/core/server/lib/common/logging.js +++ b/core/server/lib/common/logging.js @@ -1,5 +1,5 @@ -const config = require('../../config'), - {logging} = require('ghost-ignition'); +const config = require('../../config'); +const {logging} = require('ghost-ignition'); module.exports = logging({ name: config.get('logging:name'), diff --git a/core/server/lib/fs/package-json/filter.js b/core/server/lib/fs/package-json/filter.js index c461599514..86843a2a9d 100644 --- a/core/server/lib/fs/package-json/filter.js +++ b/core/server/lib/fs/package-json/filter.js @@ -1,6 +1,6 @@ -var _ = require('lodash'), - notAPackageRegex = /^\.|_messages|README.md/i, - filterPackages; +const _ = require('lodash'); +const notAPackageRegex = /^\.|_messages|README.md/i; +let filterPackages; /** * ### Filter Packages @@ -26,7 +26,7 @@ filterPackages = function filterPackages(packages, active) { } return _.reduce(packages, function (result, pkg, key) { - var item = {}; + let item = {}; if (!key.match(notAPackageRegex)) { item = { name: key, diff --git a/core/server/lib/fs/package-json/parse.js b/core/server/lib/fs/package-json/parse.js index 7b0454bf9e..a07d867869 100644 --- a/core/server/lib/fs/package-json/parse.js +++ b/core/server/lib/fs/package-json/parse.js @@ -2,9 +2,10 @@ * Dependencies */ -var Promise = require('bluebird'), - fs = require('fs-extra'), - common = require('../../common'); +const Promise = require('bluebird'); + +const fs = require('fs-extra'); +const common = require('../../common'); /** * Parse package.json and validate it has @@ -14,13 +15,15 @@ var Promise = require('bluebird'), function parsePackageJson(path) { return fs.readFile(path) .catch(function () { - var err = new Error(common.i18n.t('errors.utils.parsepackagejson.couldNotReadPackage')); + const err = new Error(common.i18n.t('errors.utils.parsepackagejson.couldNotReadPackage')); err.context = path; return Promise.reject(err); }) .then(function (source) { - var hasRequiredKeys, json, err; + let hasRequiredKeys; + let json; + let err; try { json = JSON.parse(source); diff --git a/core/server/lib/fs/package-json/read.js b/core/server/lib/fs/package-json/read.js index 6a10fab547..e6c94d29c6 100644 --- a/core/server/lib/fs/package-json/read.js +++ b/core/server/lib/fs/package-json/read.js @@ -1,25 +1,24 @@ /** * Dependencies */ -var Promise = require('bluebird'), - _ = require('lodash'), - join = require('path').join, - fs = require('fs-extra'), - parsePackageJson = require('./parse'), - common = require('../../common'), +const Promise = require('bluebird'); - notAPackageRegex = /^\.|_messages|README.md|node_modules|bower_components/i, - packageJSONPath = 'package.json', - - readPackage, - readPackages, - processPackage; +const _ = require('lodash'); +const join = require('path').join; +const fs = require('fs-extra'); +const parsePackageJson = require('./parse'); +const common = require('../../common'); +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) { - var pkg = { + const pkg = { name: packageName, path: absolutePath }; @@ -39,7 +38,7 @@ processPackage = function processPackage(absolutePath, packageName) { }; readPackage = function readPackage(packagePath, packageName) { - var absolutePath = join(packagePath, packageName); + const absolutePath = join(packagePath, packageName); return fs.stat(absolutePath) .then(function (stat) { if (!stat.isDirectory()) { @@ -48,7 +47,7 @@ readPackage = function readPackage(packagePath, packageName) { return processPackage(absolutePath, packageName) .then(function gotPackage(pkg) { - var res = {}; + const res = {}; res[packageName] = pkg; return res; }); @@ -76,7 +75,7 @@ readPackages = function readPackages(packagePath) { }); }) .map(function readPackageJson(packageName) { - var absolutePath = join(packagePath, packageName); + const absolutePath = join(packagePath, packageName); return processPackage(absolutePath, packageName); }) .then(function (packages) { diff --git a/core/server/lib/fs/read-csv.js b/core/server/lib/fs/read-csv.js index 16e1bbfb19..dcdd8ec3ad 100644 --- a/core/server/lib/fs/read-csv.js +++ b/core/server/lib/fs/read-csv.js @@ -1,14 +1,15 @@ -const Promise = require('bluebird'), - csvParser = require('csv-parser'), - _ = require('lodash'), - fs = require('fs-extra'); +const Promise = require('bluebird'); +const csvParser = require('csv-parser'); +const _ = require('lodash'); +const fs = require('fs-extra'); module.exports = function readCSV(options) { - var columnsToExtract = options.columnsToExtract || [], - results = [], rows = []; + const columnsToExtract = options.columnsToExtract || []; + let results = []; + const rows = []; return new Promise(function (resolve, reject) { - var readFile = fs.createReadStream(options.path); + const readFile = fs.createReadStream(options.path); readFile.on('err', function (err) { reject(err); @@ -18,8 +19,11 @@ module.exports = function readCSV(options) { rows.push(row); }) .on('end', function () { - // If CSV is single column - return all values including header - var headers = _.keys(rows[0]), result = {}, columnMap = {}; + // If CSV is single column - return all values including header + const headers = _.keys(rows[0]); + + let result = {}; + const columnMap = {}; if (columnsToExtract.length === 1 && headers.length === 1) { results = _.map(rows, function (value) { result = {}; @@ -27,8 +31,8 @@ module.exports = function readCSV(options) { return result; }); } else { - // If there are multiple columns in csv file - // try to match headers using lookup value + // If there are multiple columns in csv file + // try to match headers using lookup value _.map(columnsToExtract, function findMatches(column) { _.each(headers, function checkheader(header) { @@ -39,7 +43,7 @@ module.exports = function readCSV(options) { }); results = _.map(rows, function evaluateRow(row) { - var result = {}; + const result = {}; _.each(columnMap, function returnMatches(value, key) { result[key] = row[value]; }); diff --git a/core/server/lib/ghost-version.js b/core/server/lib/ghost-version.js index db9583f09b..acdf01db1c 100644 --- a/core/server/lib/ghost-version.js +++ b/core/server/lib/ghost-version.js @@ -1,7 +1,7 @@ -const semver = require('semver'), - packageInfo = require('../../../package.json'), - version = packageInfo.version, - plainVersion = version.match(/^(\d+\.)?(\d+\.)?(\d+)/)[0]; +const semver = require('semver'); +const packageInfo = require('../../../package.json'); +const version = packageInfo.version; +const plainVersion = version.match(/^(\d+\.)?(\d+\.)?(\d+)/)[0]; let _private = {}; diff --git a/core/server/lib/image/blog-icon.js b/core/server/lib/image/blog-icon.js index 8ae04e9194..002d5d9921 100644 --- a/core/server/lib/image/blog-icon.js +++ b/core/server/lib/image/blog-icon.js @@ -1,18 +1,18 @@ -var sizeOf = require('image-size'), - Promise = require('bluebird'), - _ = require('lodash'), - path = require('path'), - config = require('../../config'), - {i18n} = require('../common'), - errors = require('@tryghost/errors'), - urlUtils = require('../../lib/url-utils'), - settingsCache = require('../../services/settings/cache'), - storageUtils = require('../../adapters/storage/utils'), - getIconDimensions, - isIcoImageType, - getIconType, - getIconUrl, - getIconPath; +const sizeOf = require('image-size'); +const Promise = require('bluebird'); +const _ = require('lodash'); +const path = require('path'); +const config = require('../../config'); +const {i18n} = require('../common'); +const errors = require('@tryghost/errors'); +const urlUtils = require('../../lib/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 @@ -23,7 +23,7 @@ var sizeOf = require('image-size'), */ getIconDimensions = function getIconDimensions(path) { return new Promise(function getIconSize(resolve, reject) { - var dimensions; + let dimensions; try { dimensions = sizeOf(path); @@ -60,7 +60,7 @@ getIconDimensions = function getIconDimensions(path) { * @description Takes a path and returns boolean value. */ isIcoImageType = function isIcoImageType(icon) { - var blogIcon = icon || settingsCache.get('icon'); + const blogIcon = icon || settingsCache.get('icon'); return blogIcon.match(/.ico$/i) ? true : false; }; @@ -73,7 +73,7 @@ isIcoImageType = function isIcoImageType(icon) { * @description Takes a path and returns boolean value. */ getIconType = function getIconType(icon) { - var blogIcon = icon || settingsCache.get('icon'); + const blogIcon = icon || settingsCache.get('icon'); return isIcoImageType(blogIcon) ? 'x-icon' : 'png'; }; @@ -86,7 +86,7 @@ getIconType = function getIconType(icon) { * exists, we're returning the default `favicon.ico` */ getIconUrl = function getIconUrl(absolut) { - var blogIcon = settingsCache.get('icon'); + const blogIcon = settingsCache.get('icon'); if (absolut) { if (blogIcon) { @@ -111,7 +111,7 @@ getIconUrl = function getIconUrl(absolut) { * exists, we're returning the default `favicon.ico` */ getIconPath = function getIconPath() { - var blogIcon = settingsCache.get('icon'); + const blogIcon = settingsCache.get('icon'); if (blogIcon) { return storageUtils.getLocalFileStoragePath(blogIcon); diff --git a/core/server/lib/image/cached-image-size-from-url.js b/core/server/lib/image/cached-image-size-from-url.js index ffaead479f..2520fe799b 100644 --- a/core/server/lib/image/cached-image-size-from-url.js +++ b/core/server/lib/image/cached-image-size-from-url.js @@ -1,8 +1,8 @@ -var debug = require('ghost-ignition').debug('utils:image-size-cache'), - imageSize = require('./image-size'), - errors = require('@tryghost/errors'), - {logging} = require('../common'), - cache = {}; +const debug = require('ghost-ignition').debug('utils:image-size-cache'); +const imageSize = require('./image-size'); +const errors = require('@tryghost/errors'); +const {logging} = require('../common'); +const cache = {}; /** * Get cached image size from URL diff --git a/core/server/lib/image/gravatar.js b/core/server/lib/image/gravatar.js index ae0cddaea8..cd949f05c3 100644 --- a/core/server/lib/image/gravatar.js +++ b/core/server/lib/image/gravatar.js @@ -1,10 +1,10 @@ -var Promise = require('bluebird'), - crypto = require('crypto'), - config = require('../../config'), - request = require('../request'); +const Promise = require('bluebird'); +const crypto = require('crypto'); +const config = require('../../config'); +const request = require('../request'); module.exports.lookup = function lookup(userData, timeout) { - var gravatarUrl = '//www.gravatar.com/avatar/' + + let gravatarUrl = '//www.gravatar.com/avatar/' + crypto.createHash('md5').update(userData.email.toLowerCase().trim()).digest('hex') + '?s=250'; diff --git a/core/server/lib/mobiledoc.js b/core/server/lib/mobiledoc.js index 2e395a1349..38be181dc5 100644 --- a/core/server/lib/mobiledoc.js +++ b/core/server/lib/mobiledoc.js @@ -1,7 +1,9 @@ const common = require('./common'); const config = require('../config'); -let cardFactory, cards, mobiledocHtmlRenderer; +let cardFactory; +let cards; +let mobiledocHtmlRenderer; module.exports = { get blankDocument() { diff --git a/core/server/lib/promise/pipeline.js b/core/server/lib/promise/pipeline.js index 18d99b5dc3..98be6651cb 100644 --- a/core/server/lib/promise/pipeline.js +++ b/core/server/lib/promise/pipeline.js @@ -4,21 +4,21 @@ * Based on pipeline.js from when.js: * https://github.com/cujojs/when/blob/3.7.4/pipeline.js */ -var Promise = require('bluebird'); +const Promise = require('bluebird'); function pipeline(tasks /* initial arguments */) { - var args = Array.prototype.slice.call(arguments, 1), + const args = Array.prototype.slice.call(arguments, 1); - runTask = function (task, args) { - // Self-optimizing function to run first task with multiple - // args using apply, but subsequent tasks via direct invocation - runTask = function (task, arg) { - return task(arg); - }; - - return task.apply(null, args); + let runTask = function (task, args) { + // Self-optimizing function to run first task with multiple + // args using apply, but subsequent tasks via direct invocation + runTask = function (task, arg) { + return task(arg); }; + return task.apply(null, args); + }; + // Resolve any promises for the arguments passed in first return Promise.all(args).then(function (args) { // Iterate through the tasks passing args from one into the next diff --git a/core/server/lib/request.js b/core/server/lib/request.js index 47b80e5aa0..c9a80e1a03 100644 --- a/core/server/lib/request.js +++ b/core/server/lib/request.js @@ -1,10 +1,10 @@ -var got = require('got'), - _ = require('lodash'), - validator = require('../data/validation').validator, - errors = require('@tryghost/errors'), - ghostVersion = require('./ghost-version'); +const got = require('got'); +const _ = require('lodash'); +const validator = require('../data/validation').validator; +const errors = require('@tryghost/errors'); +const ghostVersion = require('./ghost-version'); -var defaultOptions = { +const defaultOptions = { headers: { 'user-agent': 'Ghost/' + ghostVersion.original + ' (https://github.com/TryGhost/Ghost)' } @@ -19,7 +19,7 @@ module.exports = function request(url, options) { })); } - var mergedOptions = _.merge({}, defaultOptions, options); + const mergedOptions = _.merge({}, defaultOptions, options); return got(url, mergedOptions); }; diff --git a/core/server/lib/security/identifier.js b/core/server/lib/security/identifier.js index 73f5176aa0..31f0c7a558 100644 --- a/core/server/lib/security/identifier.js +++ b/core/server/lib/security/identifier.js @@ -13,10 +13,10 @@ _private.getRandomInt = function (min, max) { * @api private */ module.exports.uid = function uid(maxLength) { - var buf = [], - chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789', - charLength = chars.length, - i; + const buf = []; + const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; + const charLength = chars.length; + let i; for (i = 0; i < maxLength; i = i + 1) { buf.push(chars[_private.getRandomInt(0, charLength - 1)]); diff --git a/core/server/lib/security/password.js b/core/server/lib/security/password.js index 28e5667576..697e0be986 100644 --- a/core/server/lib/security/password.js +++ b/core/server/lib/security/password.js @@ -1,9 +1,9 @@ const Promise = require('bluebird'); module.exports.hash = function hash(plainPassword) { - const bcrypt = require('bcryptjs'), - bcryptGenSalt = Promise.promisify(bcrypt.genSalt), - bcryptHash = Promise.promisify(bcrypt.hash); + const bcrypt = require('bcryptjs'); + const bcryptGenSalt = Promise.promisify(bcrypt.genSalt); + const bcryptHash = Promise.promisify(bcrypt.hash); return bcryptGenSalt().then(function (salt) { return bcryptHash(plainPassword, salt); @@ -11,8 +11,8 @@ module.exports.hash = function hash(plainPassword) { }; module.exports.compare = function compare(plainPassword, hashedPassword) { - const bcrypt = require('bcryptjs'), - bcryptCompare = Promise.promisify(bcrypt.compare); + const bcrypt = require('bcryptjs'); + const bcryptCompare = Promise.promisify(bcrypt.compare); return bcryptCompare(plainPassword, hashedPassword); }; diff --git a/core/server/lib/security/tokens.js b/core/server/lib/security/tokens.js index 4429585bef..973c853d80 100644 --- a/core/server/lib/security/tokens.js +++ b/core/server/lib/security/tokens.js @@ -3,8 +3,8 @@ const crypto = require('crypto'); module.exports.generateFromContent = function generateFromContent(options) { options = options || {}; - const hash = crypto.createHash('sha256'), - content = options.content; + const hash = crypto.createHash('sha256'); + const content = options.content; let text = ''; @@ -17,10 +17,10 @@ module.exports.generateFromContent = function generateFromContent(options) { module.exports.generateFromEmail = function generateFromEmail(options) { options = options || {}; - const hash = crypto.createHash('sha256'), - expires = options.expires, - email = options.email, - secret = options.secret; + const hash = crypto.createHash('sha256'); + const expires = options.expires; + const email = options.email; + const secret = options.secret; let text = ''; @@ -36,12 +36,12 @@ module.exports.resetToken = { generateHash: function generateHash(options) { options = options || {}; - var hash = crypto.createHash('sha256'), - expires = options.expires, - email = options.email, - dbHash = options.dbHash, - password = options.password, - text = ''; + const hash = crypto.createHash('sha256'); + const expires = options.expires; + const email = options.email; + const dbHash = options.dbHash; + const password = options.password; + let text = ''; hash.update(String(expires)); hash.update(email.toLocaleLowerCase()); @@ -54,11 +54,11 @@ module.exports.resetToken = { extract: function extract(options) { options = options || {}; - var token = options.token, - tokenText = Buffer.from(token, 'base64').toString('ascii'), - parts, - expires, - email; + const token = options.token; + const tokenText = Buffer.from(token, 'base64').toString('ascii'); + let parts; + let expires; + let email; parts = tokenText.split('|'); @@ -78,13 +78,13 @@ module.exports.resetToken = { compare: function compare(options) { options = options || {}; - var tokenToCompare = options.token, - parts = exports.resetToken.extract({token: tokenToCompare}), - dbHash = options.dbHash, - password = options.password, - generatedToken, - diff = 0, - i; + const tokenToCompare = options.token; + const parts = exports.resetToken.extract({token: tokenToCompare}); + const dbHash = options.dbHash; + const password = options.password; + let generatedToken; + let diff = 0; + let i; if (isNaN(parts.expires)) { return false; diff --git a/core/server/models/base/index.js b/core/server/models/base/index.js index 4ed1a5e234..d3dbf5f7c0 100644 --- a/core/server/models/base/index.js +++ b/core/server/models/base/index.js @@ -6,23 +6,23 @@ // accesses the models directly. // All other parts of Ghost, including the frontend & admin UI are only allowed to access data via the API. -const _ = require('lodash'), - bookshelf = require('bookshelf'), - moment = require('moment'), - Promise = require('bluebird'), - ObjectId = require('bson-objectid'), - debug = require('ghost-ignition').debug('models:base'), - config = require('../../config'), - db = require('../../data/db'), - common = require('../../lib/common'), - security = require('../../lib/security'), - schema = require('../../data/schema'), - urlUtils = require('../../lib/url-utils'), - validation = require('../../data/validation'), - plugins = require('../plugins'); +const _ = require('lodash'); -let ghostBookshelf, - proto; +const bookshelf = require('bookshelf'); +const moment = require('moment'); +const Promise = require('bluebird'); +const ObjectId = require('bson-objectid'); +const debug = require('ghost-ignition').debug('models:base'); +const config = require('../../config'); +const db = require('../../data/db'); +const common = require('../../lib/common'); +const security = require('../../lib/security'); +const schema = require('../../data/schema'); +const urlUtils = require('../../lib/url-utils'); +const validation = require('../../data/validation'); +const plugins = require('../plugins'); +let ghostBookshelf; +let proto; // ### ghostBookshelf // Initializes a new Bookshelf instance called ghostBookshelf, for reference elsewhere in Ghost. @@ -59,7 +59,7 @@ ghostBookshelf.plugin('bookshelf-relations', { belongsToMany: { after: function (existing, targets, options) { // reorder tags/authors - var queryOptions = { + const queryOptions = { query: { where: {} } @@ -222,7 +222,7 @@ ghostBookshelf.Model = ghostBookshelf.Model.extend({ // Bookshelf `initialize` - declare a constructor-like method for model creation initialize: function initialize() { - var self = this; + const self = this; // NOTE: triggered before `creating`/`updating` this.on('saving', function onSaving(newObj, attrs, options) { @@ -429,7 +429,7 @@ ghostBookshelf.Model = ghostBookshelf.Model.extend({ * date format is now in each db the same */ fixDatesWhenSave: function fixDates(attrs) { - var self = this; + const self = this; _.each(attrs, function each(value, key) { if (value !== null @@ -451,7 +451,8 @@ ghostBookshelf.Model = ghostBookshelf.Model.extend({ * - knex wraps the UTC value into a local JS Date */ fixDatesWhenFetch: function fixDates(attrs) { - var self = this, dateMoment; + const self = this; + let dateMoment; _.each(attrs, function each(value, key) { if (value !== null @@ -474,7 +475,7 @@ ghostBookshelf.Model = ghostBookshelf.Model.extend({ // Convert integers to real booleans fixBools: function fixBools(attrs) { - var self = this; + const self = this; _.each(attrs, function each(value, key) { if (Object.prototype.hasOwnProperty.call(schema.tables[self.tableName], key) && schema.tables[self.tableName][key].type === 'bool') { @@ -701,9 +702,9 @@ ghostBookshelf.Model = ghostBookshelf.Model.extend({ * @return {Object} The filtered results of the passed in data, containing only what's allowed in the schema. */ filterData: function filterData(data) { - var permittedAttributes = this.prototype.permittedAttributes(), - filteredData = _.pick(data, permittedAttributes), - sanitizedData = this.sanitizeData(filteredData); + const permittedAttributes = this.prototype.permittedAttributes(); + const filteredData = _.pick(data, permittedAttributes); + const sanitizedData = this.sanitizeData(filteredData); return sanitizedData; }, @@ -730,7 +731,8 @@ ghostBookshelf.Model = ghostBookshelf.Model.extend({ * Sanitize relations. */ sanitizeData: function sanitizeData(data) { - var tableName = _.result(this.prototype, 'tableName'), date; + const tableName = _.result(this.prototype, 'tableName'); + let date; _.each(data, (value, property) => { if (value !== null @@ -801,9 +803,9 @@ ghostBookshelf.Model = ghostBookshelf.Model.extend({ }); } - var options = _.cloneDeep(unfilteredOptions), - extraAllowedProperties = filterConfig.extraAllowedProperties || [], - permittedOptions; + let options = _.cloneDeep(unfilteredOptions); + const extraAllowedProperties = filterConfig.extraAllowedProperties || []; + let permittedOptions; permittedOptions = this.permittedOptions(methodName, options); permittedOptions = _.union(permittedOptions, extraAllowedProperties); @@ -825,8 +827,8 @@ ghostBookshelf.Model = ghostBookshelf.Model.extend({ * @return {Promise(ghostBookshelf.Collection)} Collection of all Models */ findAll: function findAll(unfilteredOptions) { - var options = this.filterOptions(unfilteredOptions, 'findAll'), - itemCollection = this.forge(); + const options = this.filterOptions(unfilteredOptions, 'findAll'); + const itemCollection = this.forge(); // @TODO: we can't use order raw when running migrations (see https://github.com/tgriesser/knex/issues/2763) if (this.orderDefaultRaw && !options.migrating) { @@ -872,9 +874,9 @@ ghostBookshelf.Model = ghostBookshelf.Model.extend({ * @param {Object} unfilteredOptions */ findPage: function findPage(unfilteredOptions) { - var options = this.filterOptions(unfilteredOptions, 'findPage'), - itemCollection = this.forge(), - requestedColumns = options.columns; + const options = this.filterOptions(unfilteredOptions, 'findPage'); + const itemCollection = this.forge(); + const requestedColumns = options.columns; // Set this to true or pass ?debug=true as an API option to get output itemCollection.debug = options.debug && config.get('env') !== 'production'; @@ -992,8 +994,8 @@ ghostBookshelf.Model = ghostBookshelf.Model.extend({ * @return {Promise(ghostBookshelf.Model)} Newly Added Model */ add: function add(data, unfilteredOptions) { - var options = this.filterOptions(unfilteredOptions, 'add'), - model; + const options = this.filterOptions(unfilteredOptions, 'add'); + let model; data = this.filterData(data); model = this.forge(data); @@ -1042,14 +1044,17 @@ ghostBookshelf.Model = ghostBookshelf.Model.extend({ * @return {Promise(String)} Resolves to a unique slug string */ generateSlug: function generateSlug(Model, base, options) { - var slug, - slugTryCount = 1, - baseName = Model.prototype.tableName.replace(/s$/, ''), - // Look for a matching slug, append an incrementing number if so - checkIfSlugExists, longSlug; + let slug; + 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) { - var args = {slug: slugToFind}; + const args = {slug: slugToFind}; // status is needed for posts if (options && options.status) { @@ -1057,7 +1062,7 @@ ghostBookshelf.Model = ghostBookshelf.Model.extend({ } return Model.findOne(args, options).then(function then(found) { - var trimSpace; + let trimSpace; if (!found) { return slugToFind; @@ -1127,7 +1132,9 @@ ghostBookshelf.Model = ghostBookshelf.Model.extend({ }, parseOrderOption: function (order, withRelated) { - var permittedAttributes, result, rules; + let permittedAttributes; + let result; + let rules; permittedAttributes = this.prototype.permittedAttributes(); if (withRelated && withRelated.indexOf('count.posts') > -1) { @@ -1137,7 +1144,9 @@ ghostBookshelf.Model = ghostBookshelf.Model.extend({ rules = order.split(','); _.each(rules, function (rule) { - var match, field, direction; + let match; + let field; + let direction; match = /^([a-z0-9_.]+)\s+(asc|desc)$/i.exec(rule.trim()); diff --git a/core/server/models/base/listeners.js b/core/server/models/base/listeners.js index a7e6bf2278..da4d807a0f 100644 --- a/core/server/models/base/listeners.js +++ b/core/server/models/base/listeners.js @@ -1,8 +1,8 @@ -var moment = require('moment-timezone'), - _ = require('lodash'), - models = require('../../models'), - common = require('../../lib/common'), - sequence = require('../../lib/promise/sequence'); +const moment = require('moment-timezone'); +const _ = require('lodash'); +const models = require('../../models'); +const common = require('../../lib/common'); +const sequence = require('../../lib/promise/sequence'); /** * WHEN timezone changes, we will: @@ -13,9 +13,9 @@ common.events.on('settings.active_timezone.edited', function (settingModel, opti options = options || {}; options = _.merge({}, options, {context: {internal: true}}); - var newTimezone = settingModel.attributes.value, - previousTimezone = settingModel._previousAttributes.value, - timezoneOffsetDiff = moment.tz(previousTimezone).utcOffset() - moment.tz(newTimezone).utcOffset(); + const newTimezone = settingModel.attributes.value; + const previousTimezone = settingModel._previousAttributes.value; + const timezoneOffsetDiff = moment.tz(previousTimezone).utcOffset() - moment.tz(newTimezone).utcOffset(); // CASE: TZ was updated, but did not change if (previousTimezone === newTimezone) { @@ -44,7 +44,7 @@ common.events.on('settings.active_timezone.edited', function (settingModel, opti return sequence(results.map(function (post) { return function reschedulePostIfPossible() { - var newPublishedAtMoment = moment(post.get('published_at')).add(timezoneOffsetDiff, 'minutes'); + const newPublishedAtMoment = moment(post.get('published_at')).add(timezoneOffsetDiff, 'minutes'); /** * CASE: @@ -88,9 +88,9 @@ common.events.on('settings.active_timezone.edited', function (settingModel, opti * to the settings model to create real lock. */ common.events.on('settings.notifications.edited', function (settingModel) { - var allNotifications = JSON.parse(settingModel.attributes.value || []), - options = {context: {internal: true}}, - skip = true; + let allNotifications = JSON.parse(settingModel.attributes.value || []); + const options = {context: {internal: true}}; + let skip = true; allNotifications = allNotifications.filter(function (notification) { // Do not delete the release notification diff --git a/core/server/models/base/utils.js b/core/server/models/base/utils.js index 2dc365b5d1..16888ad79c 100644 --- a/core/server/models/base/utils.js +++ b/core/server/models/base/utils.js @@ -2,11 +2,13 @@ * # Utils * Parts of the model code which can be split out and unit tested */ -var _ = require('lodash'), - Promise = require('bluebird'), - ObjectId = require('bson-objectid'), - common = require('../../lib/common'), - attach, detach; +const _ = require('lodash'); + +const Promise = require('bluebird'); +const ObjectId = require('bson-objectid'); +const common = require('../../lib/common'); +let attach; +let detach; /** * Attach wrapper (please never call attach manual!) @@ -24,8 +26,8 @@ var _ = require('lodash'), attach = function attach(Model, effectedModelId, relation, modelsToAttach, options) { options = options || {}; - var fetchedModel, - localOptions = {transacting: options.transacting}; + let fetchedModel; + const localOptions = {transacting: options.transacting}; return Model.forge({id: effectedModelId}).fetch(localOptions) .then(function successFetchedModel(_fetchedModel) { @@ -66,8 +68,8 @@ attach = function attach(Model, effectedModelId, relation, modelsToAttach, optio detach = function detach(Model, effectedModelId, relation, modelsToAttach, options) { options = options || {}; - var fetchedModel, - localOptions = {transacting: options.transacting}; + let fetchedModel; + const localOptions = {transacting: options.transacting}; return Model.forge({id: effectedModelId}).fetch(localOptions) .then(function successFetchedModel(_fetchedModel) { diff --git a/core/server/models/index.js b/core/server/models/index.js index b494ef2c2d..7cd6a465ef 100644 --- a/core/server/models/index.js +++ b/core/server/models/index.js @@ -2,9 +2,7 @@ * Dependencies */ -var _ = require('lodash'), - exports, - models; +const _ = require('lodash'); // enable event listeners require('./base/listeners'); @@ -14,7 +12,7 @@ require('./base/listeners'); */ exports = module.exports; -models = [ +const models = [ 'permission', 'post', 'role', diff --git a/core/server/models/invite.js b/core/server/models/invite.js index d75e835bc8..7246572a2f 100644 --- a/core/server/models/invite.js +++ b/core/server/models/invite.js @@ -6,15 +6,15 @@ const security = require('../lib/security'); const settingsCache = require('../services/settings/cache'); const ghostBookshelf = require('./base'); -let Invite, - Invites; +let Invite; +let Invites; Invite = ghostBookshelf.Model.extend({ tableName: 'invites', toJSON: function (unfilteredOptions) { - var options = Invite.filterOptions(unfilteredOptions, 'toJSON'), - attrs = ghostBookshelf.Model.prototype.toJSON.call(this, options); + const options = Invite.filterOptions(unfilteredOptions, 'toJSON'); + const attrs = ghostBookshelf.Model.prototype.toJSON.call(this, options); delete attrs.token; return attrs; diff --git a/core/server/models/label.js b/core/server/models/label.js index 2d92cb717d..7e3fd8a213 100644 --- a/core/server/models/label.js +++ b/core/server/models/label.js @@ -1,7 +1,8 @@ const ghostBookshelf = require('./base'); const common = require('../lib/common'); -let Label, Labels; +let Label; +let Labels; Label = ghostBookshelf.Model.extend({ @@ -31,7 +32,7 @@ Label = ghostBookshelf.Model.extend({ }, onSaving: function onSaving(newLabel, attr, options) { - var self = this; + const self = this; ghostBookshelf.Model.prototype.onSaving.apply(this, arguments); // Make sure name is trimmed of extra spaces @@ -84,15 +85,15 @@ Label = ghostBookshelf.Model.extend({ }, permittedOptions: function permittedOptions(methodName) { - var options = ghostBookshelf.Model.permittedOptions.call(this, methodName), + let options = ghostBookshelf.Model.permittedOptions.call(this, methodName); - // whitelists for the `options` hash argument on methods, by method name. - // these are the only options that can be passed to Bookshelf / Knex. - validOptions = { - findAll: ['columns'], - findOne: ['columns'], - destroy: ['destroyAll'] - }; + // whitelists for the `options` hash argument on methods, by method name. + // these are the only options that can be passed to Bookshelf / Knex. + const validOptions = { + findAll: ['columns'], + findOne: ['columns'], + destroy: ['destroyAll'] + }; if (validOptions[methodName]) { options = options.concat(validOptions[methodName]); @@ -102,7 +103,7 @@ Label = ghostBookshelf.Model.extend({ }, destroy: function destroy(unfilteredOptions) { - var options = this.filterOptions(unfilteredOptions, 'destroy', {extraAllowedProperties: ['id']}); + const options = this.filterOptions(unfilteredOptions, 'destroy', {extraAllowedProperties: ['id']}); options.withRelated = ['members']; return this.forge({id: options.id}) diff --git a/core/server/models/permission.js b/core/server/models/permission.js index 57a67748c0..4f59f27cd8 100644 --- a/core/server/models/permission.js +++ b/core/server/models/permission.js @@ -1,7 +1,7 @@ const ghostBookshelf = require('./base'); -let Permission, - Permissions; +let Permission; +let Permissions; Permission = ghostBookshelf.Model.extend({ diff --git a/core/server/models/plugins/collision.js b/core/server/models/plugins/collision.js index 89081cc180..08864fcc54 100644 --- a/core/server/models/plugins/collision.js +++ b/core/server/models/plugins/collision.js @@ -1,13 +1,12 @@ -var moment = require('moment-timezone'), - Promise = require('bluebird'), - _ = require('lodash'), - common = require('../../lib/common'); +const moment = require('moment-timezone'); +const Promise = require('bluebird'); +const _ = require('lodash'); +const common = require('../../lib/common'); module.exports = function (Bookshelf) { - var ParentModel = Bookshelf.Model, - Model; + const ParentModel = Bookshelf.Model; - Model = Bookshelf.Model.extend({ + const Model = Bookshelf.Model.extend({ /** * Update collision protection. * @@ -24,9 +23,9 @@ module.exports = function (Bookshelf) { * the same current database values and both would succeed to update and override each other. */ sync: function timestamp(options) { - var parentSync = ParentModel.prototype.sync.apply(this, arguments), - originalUpdateSync = parentSync.update, - self = this; + const parentSync = ParentModel.prototype.sync.apply(this, arguments); + const originalUpdateSync = parentSync.update; + const self = this; // CASE: only enabled for posts table if (this.tableName !== 'posts' || diff --git a/core/server/models/plugins/include-count.js b/core/server/models/plugins/include-count.js index 5d62241977..5a7eec891b 100644 --- a/core/server/models/plugins/include-count.js +++ b/core/server/models/plugins/include-count.js @@ -1,13 +1,10 @@ -var _debug = require('ghost-ignition').debug._base, - debug = _debug('ghost-query'), - _ = require('lodash'); +const _debug = require('ghost-ignition').debug._base; +const debug = _debug('ghost-query'); +const _ = require('lodash'); module.exports = function (Bookshelf) { - var modelProto = Bookshelf.Model.prototype, - Model, - countQueryBuilder; - - countQueryBuilder = { + const modelProto = Bookshelf.Model.prototype; + const countQueryBuilder = { tags: { posts: function addPostCountToTags(model, options) { model.query('columns', 'tags.*', function (qb) { @@ -44,13 +41,13 @@ module.exports = function (Bookshelf) { } }; - Model = Bookshelf.Model.extend({ + const Model = Bookshelf.Model.extend({ addCounts: function (options) { if (!options) { return; } - var tableName = _.result(this, 'tableName'); + const tableName = _.result(this, 'tableName'); if (options.withRelated && options.withRelated.indexOf('count.posts') > -1) { // remove post_count from withRelated @@ -86,11 +83,11 @@ module.exports = function (Bookshelf) { }, serialize: function serialize(options) { - var attrs = modelProto.serialize.call(this, options), - countRegex = /^(count)(__)(.*)$/; + const attrs = modelProto.serialize.call(this, options); + const countRegex = /^(count)(__)(.*)$/; _.forOwn(attrs, function (value, key) { - var match = key.match(countRegex); + const match = key.match(countRegex); if (match) { attrs[match[1]] = attrs[match[1]] || {}; attrs[match[1]][match[3]] = value; diff --git a/core/server/models/plugins/pagination.js b/core/server/models/plugins/pagination.js index 53da976c2e..7d47e5fb2e 100644 --- a/core/server/models/plugins/pagination.js +++ b/core/server/models/plugins/pagination.js @@ -1,11 +1,12 @@ // # Pagination // // Extends Bookshelf.Model with a `fetchPage` method. Handles everything to do with paginated requests. -var _ = require('lodash'), - common = require('../../lib/common'), - defaults, - paginationUtils, - pagination; +const _ = require('lodash'); + +const common = require('../../lib/common'); +let defaults; +let paginationUtils; +let pagination; /** * ### Default pagination values @@ -65,15 +66,16 @@ paginationUtils = { * @returns {pagination} pagination metadata */ formatResponse: function formatResponse(totalItems, options) { - var calcPages = Math.ceil(totalItems / options.limit) || 0, - pagination = { - page: options.page || defaults.page, - limit: options.limit, - pages: calcPages === 0 ? 1 : calcPages, - total: totalItems, - next: null, - prev: null - }; + const calcPages = Math.ceil(totalItems / options.limit) || 0; + + const pagination = { + page: options.page || defaults.page, + limit: options.limit, + pages: calcPages === 0 ? 1 : calcPages, + total: totalItems, + next: null, + prev: null + }; if (pagination.pages > 1) { if (pagination.page === 1) { @@ -142,9 +144,10 @@ pagination = function pagination(bookshelf) { options = paginationUtils.parseOptions(options); // Get the table name and idAttribute for this model - var tableName = _.result(this.constructor.prototype, 'tableName'), - idAttribute = _.result(this.constructor.prototype, 'idAttribute'), - self = this; + const tableName = _.result(this.constructor.prototype, 'tableName'); + + const idAttribute = _.result(this.constructor.prototype, 'idAttribute'); + const self = this; let countPromise; if (options.transacting) { diff --git a/core/server/models/post.js b/core/server/models/post.js index a83eefe9f0..76c9c68bc1 100644 --- a/core/server/models/post.js +++ b/core/server/models/post.js @@ -111,7 +111,7 @@ Post = ghostBookshelf.Model.extend({ return; } - var status = model.get('status'); + const status = model.get('status'); model.emitChange('added', options); @@ -263,20 +263,22 @@ Post = ghostBookshelf.Model.extend({ onSaving: function onSaving(model, attr, options) { options = options || {}; - var self = this, - title, - i, - // Variables to make the slug checking more readable - newTitle = this.get('title'), - newStatus = this.get('status'), - olderStatus = this.previous('status'), - prevTitle = this.previous('title'), - prevSlug = this.previous('slug'), - publishedAt = this.get('published_at'), - publishedAtHasChanged = this.hasDateChanged('published_at', {beforeWrite: true}), - generatedFields = ['html', 'plaintext'], - tagsToSave, - ops = []; + const self = this; + let title; + let i; + + // Variables to make the slug checking more readable + const newTitle = this.get('title'); + + const newStatus = this.get('status'); + const olderStatus = this.previous('status'); + const prevTitle = this.previous('title'); + const prevSlug = this.previous('slug'); + const publishedAt = this.get('published_at'); + const publishedAtHasChanged = this.hasDateChanged('published_at', {beforeWrite: true}); + const generatedFields = ['html', 'plaintext']; + let tagsToSave; + const ops = []; // CASE: disallow published -> scheduled // @TODO: remove when we have versioning based on updated_at @@ -635,8 +637,8 @@ Post = ghostBookshelf.Model.extend({ * Otherwise we return what is requested e.g. `?formats=mobiledoc,plaintext` */ formatsToJSON: function formatsToJSON(attrs, options) { - var defaultFormats = ['html'], - formatsToKeep = options.formats || defaultFormats; + const defaultFormats = ['html']; + const formatsToKeep = options.formats || defaultFormats; // Iterate over all known formats, and if they are not in the keep list, remove them _.each(Post.allowedFormats, function (format) { @@ -649,8 +651,8 @@ Post = ghostBookshelf.Model.extend({ }, toJSON: function toJSON(unfilteredOptions) { - var options = Post.filterOptions(unfilteredOptions, 'toJSON'), - attrs = ghostBookshelf.Model.prototype.toJSON.call(this, options); + const options = Post.filterOptions(unfilteredOptions, 'toJSON'); + let attrs = ghostBookshelf.Model.prototype.toJSON.call(this, options); attrs = this.formatsToJSON(attrs, options); @@ -769,17 +771,17 @@ Post = ghostBookshelf.Model.extend({ * @return {Array} Keys allowed in the `options` hash of the model's method. */ permittedOptions: function permittedOptions(methodName) { - var options = ghostBookshelf.Model.permittedOptions.call(this, methodName), + let options = ghostBookshelf.Model.permittedOptions.call(this, methodName); - // whitelists for the `options` hash argument on methods, by method name. - // these are the only options that can be passed to Bookshelf / Knex. - validOptions = { - findOne: ['columns', 'importing', 'withRelated', 'require', 'filter'], - findPage: ['status'], - findAll: ['columns', 'filter'], - destroy: ['destroyAll', 'destroyBy'], - edit: ['filter', 'send_email_when_published'] - }; + // whitelists for the `options` hash argument on methods, by method name. + // these are the only options that can be passed to Bookshelf / Knex. + const validOptions = { + findOne: ['columns', 'importing', 'withRelated', 'require', 'filter'], + findPage: ['status'], + findAll: ['columns', 'filter'], + destroy: ['destroyAll', 'destroyBy'], + edit: ['filter', 'send_email_when_published'] + }; // The post model additionally supports having a formats option options.push('formats'); @@ -822,8 +824,8 @@ Post = ghostBookshelf.Model.extend({ * @return {Object} The filtered results of the passed in data, containing only what's allowed in the schema. */ filterData: function filterData(data) { - var filteredData = ghostBookshelf.Model.filterData.apply(this, arguments), - extraData = _.pick(data, this.prototype.relationships); + const filteredData = ghostBookshelf.Model.filterData.apply(this, arguments); + const extraData = _.pick(data, this.prototype.relationships); _.merge(filteredData, extraData); return filteredData; diff --git a/core/server/models/relations/authors.js b/core/server/models/relations/authors.js index a0141ce1ec..2beabd9e33 100644 --- a/core/server/models/relations/authors.js +++ b/core/server/models/relations/authors.js @@ -291,9 +291,9 @@ module.exports.extendModel = function extendModel(Post, Posts, ghostBookshelf) { * @param {[type]} options has context and id. Context is the user doing the destroy, id is the user to destroy */ destroyByAuthor: function destroyByAuthor(unfilteredOptions) { - let options = this.filterOptions(unfilteredOptions, 'destroyByAuthor', {extraAllowedProperties: ['id']}), - postCollection = Posts.forge(), - authorId = options.id; + let options = this.filterOptions(unfilteredOptions, 'destroyByAuthor', {extraAllowedProperties: ['id']}); + let postCollection = Posts.forge(); + let authorId = options.id; if (!authorId) { return Promise.reject(new common.errors.NotFoundError({ @@ -332,9 +332,14 @@ module.exports.extendModel = function extendModel(Post, Posts, ghostBookshelf) { }, permissible: function permissible(postModelOrId, action, context, unsafeAttrs, loadedPermissions, hasUserPermission, hasApiKeyPermission) { - var self = this, - postModel = postModelOrId, - origArgs, isContributor, isAuthor, isEdit, isAdd, isDestroy; + const self = this; + const postModel = postModelOrId; + let origArgs; + let isContributor; + let isAuthor; + let isEdit; + let isAdd; + let isDestroy; // If we passed in an id instead of a model, get the model // then check the permissions diff --git a/core/server/models/role.js b/core/server/models/role.js index 0bcdb3ee8f..2cbe00caaf 100644 --- a/core/server/models/role.js +++ b/core/server/models/role.js @@ -1,10 +1,9 @@ -var _ = require('lodash'), - ghostBookshelf = require('./base'), - Promise = require('bluebird'), - common = require('../lib/common'), - - Role, - Roles; +const _ = require('lodash'); +const ghostBookshelf = require('./base'); +const Promise = require('bluebird'); +const common = require('../lib/common'); +let Role; +let Roles; Role = ghostBookshelf.Model.extend({ @@ -34,14 +33,14 @@ Role = ghostBookshelf.Model.extend({ * @return {Array} Keys allowed in the `options` hash of the model's method. */ permittedOptions: function permittedOptions(methodName) { - var options = ghostBookshelf.Model.permittedOptions.call(this, methodName), + let options = ghostBookshelf.Model.permittedOptions.call(this, methodName); - // whitelists for the `options` hash argument on methods, by method name. - // these are the only options that can be passed to Bookshelf / Knex. - validOptions = { - findOne: ['withRelated'], - findAll: ['withRelated'] - }; + // whitelists for the `options` hash argument on methods, by method name. + // these are the only options that can be passed to Bookshelf / Knex. + const validOptions = { + findOne: ['withRelated'], + findAll: ['withRelated'] + }; if (validOptions[methodName]) { options = options.concat(validOptions[methodName]); diff --git a/core/server/models/settings.js b/core/server/models/settings.js index d7245df1e0..9d747e0771 100644 --- a/core/server/models/settings.js +++ b/core/server/models/settings.js @@ -1,15 +1,15 @@ -const Promise = require('bluebird'), - _ = require('lodash'), - uuid = require('uuid'), - crypto = require('crypto'), - keypair = require('keypair'), - ghostBookshelf = require('./base'), - common = require('../lib/common'), - validation = require('../data/validation'), - settingsCache = require('../services/settings/cache'), - internalContext = {context: {internal: true}}; - -let Settings, defaultSettings; +const Promise = require('bluebird'); +const _ = require('lodash'); +const uuid = require('uuid'); +const crypto = require('crypto'); +const keypair = require('keypair'); +const ghostBookshelf = require('./base'); +const common = require('../lib/common'); +const validation = require('../data/validation'); +const settingsCache = require('../services/settings/cache'); +const internalContext = {context: {internal: true}}; +let Settings; +let defaultSettings; const doBlock = fn => fn(); @@ -37,21 +37,22 @@ const getGhostKey = doBlock(() => { // It's much easier for us to work with it as a single level // instead of iterating those categories every time function parseDefaultSettings() { - var defaultSettingsInCategories = require('../data/schema/').defaultSettings, - defaultSettingsFlattened = {}, - dynamicDefault = { - db_hash: () => uuid.v4(), - public_hash: () => crypto.randomBytes(15).toString('hex'), - // @TODO: session_secret would ideally be named "admin_session_secret" - session_secret: () => crypto.randomBytes(32).toString('hex'), - members_session_secret: () => crypto.randomBytes(32).toString('hex'), - theme_session_secret: () => crypto.randomBytes(32).toString('hex'), - members_public_key: () => getMembersKey('public'), - members_private_key: () => getMembersKey('private'), - members_email_auth_secret: () => crypto.randomBytes(64).toString('hex'), - ghost_public_key: () => getGhostKey('public'), - ghost_private_key: () => getGhostKey('private') - }; + const defaultSettingsInCategories = require('../data/schema/').defaultSettings; + const defaultSettingsFlattened = {}; + + const dynamicDefault = { + db_hash: () => uuid.v4(), + public_hash: () => crypto.randomBytes(15).toString('hex'), + // @TODO: session_secret would ideally be named "admin_session_secret" + session_secret: () => crypto.randomBytes(32).toString('hex'), + members_session_secret: () => crypto.randomBytes(32).toString('hex'), + theme_session_secret: () => crypto.randomBytes(32).toString('hex'), + members_public_key: () => getMembersKey('public'), + members_private_key: () => getMembersKey('private'), + members_email_auth_secret: () => crypto.randomBytes(64).toString('hex'), + ghost_public_key: () => getGhostKey('public'), + ghost_private_key: () => getGhostKey('private') + }; _.each(defaultSettingsInCategories, function each(settings, categoryName) { _.each(settings, function each(setting, settingName) { @@ -121,7 +122,7 @@ Settings = ghostBookshelf.Model.extend({ }, onValidate: function onValidate() { - var self = this; + const self = this; return ghostBookshelf.Model.prototype.onValidate.apply(this, arguments) .then(function then() { @@ -170,8 +171,8 @@ Settings = ghostBookshelf.Model.extend({ }, edit: function (data, unfilteredOptions) { - var options = this.filterOptions(unfilteredOptions, 'edit'), - self = this; + const options = this.filterOptions(unfilteredOptions, 'edit'); + const self = this; if (!Array.isArray(data)) { data = [data]; @@ -218,8 +219,8 @@ Settings = ghostBookshelf.Model.extend({ }, populateDefaults: function populateDefaults(unfilteredOptions) { - var options = this.filterOptions(unfilteredOptions, 'populateDefaults'), - self = this; + const options = this.filterOptions(unfilteredOptions, 'populateDefaults'); + const self = this; if (!options.context) { options.context = internalContext.context; @@ -228,13 +229,14 @@ Settings = ghostBookshelf.Model.extend({ return this .findAll(options) .then(function checkAllSettings(allSettings) { - var usedKeys = allSettings.models.map(function mapper(setting) { - return setting.get('key'); - }), - insertOperations = []; + const usedKeys = allSettings.models.map(function mapper(setting) { + return setting.get('key'); + }); + + const insertOperations = []; _.each(getDefaultSettings(), function forEachDefault(defaultSetting, defaultSettingKey) { - var isMissingFromDB = usedKeys.indexOf(defaultSettingKey) === -1; + const isMissingFromDB = usedKeys.indexOf(defaultSettingKey) === -1; if (isMissingFromDB) { defaultSetting.value = defaultSetting.getDefaultValue(); insertOperations.push(Settings.forge(defaultSetting).save(null, options)); diff --git a/core/server/models/tag.js b/core/server/models/tag.js index f3245ad891..5ca5ef582e 100644 --- a/core/server/models/tag.js +++ b/core/server/models/tag.js @@ -1,7 +1,8 @@ const ghostBookshelf = require('./base'); const common = require('../lib/common'); -let Tag, Tags; +let Tag; +let Tags; Tag = ghostBookshelf.Model.extend({ @@ -37,7 +38,7 @@ Tag = ghostBookshelf.Model.extend({ }, onSaving: function onSaving(newTag, attr, options) { - var self = this; + const self = this; ghostBookshelf.Model.prototype.onSaving.apply(this, arguments); @@ -61,8 +62,8 @@ Tag = ghostBookshelf.Model.extend({ }, toJSON: function toJSON(unfilteredOptions) { - var options = Tag.filterOptions(unfilteredOptions, 'toJSON'), - attrs = ghostBookshelf.Model.prototype.toJSON.call(this, options); + const options = Tag.filterOptions(unfilteredOptions, 'toJSON'); + const attrs = ghostBookshelf.Model.prototype.toJSON.call(this, options); // @NOTE: this serialization should be moved into api layer, it's not being moved as it's not used attrs.parent = attrs.parent || attrs.parent_id; @@ -94,15 +95,15 @@ Tag = ghostBookshelf.Model.extend({ }, permittedOptions: function permittedOptions(methodName) { - var options = ghostBookshelf.Model.permittedOptions.call(this, methodName), + let options = ghostBookshelf.Model.permittedOptions.call(this, methodName); - // whitelists for the `options` hash argument on methods, by method name. - // these are the only options that can be passed to Bookshelf / Knex. - validOptions = { - findAll: ['columns'], - findOne: ['columns', 'visibility'], - destroy: ['destroyAll'] - }; + // whitelists for the `options` hash argument on methods, by method name. + // these are the only options that can be passed to Bookshelf / Knex. + const validOptions = { + findAll: ['columns'], + findOne: ['columns', 'visibility'], + destroy: ['destroyAll'] + }; if (validOptions[methodName]) { options = options.concat(validOptions[methodName]); @@ -112,7 +113,7 @@ Tag = ghostBookshelf.Model.extend({ }, destroy: function destroy(unfilteredOptions) { - var options = this.filterOptions(unfilteredOptions, 'destroy', {extraAllowedProperties: ['id']}); + const options = this.filterOptions(unfilteredOptions, 'destroy', {extraAllowedProperties: ['id']}); options.withRelated = ['posts']; return this.forge({id: options.id}) diff --git a/core/server/models/user.js b/core/server/models/user.js index 6a8a27ea10..53400c2f32 100644 --- a/core/server/models/user.js +++ b/core/server/models/user.js @@ -1,24 +1,26 @@ -const _ = require('lodash'), - Promise = require('bluebird'), - validator = require('validator'), - ObjectId = require('bson-objectid'), - ghostBookshelf = require('./base'), - baseUtils = require('./base/utils'), - common = require('../lib/common'), - security = require('../lib/security'), - imageLib = require('../lib/image'), - pipeline = require('../lib/promise/pipeline'), - validation = require('../data/validation'), - permissions = require('../services/permissions'), - activeStates = ['active', 'warn-1', 'warn-2', 'warn-3', 'warn-4'], - /** - * inactive: owner user before blog setup, suspended users - * locked user: imported users, they get a random password - */ - inactiveStates = ['inactive', 'locked'], - allStates = activeStates.concat(inactiveStates); +const _ = require('lodash'); +const Promise = require('bluebird'); +const validator = require('validator'); +const ObjectId = require('bson-objectid'); +const ghostBookshelf = require('./base'); +const baseUtils = require('./base/utils'); +const common = require('../lib/common'); +const security = require('../lib/security'); +const imageLib = require('../lib/image'); +const pipeline = require('../lib/promise/pipeline'); +const validation = require('../data/validation'); +const permissions = require('../services/permissions'); +const activeStates = ['active', 'warn-1', 'warn-2', 'warn-3', 'warn-4']; -let User, Users; +/** + * inactive: owner user before blog setup, suspended users + * locked user: imported users, they get a random password + */ +const inactiveStates = ['inactive', 'locked']; + +const allStates = activeStates.concat(inactiveStates); +let User; +let Users; User = ghostBookshelf.Model.extend({ @@ -106,9 +108,9 @@ User = ghostBookshelf.Model.extend({ * Generating a slug requires a db call to look for conflicting slugs */ onSaving: function onSaving(newPage, attr, options) { - var self = this, - tasks = [], - passwordValidation = {}; + const self = this; + const tasks = []; + let passwordValidation = {}; ghostBookshelf.Model.prototype.onSaving.apply(this, arguments); @@ -210,8 +212,8 @@ User = ghostBookshelf.Model.extend({ }, toJSON: function toJSON(unfilteredOptions) { - var options = User.filterOptions(unfilteredOptions, 'toJSON'), - attrs = ghostBookshelf.Model.prototype.toJSON.call(this, options); + const options = User.filterOptions(unfilteredOptions, 'toJSON'); + const attrs = ghostBookshelf.Model.prototype.toJSON.call(this, options); // remove password hash for security reasons delete attrs.password; @@ -247,7 +249,7 @@ User = ghostBookshelf.Model.extend({ }, hasRole: function hasRole(roleName) { - var roles = this.related('roles'); + const roles = this.related('roles'); return roles.some(function getRole(role) { return role.get('name') === roleName; @@ -336,18 +338,18 @@ User = ghostBookshelf.Model.extend({ * @return {Array} Keys allowed in the `options` hash of the model's method. */ permittedOptions: function permittedOptions(methodName, options) { - var permittedOptionsToReturn = ghostBookshelf.Model.permittedOptions.call(this, methodName), + let permittedOptionsToReturn = ghostBookshelf.Model.permittedOptions.call(this, methodName); - // whitelists for the `options` hash argument on methods, by method name. - // these are the only options that can be passed to Bookshelf / Knex. - validOptions = { - findOne: ['withRelated', 'status'], - setup: ['id'], - edit: ['withRelated', 'importPersistUser'], - add: ['importPersistUser'], - findPage: ['status'], - findAll: ['filter'] - }; + // whitelists for the `options` hash argument on methods, by method name. + // these are the only options that can be passed to Bookshelf / Knex. + const validOptions = { + findOne: ['withRelated', 'status'], + setup: ['id'], + edit: ['withRelated', 'importPersistUser'], + add: ['importPersistUser'], + findPage: ['status'], + findAll: ['filter'] + }; if (validOptions[methodName]) { permittedOptionsToReturn = permittedOptionsToReturn.concat(validOptions[methodName]); @@ -377,11 +379,11 @@ User = ghostBookshelf.Model.extend({ * **See:** [ghostBookshelf.Model.findOne](base.js.html#Find%20One) */ findOne: function findOne(dataToClone, unfilteredOptions) { - var options = this.filterOptions(unfilteredOptions, 'findOne'), - query, - status, - data = _.cloneDeep(dataToClone), - lookupRole = data.role; + const options = this.filterOptions(unfilteredOptions, 'findOne'); + let query; + let status; + let data = _.cloneDeep(dataToClone); + const lookupRole = data.role; // Ensure only valid fields/columns are added to query if (options.columns) { @@ -428,9 +430,9 @@ User = ghostBookshelf.Model.extend({ * **See:** [ghostBookshelf.Model.edit](base.js.html#edit) */ edit: function edit(data, unfilteredOptions) { - var options = this.filterOptions(unfilteredOptions, 'edit'), - self = this, - ops = []; + const options = this.filterOptions(unfilteredOptions, 'edit'); + const self = this; + const ops = []; if (data.roles && data.roles.length > 1) { return Promise.reject( @@ -454,7 +456,7 @@ User = ghostBookshelf.Model.extend({ ops.push(function update() { return ghostBookshelf.Model.edit.call(self, data, options).then((user) => { - var roleId; + let roleId; if (!data.roles) { return user; @@ -506,11 +508,11 @@ User = ghostBookshelf.Model.extend({ * **See:** [ghostBookshelf.Model.add](base.js.html#Add) */ add: function add(dataToClone, unfilteredOptions) { - var options = this.filterOptions(unfilteredOptions, 'add'), - self = this, - data = _.cloneDeep(dataToClone), - userData = this.filterData(data), - roles; + const options = this.filterOptions(unfilteredOptions, 'add'); + const self = this; + const data = _.cloneDeep(dataToClone); + let userData = this.filterData(data); + let roles; // check for too many roles if (data.roles && data.roles.length > 1) { @@ -599,10 +601,10 @@ User = ghostBookshelf.Model.extend({ * @TODO: kill setup function? */ setup: function setup(data, unfilteredOptions) { - var options = this.filterOptions(unfilteredOptions, 'setup'), - self = this, - userData = this.filterData(data), - passwordValidation = {}; + const options = this.filterOptions(unfilteredOptions, 'setup'); + const self = this; + const userData = this.filterData(data); + let passwordValidation = {}; passwordValidation = validation.validatePassword(userData.password, userData.email, data.blogTitle); @@ -649,9 +651,9 @@ User = ghostBookshelf.Model.extend({ }, permissible: function permissible(userModelOrId, action, context, unsafeAttrs, loadedPermissions, hasUserPermission, hasApiKeyPermission) { - var self = this, - userModel = userModelOrId, - origArgs; + const self = this; + const userModel = userModelOrId; + let origArgs; // If we passed in a model without its related roles, we need to fetch it again if (_.isObject(userModelOrId) && !_.isObject(userModelOrId.related('roles'))) { @@ -674,7 +676,7 @@ User = ghostBookshelf.Model.extend({ } // Build up the original args but substitute with actual model - var newArgs = [foundUserModel].concat(origArgs); + const newArgs = [foundUserModel].concat(origArgs); return self.permissible.apply(self, newArgs); }); @@ -792,7 +794,7 @@ User = ghostBookshelf.Model.extend({ // Finds the user by email, and checks the password // @TODO: shorten this function and rename... check: function check(object) { - var self = this; + const self = this; return this.getByEmail(object.email) .then((user) => { @@ -835,8 +837,8 @@ User = ghostBookshelf.Model.extend({ }, isPasswordCorrect: function isPasswordCorrect(object) { - var plainPassword = object.plainPassword, - hashedPassword = object.hashedPassword; + const plainPassword = object.plainPassword; + const hashedPassword = object.hashedPassword; if (!plainPassword || !hashedPassword) { return Promise.reject(new common.errors.ValidationError({ @@ -960,7 +962,7 @@ User = ghostBookshelf.Model.extend({ // When multi-user support is added, email addresses must be deduplicated with case insensitivity, so that // joe@bloggs.com and JOE@BLOGGS.COM cannot be created as two separate users. getByEmail: function getByEmail(email, unfilteredOptions) { - var options = ghostBookshelf.Model.filterOptions(unfilteredOptions, 'getByEmail'); + const options = ghostBookshelf.Model.filterOptions(unfilteredOptions, 'getByEmail'); // We fetch all users and process them in JS as there is no easy way to make this query across all DBs // Although they all support `lower()`, sqlite can't case transform unicode characters @@ -969,7 +971,7 @@ User = ghostBookshelf.Model.extend({ options.require = true; return Users.forge().fetch(options).then(function then(users) { - var userWithEmail = users.find(function findUser(user) { + const userWithEmail = users.find(function findUser(user) { return user.get('email').toLowerCase() === email.toLowerCase(); }); diff --git a/core/server/models/webhook.js b/core/server/models/webhook.js index 177174af00..9fa9a79d9d 100644 --- a/core/server/models/webhook.js +++ b/core/server/models/webhook.js @@ -1,8 +1,7 @@ -const Promise = require('bluebird'), - ghostBookshelf = require('./base'); - -let Webhook, - Webhooks; +const Promise = require('bluebird'); +const ghostBookshelf = require('./base'); +let Webhook; +let Webhooks; Webhook = ghostBookshelf.Model.extend({ tableName: 'webhooks', @@ -42,8 +41,8 @@ Webhook = ghostBookshelf.Model.extend({ } }, { findAllByEvent: function findAllByEvent(event, unfilteredOptions) { - var options = this.filterOptions(unfilteredOptions, 'findAll'), - webhooksCollection = Webhooks.forge(); + const options = this.filterOptions(unfilteredOptions, 'findAll'); + const webhooksCollection = Webhooks.forge(); return webhooksCollection .query('where', 'event', '=', event) @@ -51,11 +50,11 @@ Webhook = ghostBookshelf.Model.extend({ }, getByEventAndTarget: function getByEventAndTarget(event, targetUrl, unfilteredOptions) { - var options = ghostBookshelf.Model.filterOptions(unfilteredOptions, 'getByEventAndTarget'); + const options = ghostBookshelf.Model.filterOptions(unfilteredOptions, 'getByEventAndTarget'); options.require = true; return Webhooks.forge().fetch(options).then(function then(webhooks) { - var webhookWithEventAndTarget = webhooks.find(function findWebhook(webhook) { + const webhookWithEventAndTarget = webhooks.find(function findWebhook(webhook) { return webhook.get('event').toLowerCase() === event.toLowerCase() && webhook.get('target_url').toLowerCase() === targetUrl.toLowerCase(); }); diff --git a/core/server/public/members.js b/core/server/public/members.js index 79ebe49e1f..ea4decaece 100644 --- a/core/server/public/members.js +++ b/core/server/public/members.js @@ -1,5 +1,5 @@ Array.prototype.forEach.call(document.querySelectorAll('form[data-members-form]'), function (form){ - var errorEl = form.querySelector('[data-members-error]'); + const errorEl = form.querySelector('[data-members-error]'); function submitHandler(event) { form.removeEventListener('submit', submitHandler); event.preventDefault(); @@ -7,13 +7,13 @@ Array.prototype.forEach.call(document.querySelectorAll('form[data-members-form]' errorEl.innerText = ''; } form.classList.remove('success', 'invalid', 'error'); - var input = event.target.querySelector('input[data-members-email]'); - var email = input.value; - var emailType = undefined; - var labels = []; + const input = event.target.querySelector('input[data-members-email]'); + const email = input.value; + let emailType = undefined; + const labels = []; - var labelInputs = event.target.querySelectorAll('input[data-members-label]') || []; - for (var i = 0;i < labelInputs.length; ++i) { + const labelInputs = event.target.querySelectorAll('input[data-members-label]') || []; + for (let i = 0;i < labelInputs.length; ++i) { labels.push(labelInputs[i].value); } @@ -49,16 +49,16 @@ Array.prototype.forEach.call(document.querySelectorAll('form[data-members-form]' }); Array.prototype.forEach.call(document.querySelectorAll('[data-members-plan]'), function (el) { - var errorEl = el.querySelector('[data-members-error]'); + const errorEl = el.querySelector('[data-members-error]'); function clickHandler(event) { el.removeEventListener('click', clickHandler); event.preventDefault(); - var plan = el.dataset.membersPlan; - var successUrl = el.dataset.membersSuccess; - var cancelUrl = el.dataset.membersCancel; - var checkoutSuccessUrl; - var checkoutCancelUrl; + const plan = el.dataset.membersPlan; + const successUrl = el.dataset.membersSuccess; + const cancelUrl = el.dataset.membersCancel; + let checkoutSuccessUrl; + let checkoutCancelUrl; if (successUrl) { checkoutSuccessUrl = (new URL(successUrl, window.location.href)).href; @@ -98,7 +98,7 @@ Array.prototype.forEach.call(document.querySelectorAll('[data-members-plan]'), f return res.json(); }); }).then(function (result) { - var stripe = Stripe(result.publicKey); + const stripe = Stripe(result.publicKey); return stripe.redirectToCheckout({ sessionId: result.sessionId }); @@ -120,11 +120,11 @@ Array.prototype.forEach.call(document.querySelectorAll('[data-members-plan]'), f }); Array.prototype.forEach.call(document.querySelectorAll('[data-members-edit-billing]'), function (el) { - var errorEl = el.querySelector('[data-members-error]'); - var membersSuccess = el.dataset.membersSuccess; - var membersCancel = el.dataset.membersCancel; - var successUrl; - var cancelUrl; + const errorEl = el.querySelector('[data-members-error]'); + const membersSuccess = el.dataset.membersSuccess; + const membersCancel = el.dataset.membersCancel; + let successUrl; + let cancelUrl; if (membersSuccess) { successUrl = (new URL(membersSuccess, window.location.href)).href; @@ -167,7 +167,7 @@ Array.prototype.forEach.call(document.querySelectorAll('[data-members-edit-billi return res.json(); }); }).then(function (result) { - var stripe = Stripe(result.publicKey); + const stripe = Stripe(result.publicKey); return stripe.redirectToCheckout({ sessionId: result.sessionId }); @@ -210,14 +210,14 @@ Array.prototype.forEach.call(document.querySelectorAll('[data-members-signout]') }); Array.prototype.forEach.call(document.querySelectorAll('[data-members-cancel-subscription]'), function (el) { - var errorEl = el.parentElement.querySelector('[data-members-error]'); + const errorEl = el.parentElement.querySelector('[data-members-error]'); function clickHandler(event) { el.removeEventListener('click', clickHandler); event.preventDefault(); el.classList.remove('error'); el.classList.add('loading'); - var subscriptionId = el.dataset.membersCancelSubscription; + const subscriptionId = el.dataset.membersCancelSubscription; if (errorEl) { errorEl.innerText = ''; @@ -260,14 +260,14 @@ Array.prototype.forEach.call(document.querySelectorAll('[data-members-cancel-sub }); Array.prototype.forEach.call(document.querySelectorAll('[data-members-continue-subscription]'), function (el) { - var errorEl = el.parentElement.querySelector('[data-members-error]'); + const errorEl = el.parentElement.querySelector('[data-members-error]'); function clickHandler(event) { el.removeEventListener('click', clickHandler); event.preventDefault(); el.classList.remove('error'); el.classList.add('loading'); - var subscriptionId = el.dataset.membersContinueSubscription; + const subscriptionId = el.dataset.membersContinueSubscription; if (errorEl) { errorEl.innerText = ''; @@ -309,7 +309,7 @@ Array.prototype.forEach.call(document.querySelectorAll('[data-members-continue-s el.addEventListener('click', clickHandler); }); -var url = new URL(window.location); +const url = new URL(window.location); if (url.searchParams.get('token')) { url.searchParams.delete('token'); window.history.replaceState({}, document.title, url.href); diff --git a/core/server/public/members.min.js b/core/server/public/members.min.js index 915751dbbb..496fa588ea 100644 --- a/core/server/public/members.min.js +++ b/core/server/public/members.min.js @@ -1 +1,16 @@ -Array.prototype.forEach.call(document.querySelectorAll("form[data-members-form]"),function(i){var c=i.querySelector("[data-members-error]");i.addEventListener("submit",function r(e){i.removeEventListener("submit",r),e.preventDefault(),c&&(c.innerText=""),i.classList.remove("success","invalid","error");for(var t=e.target.querySelector("input[data-members-email]").value,n=void 0,a=[],o=e.target.querySelectorAll("input[data-members-label]")||[],s=0;s { diff --git a/core/server/services/auth/setup.js b/core/server/services/auth/setup.js index 4830e068d8..be2a136912 100644 --- a/core/server/services/auth/setup.js +++ b/core/server/services/auth/setup.js @@ -91,17 +91,18 @@ function sendWelcomeEmail(email, mailAPI) { return mail.utils.generateContent({data: data, template: 'welcome'}) .then((content) => { const message = { - to: email, - subject: common.i18n.t('common.api.authentication.mail.yourNewGhostBlog'), - html: content.html, - text: content.text - }, - payload = { - mail: [{ - message: message, - options: {} - }] - }; + to: email, + subject: common.i18n.t('common.api.authentication.mail.yourNewGhostBlog'), + html: content.html, + text: content.text + }; + + const payload = { + mail: [{ + message: message, + options: {} + }] + }; mailAPI.send(payload, {context: {internal: true}}) .catch((err) => { diff --git a/core/server/services/mail/utils.js b/core/server/services/mail/utils.js index 6b627fe813..96feaf9321 100644 --- a/core/server/services/mail/utils.js +++ b/core/server/services/mail/utils.js @@ -1,35 +1,28 @@ -var _ = require('lodash').runInContext(), - fs = require('fs-extra'), - path = require('path'), - htmlToText = require('html-to-text'), - urlUtils = require('../../lib/url-utils'), - templatesDir = path.resolve(__dirname, '..', 'mail', 'templates'); +const _ = require('lodash').runInContext(); +const fs = require('fs-extra'); +const path = require('path'); +const htmlToText = require('html-to-text'); +const urlUtils = require('../../lib/url-utils'); +const templatesDir = path.resolve(__dirname, '..', 'mail', 'templates'); _.templateSettings.interpolate = /{{([\s\S]+?)}}/g; exports.generateContent = function generateContent(options) { - var defaults, - data; - - defaults = { + const defaults = { siteUrl: urlUtils.urlFor('home', true) }; - data = _.defaults(defaults, options.data); + const data = _.defaults(defaults, options.data); // read the proper email body template return fs.readFile(path.join(templatesDir, options.template + '.html'), 'utf8') .then(function (content) { - var compiled, - htmlContent, - textContent; - // insert user-specific data into the email - compiled = _.template(content); - htmlContent = compiled(data); + const compiled = _.template(content); + const htmlContent = compiled(data); // generate a plain-text version of the same email - textContent = htmlToText.fromString(htmlContent); + const textContent = htmlToText.fromString(htmlContent); return { html: htmlContent, diff --git a/core/server/services/permissions/actions-map-cache.js b/core/server/services/permissions/actions-map-cache.js index 0b894835a3..b7255d032f 100644 --- a/core/server/services/permissions/actions-map-cache.js +++ b/core/server/services/permissions/actions-map-cache.js @@ -1,13 +1,14 @@ // Based heavily on the settings cache -var _ = require('lodash'), - actionsMap = {}; +const _ = require('lodash'); + +let actionsMap = {}; module.exports = { getAll: function getAll() { return _.cloneDeep(actionsMap); }, init: function init(perms) { - var seenActions = {}; + const seenActions = {}; actionsMap = {}; @@ -20,8 +21,8 @@ module.exports = { } */ _.each(perms.models, function (perm) { - var actionType = perm.get('action_type'), - objectType = perm.get('object_type'); + const actionType = perm.get('action_type'); + const objectType = perm.get('object_type'); actionsMap[actionType] = actionsMap[actionType] || []; seenActions[actionType] = seenActions[actionType] || {}; diff --git a/core/server/services/permissions/can-this.js b/core/server/services/permissions/can-this.js index 981bcc41e7..743aa240a6 100644 --- a/core/server/services/permissions/can-this.js +++ b/core/server/services/permissions/can-this.js @@ -1,19 +1,19 @@ -var _ = require('lodash'), - Promise = require('bluebird'), - models = require('../../models'), - common = require('../../lib/common'), - providers = require('./providers'), - parseContext = require('./parse-context'), - actionsMap = require('./actions-map-cache'), - canThis, - CanThisResult; +const _ = require('lodash'); +const Promise = require('bluebird'); +const models = require('../../models'); +const common = require('../../lib/common'); +const providers = require('./providers'); +const parseContext = require('./parse-context'); +const actionsMap = require('./actions-map-cache'); +let canThis; +let CanThisResult; // Base class for canThis call results CanThisResult = function () { }; CanThisResult.prototype.buildObjectTypeHandlers = function (objTypes, actType, context, permissionLoad) { - var objectTypeModelMap = { + const objectTypeModelMap = { post: models.Post, role: models.Role, user: models.User, @@ -25,12 +25,12 @@ CanThisResult.prototype.buildObjectTypeHandlers = function (objTypes, actType, c // Iterate through the object types, i.e. ['post', 'tag', 'user'] return _.reduce(objTypes, function (objTypeHandlers, objType) { // Grab the TargetModel through the objectTypeModelMap - var TargetModel = objectTypeModelMap[objType]; + const TargetModel = objectTypeModelMap[objType]; // Create the 'handler' for the object type; // the '.post()' in canThis(user).edit.post() objTypeHandlers[objType] = function (modelOrId, unsafeAttrs) { - var modelId; + let modelId; unsafeAttrs = unsafeAttrs || {}; // If it's an internal request, resolve immediately @@ -48,32 +48,34 @@ CanThisResult.prototype.buildObjectTypeHandlers = function (objTypes, actType, c // Wait for the user loading to finish return permissionLoad.then(function (loadedPermissions) { // Iterate through the user permissions looking for an affirmation - var userPermissions = loadedPermissions.user ? loadedPermissions.user.permissions : null, - apiKeyPermissions = loadedPermissions.apiKey ? loadedPermissions.apiKey.permissions : null, - hasUserPermission, - hasApiKeyPermission, - checkPermission = function (perm) { - var permObjId; + const userPermissions = loadedPermissions.user ? loadedPermissions.user.permissions : null; - // Look for a matching action type and object type first - if (perm.get('action_type') !== actType || perm.get('object_type') !== objType) { - return false; - } + const apiKeyPermissions = loadedPermissions.apiKey ? loadedPermissions.apiKey.permissions : null; + let hasUserPermission; + let hasApiKeyPermission; - // Grab the object id (if specified, could be null) - permObjId = perm.get('object_id'); + const checkPermission = function (perm) { + let permObjId; - // If we didn't specify a model (any thing) - // or the permission didn't have an id scope set - // then the "thing" has permission - if (!modelId || !permObjId) { - return true; - } + // Look for a matching action type and object type first + if (perm.get('action_type') !== actType || perm.get('object_type') !== objType) { + return false; + } - // Otherwise, check if the id's match - // TODO: String vs Int comparison possibility here? - return modelId === permObjId; - }; + // Grab the object id (if specified, could be null) + permObjId = perm.get('object_id'); + + // If we didn't specify a model (any thing) + // or the permission didn't have an id scope set + // then the "thing" has permission + if (!modelId || !permObjId) { + return true; + } + + // Otherwise, check if the id's match + // TODO: String vs Int comparison possibility here? + return modelId === permObjId; + }; if (loadedPermissions.user && _.some(loadedPermissions.user.roles, {name: 'Owner'})) { hasUserPermission = true; @@ -109,10 +111,10 @@ CanThisResult.prototype.buildObjectTypeHandlers = function (objTypes, actType, c }; CanThisResult.prototype.beginCheck = function (context) { - var self = this, - userPermissionLoad, - apiKeyPermissionLoad, - permissionsLoad; + const self = this; + let userPermissionLoad; + let apiKeyPermissionLoad; + let permissionsLoad; // Get context.user, context.api_key and context.app context = parseContext(context); @@ -149,7 +151,7 @@ CanThisResult.prototype.beginCheck = function (context) { _.each(actionsMap.getAll(), function (objTypes, actType) { // Build up the object type handlers; // the '.post()' parts in canThis(user).edit.post() - var objTypeHandlers = self.buildObjectTypeHandlers(objTypes, actType, context, permissionsLoad); + const objTypeHandlers = self.buildObjectTypeHandlers(objTypes, actType, context, permissionsLoad); // Define a property for the action on the result; // the '.edit' in canThis(user).edit.post() @@ -166,7 +168,7 @@ CanThisResult.prototype.beginCheck = function (context) { }; canThis = function (context) { - var result = new CanThisResult(); + const result = new CanThisResult(); return result.beginCheck(context); }; diff --git a/core/server/services/permissions/index.js b/core/server/services/permissions/index.js index 8df99e26e6..46b39c6a18 100644 --- a/core/server/services/permissions/index.js +++ b/core/server/services/permissions/index.js @@ -1,9 +1,10 @@ // canThis(someUser).edit.posts([id]|[[ids]]) // canThis(someUser).edit.post(somePost|somePostId) -var models = require('../../models'), - actionsMap = require('./actions-map-cache'), - init; +const models = require('../../models'); + +const actionsMap = require('./actions-map-cache'); +let init; init = function init(options) { options = options || {}; diff --git a/core/server/services/permissions/parse-context.js b/core/server/services/permissions/parse-context.js index fbde6600d8..fc071f14c6 100644 --- a/core/server/services/permissions/parse-context.js +++ b/core/server/services/permissions/parse-context.js @@ -6,7 +6,7 @@ * @return {{internal: boolean, external: boolean, user: integer|null, public: boolean, api_key: Object|null}} */ module.exports = function parseContext(context) { - var parsed = { + const parsed = { internal: false, external: false, user: null, diff --git a/core/server/services/permissions/providers.js b/core/server/services/permissions/providers.js index 152d61d705..324eb32093 100644 --- a/core/server/services/permissions/providers.js +++ b/core/server/services/permissions/providers.js @@ -1,31 +1,33 @@ -var _ = require('lodash'), - Promise = require('bluebird'), - models = require('../../models'), - common = require('../../lib/common'); +const _ = require('lodash'); +const Promise = require('bluebird'); +const models = require('../../models'); +const common = require('../../lib/common'); module.exports = { user: function (id) { return models.User.findOne({id: id, status: 'active'}, {withRelated: ['permissions', 'roles', 'roles.permissions']}) .then(function (foundUser) { - // CASE: {context: {user: id}} where the id is not in our database + // CASE: {context: {user: id}} where the id is not in our database if (!foundUser) { return Promise.reject(new common.errors.NotFoundError({ message: common.i18n.t('errors.models.user.userNotFound') })); } - var seenPerms = {}, - rolePerms = _.map(foundUser.related('roles').models, function (role) { - return role.related('permissions').models; - }), - allPerms = [], - user = foundUser.toJSON(); + const seenPerms = {}; + + const rolePerms = _.map(foundUser.related('roles').models, function (role) { + return role.related('permissions').models; + }); + + const allPerms = []; + const user = foundUser.toJSON(); rolePerms.push(foundUser.related('permissions').models); _.each(rolePerms, function (rolePermGroup) { _.each(rolePermGroup, function (perm) { - var key = perm.get('action_type') + '-' + perm.get('object_type') + '-' + perm.get('object_id'); + const key = perm.get('action_type') + '-' + perm.get('object_type') + '-' + perm.get('object_id'); // Only add perms once if (seenPerms[key]) { diff --git a/core/server/services/permissions/public.js b/core/server/services/permissions/public.js index b6eeaca0e0..c56d54e886 100644 --- a/core/server/services/permissions/public.js +++ b/core/server/services/permissions/public.js @@ -1,8 +1,8 @@ -var _ = require('lodash'), - Promise = require('bluebird'), - common = require('../../lib/common'), - parseContext = require('./parse-context'), - _private = {}; +const _ = require('lodash'); +const Promise = require('bluebird'); +const common = require('../../lib/common'); +const parseContext = require('./parse-context'); +const _private = {}; /** * @TODO: @@ -16,7 +16,7 @@ var _ = require('lodash'), * - public context cannot fetch draft/scheduled posts */ _private.applyStatusRules = function applyStatusRules(docName, method, opts) { - var err = new common.errors.NoPermissionError({message: common.i18n.t('errors.permissions.applyStatusRules.error', {docName: docName})}); + const err = new common.errors.NoPermissionError({message: common.i18n.t('errors.permissions.applyStatusRules.error', {docName: docName})}); // Enforce status 'active' for users if (docName === 'users') { diff --git a/core/server/services/slack.js b/core/server/services/slack.js index 90b932ecee..8c99933c50 100644 --- a/core/server/services/slack.js +++ b/core/server/services/slack.js @@ -1,37 +1,37 @@ -var common = require('../lib/common'), - request = require('../lib/request'), - imageLib = require('../lib/image'), - urlUtils = require('../lib/url-utils'), - urlService = require('../../frontend/services/url'), - settingsCache = require('./settings/cache'), - schema = require('../data/schema').checks, - moment = require('moment'), +const common = require('../lib/common'); +const request = require('../lib/request'); +const imageLib = require('../lib/image'); +const urlUtils = require('../lib/url-utils'); +const urlService = require('../../frontend/services/url'); +const settingsCache = require('./settings/cache'); +const schema = require('../data/schema').checks; +const moment = require('moment'); - defaultPostSlugs = [ - 'welcome', - 'the-editor', - 'using-tags', - 'managing-users', - 'private-sites', - 'advanced-markdown', - 'themes' - ]; +const defaultPostSlugs = [ + 'welcome', + 'the-editor', + 'using-tags', + 'managing-users', + 'private-sites', + 'advanced-markdown', + 'themes' +]; function getSlackSettings() { - var setting = settingsCache.get('slack'); + const setting = settingsCache.get('slack'); // This might one day have multiple entries, for now its always a array // and we return the first item or an empty object return setting ? setting[0] : {}; } function ping(post) { - let message, - title, - author, - description, - slackData = {}, - slackSettings = getSlackSettings(), - blogTitle = settingsCache.get('title'); + let message; + let title; + let author; + let description; + let slackData = {}; + let slackSettings = getSlackSettings(); + let blogTitle = settingsCache.get('title'); // If this is a post, we want to send the link of the post if (schema.isPost(post)) { diff --git a/core/server/services/xmlrpc.js b/core/server/services/xmlrpc.js index b46b4bc795..1082ab8a08 100644 --- a/core/server/services/xmlrpc.js +++ b/core/server/services/xmlrpc.js @@ -1,31 +1,32 @@ -var _ = require('lodash'), - xml = require('xml'), - config = require('../config'), - urlService = require('../../frontend/services/url'), - common = require('../lib/common'), - request = require('../lib/request'), - settingsCache = require('./settings/cache'), +const _ = require('lodash'); +const xml = require('xml'); +const config = require('../config'); +const urlService = require('../../frontend/services/url'); +const common = require('../lib/common'); +const request = require('../lib/request'); +const settingsCache = require('./settings/cache'); - defaultPostSlugs = [ - 'welcome', - 'the-editor', - 'using-tags', - 'managing-users', - 'private-sites', - 'advanced-markdown', - 'themes' - ], - // ToDo: Make this configurable - pingList = [ - { - url: 'http://rpc.pingomatic.com' - } - ]; +const defaultPostSlugs = [ + 'welcome', + 'the-editor', + 'using-tags', + 'managing-users', + 'private-sites', + 'advanced-markdown', + 'themes' +]; + +// ToDo: Make this configurable +const pingList = [ + { + url: 'http://rpc.pingomatic.com' + } +]; function ping(post) { - var pingXML, - title = post.title, - url = urlService.getUrlByResourceId(post.id, {absolute: true}); + let pingXML; + const title = post.title; + const url = urlService.getUrlByResourceId(post.id, {absolute: true}); if (post.type === 'page' || config.isPrivacyDisabled('useRpcPing') || settingsCache.get('is_private')) { return; @@ -62,7 +63,7 @@ function ping(post) { // Ping each of the defined services. _.each(pingList, function (pingHost) { - var options = { + const options = { body: pingXML, timeout: 2 * 1000 }; diff --git a/core/server/update-check.js b/core/server/update-check.js index 4407c0426e..3919c07481 100644 --- a/core/server/update-check.js +++ b/core/server/update-check.js @@ -7,24 +7,25 @@ * Blog owners can opt-out of update checks by setting `privacy: { useUpdateCheck: false }` in their config file. */ -const crypto = require('crypto'), - exec = require('child_process').exec, - moment = require('moment'), - Promise = require('bluebird'), - _ = require('lodash'), - url = require('url'), - debug = require('ghost-ignition').debug('update-check'), - api = require('./api').v2, - config = require('./config'), - urlUtils = require('./lib/url-utils'), - common = require('./lib/common'), - request = require('./lib/request'), - ghostVersion = require('./lib/ghost-version'), - internal = {context: {internal: true}}, - allowedCheckEnvironments = ['development', 'production']; +const crypto = require('crypto'); + +const exec = require('child_process').exec; +const moment = require('moment'); +const Promise = require('bluebird'); +const _ = require('lodash'); +const url = require('url'); +const debug = require('ghost-ignition').debug('update-check'); +const api = require('./api').v2; +const config = require('./config'); +const urlUtils = require('./lib/url-utils'); +const common = require('./lib/common'); +const request = require('./lib/request'); +const ghostVersion = require('./lib/ghost-version'); +const internal = {context: {internal: true}}; +const allowedCheckEnvironments = ['development', 'production']; function nextCheckTimestamp() { - var now = Math.round(new Date().getTime() / 1000); + const now = Math.round(new Date().getTime() / 1000); return now + (24 * 3600); } @@ -87,8 +88,8 @@ function createCustomNotification(notification) { * @returns {Promise} */ function updateCheckData() { - let data = {}, - mailConfig = config.get('mail'); + let data = {}; + let mailConfig = config.get('mail'); data.ghost_version = ghostVersion.original; data.node_version = process.versions.node; @@ -106,14 +107,14 @@ function updateCheckData() { users: api.users.browse(internal).reflect(), npm: Promise.promisify(exec)('npm -v').reflect() }).then(function (descriptors) { - var hash = descriptors.hash.value().settings[0], - theme = descriptors.theme.value().settings[0], - posts = descriptors.posts.value(), - users = descriptors.users.value(), - npm = descriptors.npm.value(), - blogUrl = urlUtils.urlFor('home', true), - parsedBlogUrl = url.parse(blogUrl), - blogId = parsedBlogUrl.hostname + parsedBlogUrl.pathname.replace(/\//, '') + hash.value; + const hash = descriptors.hash.value().settings[0]; + const theme = descriptors.theme.value().settings[0]; + const posts = descriptors.posts.value(); + const users = descriptors.users.value(); + const npm = descriptors.npm.value(); + const blogUrl = urlUtils.urlFor('home', true); + const parsedBlogUrl = url.parse(blogUrl); + const blogId = parsedBlogUrl.hostname + parsedBlogUrl.pathname.replace(/\//, '') + hash.value; data.url = blogUrl; data.blog_id = crypto.createHash('md5').update(blogId).digest('hex'); @@ -140,11 +141,12 @@ function updateCheckRequest() { return updateCheckData() .then(function then(reqData) { let reqObj = { - timeout: 1000, - headers: {} - }, - checkEndpoint = config.get('updateCheck:url'), - checkMethod = config.isPrivacyDisabled('useUpdateCheck') ? 'GET' : 'POST'; + timeout: 1000, + headers: {} + }; + + let checkEndpoint = config.get('updateCheck:url'); + let checkMethod = config.isPrivacyDisabled('useUpdateCheck') ? 'GET' : 'POST'; // CASE: Expose stats and do a check-in if (checkMethod === 'POST') { @@ -166,7 +168,7 @@ function updateCheckRequest() { return response.body; }) .catch(function (err) { - // CASE: no notifications available, ignore + // CASE: no notifications available, ignore if (err.statusCode === 404) { return { next_check: nextCheckTimestamp(), @@ -223,8 +225,8 @@ function updateCheckRequest() { * @return {Promise} */ function updateCheckResponse(response) { - let notifications = [], - notificationGroups = (config.get('notificationGroups') || []).concat(['all']); + let notifications = []; + let notificationGroups = (config.get('notificationGroups') || []).concat(['all']); debug('Notification Groups', notificationGroups); debug('Response Update Check Service', response); diff --git a/core/server/web/admin/middleware.js b/core/server/web/admin/middleware.js index 451dd519b9..36e9b7aaf6 100644 --- a/core/server/web/admin/middleware.js +++ b/core/server/web/admin/middleware.js @@ -1,9 +1,9 @@ const urlUtils = require('../../lib/url-utils'); function redirectAdminUrls(req, res, next) { - const subdir = urlUtils.getSubdir(), - ghostPathRegex = new RegExp(`^${subdir}/ghost/(.+)`), - ghostPathMatch = req.originalUrl.match(ghostPathRegex); + const subdir = urlUtils.getSubdir(); + const ghostPathRegex = new RegExp(`^${subdir}/ghost/(.+)`); + const ghostPathMatch = req.originalUrl.match(ghostPathRegex); if (ghostPathMatch) { return res.redirect(urlUtils.urlJoin(urlUtils.urlFor('admin'), '#', ghostPathMatch[1])); diff --git a/core/server/web/api/middleware/cors.js b/core/server/web/api/middleware/cors.js index 615551c72f..8a62c31651 100644 --- a/core/server/web/api/middleware/cors.js +++ b/core/server/web/api/middleware/cors.js @@ -12,10 +12,11 @@ const DISABLE_CORS = {origin: false}; * @return {Array} */ function getIPs() { - const ifaces = os.networkInterfaces(), - ips = [ - 'localhost' - ]; + const ifaces = os.networkInterfaces(); + + const ips = [ + 'localhost' + ]; Object.keys(ifaces).forEach((ifname) => { ifaces[ifname].forEach((iface) => { diff --git a/core/server/web/shared/middlewares/uncapitalise.js b/core/server/web/shared/middlewares/uncapitalise.js index 792a9834af..1764955d36 100644 --- a/core/server/web/shared/middlewares/uncapitalise.js +++ b/core/server/web/shared/middlewares/uncapitalise.js @@ -22,8 +22,8 @@ const uncapitalise = (req, res, next) => { let redirectPath; let decodedURI; - const isSignupOrReset = pathToTest.match(/^(.*\/ghost\/(signup|reset)\/)/i), - isAPI = pathToTest.match(/^(.*\/ghost\/api\/(v[\d.]+|canary)\/.*?\/)/i); + const isSignupOrReset = pathToTest.match(/^(.*\/ghost\/(signup|reset)\/)/i); + const isAPI = pathToTest.match(/^(.*\/ghost\/api\/(v[\d.]+|canary)\/.*?\/)/i); if (isSignupOrReset) { pathToTest = isSignupOrReset[1]; diff --git a/test/api-acceptance/admin/email_preview_spec.js b/test/api-acceptance/admin/email_preview_spec.js index 1e1d77a0a7..a96ad7f2f8 100644 --- a/test/api-acceptance/admin/email_preview_spec.js +++ b/test/api-acceptance/admin/email_preview_spec.js @@ -35,7 +35,7 @@ describe('Email Preview API', function () { } should.not.exist(res.headers['x-cache-invalidate']); - var jsonResponse = res.body; + const jsonResponse = res.body; should.exist(jsonResponse); should.exist(jsonResponse.errors); testUtils.API.checkResponseValue(jsonResponse.errors[0], [ diff --git a/test/api-acceptance/admin/notifications_spec.js b/test/api-acceptance/admin/notifications_spec.js index 1b9cecff36..94e66fc85a 100644 --- a/test/api-acceptance/admin/notifications_spec.js +++ b/test/api-acceptance/admin/notifications_spec.js @@ -36,7 +36,7 @@ describe('Notifications API', function () { .expect('Cache-Control', testUtils.cacheRules.private) .expect(201) .then(function (res) { - var jsonResponse = res.body; + const jsonResponse = res.body; should.exist(jsonResponse.notifications); diff --git a/test/api-acceptance/admin/oembed_spec.js b/test/api-acceptance/admin/oembed_spec.js index d4e70b93d7..5b39604793 100644 --- a/test/api-acceptance/admin/oembed_spec.js +++ b/test/api-acceptance/admin/oembed_spec.js @@ -8,7 +8,8 @@ const localUtils = require('./utils'); const ghost = testUtils.startGhost; describe('Oembed API', function () { - let ghostServer, request; + let ghostServer; + let request; before(function () { return ghost() diff --git a/test/api-acceptance/admin/posts_spec.js b/test/api-acceptance/admin/posts_spec.js index d6fe4cba3c..4d93997a92 100644 --- a/test/api-acceptance/admin/posts_spec.js +++ b/test/api-acceptance/admin/posts_spec.js @@ -194,7 +194,7 @@ describe('Posts API', function () { } should.not.exist(res.headers['x-cache-invalidate']); - var jsonResponse = res.body; + const jsonResponse = res.body; should.exist(jsonResponse); should.exist(jsonResponse.posts); localUtils.API.checkResponse(jsonResponse.posts[0], 'post'); @@ -219,7 +219,7 @@ describe('Posts API', function () { } should.not.exist(res.headers['x-cache-invalidate']); - var jsonResponse = res.body; + const jsonResponse = res.body; should.exist(jsonResponse); should.exist(jsonResponse.posts); localUtils.API.checkResponse(jsonResponse.posts[0], 'post'); @@ -243,7 +243,7 @@ describe('Posts API', function () { } should.not.exist(res.headers['x-cache-invalidate']); - var jsonResponse = res.body; + const jsonResponse = res.body; should.exist(jsonResponse); should.exist(jsonResponse.posts); diff --git a/test/api-acceptance/admin/settings_spec.js b/test/api-acceptance/admin/settings_spec.js index 14cd3e8782..b0dc74f409 100644 --- a/test/api-acceptance/admin/settings_spec.js +++ b/test/api-acceptance/admin/settings_spec.js @@ -39,7 +39,7 @@ describe('Settings API', function () { } should.not.exist(res.headers['x-cache-invalidate']); - var jsonResponse = res.body; + const jsonResponse = res.body; should.exist(jsonResponse); localUtils.API.checkResponse(jsonResponse, 'settings'); @@ -97,68 +97,69 @@ describe('Settings API', function () { return done(err); } - var jsonResponse = res.body, - changedValue = [], - settingToChange = { - settings: [ - { - key: 'title', - value: changedValue - }, - { - key: 'codeinjection_head', - value: null - }, - { - key: 'navigation', - value: {label: 'label1'} - }, - { - key: 'slack', - value: JSON.stringify({username: 'username'}) - }, - { - key: 'is_private', - value: false - }, - { - key: 'meta_title', - value: 'SEO title' - }, - { - key: 'meta_description', - value: 'SEO description' - }, - { - key: 'og_image', - value: '/content/images/2019/07/facebook.png' - }, - { - key: 'og_title', - value: 'facebook title' - }, - { - key: 'og_description', - value: 'facebook description' - }, - { - key: 'twitter_image', - value: '/content/images/2019/07/twitter.png' - }, - { - key: 'twitter_title', - value: 'twitter title' - }, - { - key: 'twitter_description', - value: 'twitter description' - }, - { - key: 'labs', - value: '{"subscribers":false,"members":true}' - } - ] - }; + const jsonResponse = res.body; + const changedValue = []; + + const settingToChange = { + settings: [ + { + key: 'title', + value: changedValue + }, + { + key: 'codeinjection_head', + value: null + }, + { + key: 'navigation', + value: {label: 'label1'} + }, + { + key: 'slack', + value: JSON.stringify({username: 'username'}) + }, + { + key: 'is_private', + value: false + }, + { + key: 'meta_title', + value: 'SEO title' + }, + { + key: 'meta_description', + value: 'SEO description' + }, + { + key: 'og_image', + value: '/content/images/2019/07/facebook.png' + }, + { + key: 'og_title', + value: 'facebook title' + }, + { + key: 'og_description', + value: 'facebook description' + }, + { + key: 'twitter_image', + value: '/content/images/2019/07/twitter.png' + }, + { + key: 'twitter_title', + value: 'twitter title' + }, + { + key: 'twitter_description', + value: 'twitter description' + }, + { + key: 'labs', + value: '{"subscribers":false,"members":true}' + } + ] + }; should.exist(jsonResponse); should.exist(jsonResponse.settings); diff --git a/test/api-acceptance/admin/slugs_spec.js b/test/api-acceptance/admin/slugs_spec.js index 9997998e09..7d058e784d 100644 --- a/test/api-acceptance/admin/slugs_spec.js +++ b/test/api-acceptance/admin/slugs_spec.js @@ -1,11 +1,10 @@ -var should = require('should'), - supertest = require('supertest'), - testUtils = require('../../utils'), - config = require('../../../core/server/config'), - localUtils = require('./utils'), - - ghost = testUtils.startGhost, - request; +const should = require('should'); +const supertest = require('supertest'); +const testUtils = require('../../utils'); +const config = require('../../../core/server/config'); +const localUtils = require('./utils'); +const ghost = testUtils.startGhost; +let request; describe('Slug API', function () { let ghostServer; @@ -33,7 +32,7 @@ describe('Slug API', function () { } should.not.exist(res.headers['x-cache-invalidate']); - var jsonResponse = res.body; + const jsonResponse = res.body; should.exist(jsonResponse); should.exist(jsonResponse.slugs); jsonResponse.slugs.should.have.length(1); diff --git a/test/api-acceptance/admin/users_spec.js b/test/api-acceptance/admin/users_spec.js index 8571dad1eb..838a157961 100644 --- a/test/api-acceptance/admin/users_spec.js +++ b/test/api-acceptance/admin/users_spec.js @@ -12,7 +12,8 @@ const ghost = testUtils.startGhost; let request; describe('User API', function () { - let inactiveUser, admin; + let inactiveUser; + let admin; before(function () { return ghost() @@ -57,7 +58,7 @@ describe('User API', function () { should.not.exist(res.headers['x-cache-invalidate']); - var jsonResponse = res.body; + const jsonResponse = res.body; should.exist(jsonResponse.users); localUtils.API.checkResponse(jsonResponse, 'users'); @@ -102,7 +103,7 @@ describe('User API', function () { } should.not.exist(res.headers['x-cache-invalidate']); - var jsonResponse = res.body; + const jsonResponse = res.body; should.exist(jsonResponse.users); localUtils.API.checkResponse(jsonResponse, 'users'); @@ -141,7 +142,7 @@ describe('User API', function () { } should.not.exist(res.headers['x-cache-invalidate']); - var jsonResponse = res.body; + const jsonResponse = res.body; should.exist(jsonResponse.users); should.not.exist(jsonResponse.meta); @@ -164,7 +165,7 @@ describe('User API', function () { } should.not.exist(res.headers['x-cache-invalidate']); - var jsonResponse = res.body; + const jsonResponse = res.body; should.exist(jsonResponse.users); should.not.exist(jsonResponse.meta); @@ -186,7 +187,7 @@ describe('User API', function () { } should.not.exist(res.headers['x-cache-invalidate']); - var jsonResponse = res.body; + const jsonResponse = res.body; should.exist(jsonResponse.users); should.not.exist(jsonResponse.meta); @@ -213,7 +214,7 @@ describe('User API', function () { return done(err); } - var putBody = res.body; + const putBody = res.body; res.headers['x-cache-invalidate'].should.eql('/*'); should.exist(putBody.users[0]); putBody.users[0].website.should.eql('http://joe-bloggs.ghost.org'); diff --git a/test/api-acceptance/admin/webhooks_spec.js b/test/api-acceptance/admin/webhooks_spec.js index fda1253756..e49cf2bb2d 100644 --- a/test/api-acceptance/admin/webhooks_spec.js +++ b/test/api-acceptance/admin/webhooks_spec.js @@ -8,7 +8,7 @@ const ghost = testUtils.startGhost; let request; describe('Webhooks API', function () { - var ghostServer; + let ghostServer; before(function () { return ghost() @@ -41,7 +41,7 @@ describe('Webhooks API', function () { return done(err); } - var jsonResponse = res.body; + const jsonResponse = res.body; should.exist(jsonResponse.webhooks); @@ -118,7 +118,7 @@ describe('Webhooks API', function () { }); it('Can delete a webhook', function (done) { - var newWebhook = { + const newWebhook = { event: 'test.create', // a different target_url from above is needed to avoid an "already exists" error target_url: 'http://example.com/webhooks/test/2' @@ -136,8 +136,8 @@ describe('Webhooks API', function () { return done(err); } - var location = res.headers.location; - var jsonResponse = res.body; + const location = res.headers.location; + const jsonResponse = res.body; should.exist(jsonResponse.webhooks); localUtils.API.checkResponse(jsonResponse.webhooks[0], 'webhook'); diff --git a/test/api-acceptance/content/authors_spec.js b/test/api-acceptance/content/authors_spec.js index da5a927cae..10a48d9118 100644 --- a/test/api-acceptance/content/authors_spec.js +++ b/test/api-acceptance/content/authors_spec.js @@ -43,7 +43,7 @@ describe('Authors Content API', function () { } should.not.exist(res.headers['x-cache-invalidate']); - var jsonResponse = res.body; + const jsonResponse = res.body; should.exist(jsonResponse.authors); localUtils.API.checkResponse(jsonResponse, 'authors'); jsonResponse.authors.should.have.length(3); @@ -79,7 +79,7 @@ describe('Authors Content API', function () { return done(err); } - var jsonResponse = res.body; + const jsonResponse = res.body; should.exist(jsonResponse.authors); jsonResponse.authors.should.have.length(3); @@ -117,7 +117,7 @@ describe('Authors Content API', function () { } should.not.exist(res.headers['x-cache-invalidate']); - var jsonResponse = res.body; + const jsonResponse = res.body; should.exist(jsonResponse.authors); jsonResponse.authors.should.have.length(1); @@ -140,7 +140,7 @@ describe('Authors Content API', function () { } should.not.exist(res.headers['x-cache-invalidate']); - var jsonResponse = res.body; + const jsonResponse = res.body; should.exist(jsonResponse.authors); jsonResponse.authors.should.have.length(1); diff --git a/test/api-acceptance/content/posts_spec.js b/test/api-acceptance/content/posts_spec.js index d2b8015ee1..d7899b0926 100644 --- a/test/api-acceptance/content/posts_spec.js +++ b/test/api-acceptance/content/posts_spec.js @@ -44,7 +44,7 @@ describe('Posts Content API', function () { should.exist(res.headers['access-control-allow-origin']); should.not.exist(res.headers['x-cache-invalidate']); - var jsonResponse = res.body; + const jsonResponse = res.body; should.exist(jsonResponse.posts); localUtils.API.checkResponse(jsonResponse, 'posts'); jsonResponse.posts.should.have.length(11); @@ -257,7 +257,7 @@ describe('Posts Content API', function () { should.exist(res.headers['access-control-allow-origin']); should.not.exist(res.headers['x-cache-invalidate']); - var jsonResponse = res.body; + const jsonResponse = res.body; should.exist(jsonResponse.posts); localUtils.API.checkResponse(jsonResponse, 'posts'); jsonResponse.posts.should.have.length(11); @@ -283,8 +283,8 @@ describe('Posts Content API', function () { .expect(200) .then(function (res) { should.exist(res.body.posts[0]); - var post = res.body.posts[0], - publishedAt = moment(post.published_at).format('YYYY-MM-DD HH:mm:ss'); + const post = res.body.posts[0]; + const publishedAt = moment(post.published_at).format('YYYY-MM-DD HH:mm:ss'); post.title.should.eql('Welcome to Ghost'); @@ -297,8 +297,8 @@ describe('Posts Content API', function () { }) .then(function (res) { should.exist(res.body.posts[0]); - var post = res.body.posts[0], - publishedAt = moment(post.published_at).format('YYYY-MM-DD HH:mm:ss'); + const post = res.body.posts[0]; + const publishedAt = moment(post.published_at).format('YYYY-MM-DD HH:mm:ss'); post.title.should.eql('Writing posts with Ghost ✍️'); @@ -311,7 +311,7 @@ describe('Posts Content API', function () { }) .then(function (res) { should.exist(res.body.posts[0]); - var post = res.body.posts[0]; + const post = res.body.posts[0]; post.title.should.eql('Welcome to Ghost'); diff --git a/test/api-acceptance/content/tags_spec.js b/test/api-acceptance/content/tags_spec.js index e9d29832ee..013e474dca 100644 --- a/test/api-acceptance/content/tags_spec.js +++ b/test/api-acceptance/content/tags_spec.js @@ -39,7 +39,7 @@ describe('Tags Content API', function () { } should.not.exist(res.headers['x-cache-invalidate']); - var jsonResponse = res.body; + const jsonResponse = res.body; should.exist(jsonResponse.tags); localUtils.API.checkResponse(jsonResponse, 'tags'); jsonResponse.tags.should.have.length(4); @@ -76,7 +76,7 @@ describe('Tags Content API', function () { return done(err); } should.not.exist(res.headers['x-cache-invalidate']); - var jsonResponse = res.body; + const jsonResponse = res.body; should.exist(jsonResponse.tags); localUtils.API.checkResponse(jsonResponse, 'tags'); jsonResponse.tags.should.have.length(4); @@ -98,7 +98,7 @@ describe('Tags Content API', function () { } should.not.exist(res.headers['x-cache-invalidate']); - var jsonResponse = res.body; + const jsonResponse = res.body; should.exist(jsonResponse.tags); localUtils.API.checkResponse(jsonResponse, 'tags'); jsonResponse.tags.should.have.length(3); diff --git a/test/regression/api/admin_spec.js b/test/regression/api/admin_spec.js index ce7eef1676..a4a27937d1 100644 --- a/test/regression/api/admin_spec.js +++ b/test/regression/api/admin_spec.js @@ -3,15 +3,16 @@ // Mocking out the models to not touch the DB would turn these into unit tests, and should probably be done in future, // But then again testing real code, rather than mock code, might be more useful... -var should = require('should'), - supertest = require('supertest'), - testUtils = require('../../utils/index'), - configUtils = require('../../utils/configUtils'), - urlUtils = require('../../utils/urlUtils'), - ghost = testUtils.startGhost, - common = require('../../../core/server/lib/common/index'), - config = require('../../../core/server/config/index'), - request; +const should = require('should'); + +const supertest = require('supertest'); +const testUtils = require('../../utils/index'); +const configUtils = require('../../utils/configUtils'); +const urlUtils = require('../../utils/urlUtils'); +const ghost = testUtils.startGhost; +const common = require('../../../core/server/lib/common/index'); +const config = require('../../../core/server/config/index'); +let request; common.i18n.init(); @@ -76,7 +77,7 @@ describe('Admin Routing', function () { // we'll use X-Forwarded-Proto: https to simulate an 'https://' request behind a proxy describe('Require HTTPS - redirect', function () { - var ghostServer; + let ghostServer; before(function () { configUtils.set('url', 'https://localhost:2390'); diff --git a/test/regression/api/canary/admin/authentication_spec.js b/test/regression/api/canary/admin/authentication_spec.js index df97ad75af..2fc87301f5 100644 --- a/test/regression/api/canary/admin/authentication_spec.js +++ b/test/regression/api/canary/admin/authentication_spec.js @@ -237,7 +237,7 @@ describe('Authentication API v3', function () { it('reset password', function (done) { models.User.getOwnerUser(testUtils.context.internal) .then(function (ownerUser) { - var token = security.tokens.resetToken.generateHash({ + const token = security.tokens.resetToken.generateHash({ expires: Date.now() + (1000 * 60), email: user.email, dbHash: settingsCache.get('db_hash'), diff --git a/test/regression/api/canary/admin/posts_spec.js b/test/regression/api/canary/admin/posts_spec.js index 4d1803ac92..8c494446be 100644 --- a/test/regression/api/canary/admin/posts_spec.js +++ b/test/regression/api/canary/admin/posts_spec.js @@ -105,7 +105,7 @@ describe('Posts API', function () { } should.not.exist(res.headers['x-cache-invalidate']); - var jsonResponse = res.body; + const jsonResponse = res.body; should.exist(jsonResponse); should.exist(jsonResponse.errors); testUtils.API.checkResponseValue(jsonResponse.errors[0], [ diff --git a/test/regression/api/canary/admin/settings_spec.js b/test/regression/api/canary/admin/settings_spec.js index 0c851254f1..f5aee62a0c 100644 --- a/test/regression/api/canary/admin/settings_spec.js +++ b/test/regression/api/canary/admin/settings_spec.js @@ -58,7 +58,7 @@ describe('Settings API (canary)', function () { } should.not.exist(res.headers['x-cache-invalidate']); - var jsonResponse = res.body; + const jsonResponse = res.body; should.exist(jsonResponse); should.exist(jsonResponse.errors); testUtils.API.checkResponseValue(jsonResponse.errors[0], [ @@ -85,16 +85,17 @@ describe('Settings API (canary)', function () { return done(err); } - var jsonResponse = res.body, - changedValue = [], - settingToChange = { - settings: [ - { - key: 'labs', - value: '{"subscribers":false,"members":false}' - } - ] - }; + const jsonResponse = res.body; + const changedValue = []; + + const settingToChange = { + settings: [ + { + key: 'labs', + value: '{"subscribers":false,"members":false}' + } + ] + }; should.exist(jsonResponse); should.exist(jsonResponse.settings); @@ -153,8 +154,8 @@ describe('Settings API (canary)', function () { return done(err); } - var jsonResponse = res.body, - newValue = 'new value'; + let jsonResponse = res.body; + const newValue = 'new value'; should.exist(jsonResponse); should.exist(jsonResponse.settings); jsonResponse.settings = [{key: 'testvalue', value: newValue}]; @@ -198,15 +199,16 @@ describe('Settings API (canary)', function () { return done(err); } - const jsonResponse = res.body, - settingToChange = { - settings: [ - { - key: 'is_private', - value: '1' - } - ] - }; + const jsonResponse = res.body; + + const settingToChange = { + settings: [ + { + key: 'is_private', + value: '1' + } + ] + }; should.exist(jsonResponse); should.exist(jsonResponse.settings); @@ -320,8 +322,8 @@ describe('Settings API (canary)', function () { return done(err); } - var jsonResponse = res.body, - newValue = 'new value'; + let jsonResponse = res.body; + const newValue = 'new value'; should.exist(jsonResponse); should.exist(jsonResponse.settings); jsonResponse.settings = [{key: 'visibility', value: 'public'}]; @@ -390,8 +392,8 @@ describe('Settings API (canary)', function () { return done(err); } - var jsonResponse = res.body, - newValue = 'new value'; + let jsonResponse = res.body; + const newValue = 'new value'; should.exist(jsonResponse); should.exist(jsonResponse.settings); jsonResponse.settings = [{key: 'visibility', value: 'public'}]; diff --git a/test/regression/api/canary/admin/users_spec.js b/test/regression/api/canary/admin/users_spec.js index 21d5382f4c..f49ce7d690 100644 --- a/test/regression/api/canary/admin/users_spec.js +++ b/test/regression/api/canary/admin/users_spec.js @@ -8,7 +8,11 @@ const ghost = testUtils.startGhost; let request; describe('User API', function () { - let editor, author, ghostServer, otherAuthor, admin; + let editor; + let author; + let ghostServer; + let otherAuthor; + let admin; describe('As Owner', function () { before(function () { @@ -55,7 +59,7 @@ describe('User API', function () { } should.not.exist(res.headers['x-cache-invalidate']); - var jsonResponse = res.body; + const jsonResponse = res.body; should.exist(jsonResponse); should.exist(jsonResponse.errors); testUtils.API.checkResponseValue(jsonResponse.errors[0], [ @@ -85,7 +89,7 @@ describe('User API', function () { } should.not.exist(res.headers['x-cache-invalidate']); - var jsonResponse = res.body; + const jsonResponse = res.body; should.exist(jsonResponse); should.exist(jsonResponse.errors); testUtils.API.checkResponseValue(jsonResponse.errors[0], [ diff --git a/test/regression/api/canary/content/posts_spec.js b/test/regression/api/canary/content/posts_spec.js index 775b71f823..0127706b10 100644 --- a/test/regression/api/canary/content/posts_spec.js +++ b/test/regression/api/canary/content/posts_spec.js @@ -46,7 +46,7 @@ describe('api/canary/content/posts', function () { should.exist(res.headers['access-control-allow-origin']); should.not.exist(res.headers['x-cache-invalidate']); - var jsonResponse = res.body; + const jsonResponse = res.body; should.exist(jsonResponse.posts); localUtils.API.checkResponse(jsonResponse, 'posts'); jsonResponse.posts.should.have.length(11); @@ -87,7 +87,7 @@ describe('api/canary/content/posts', function () { should.exist(res.headers['access-control-allow-origin']); should.not.exist(res.headers['x-cache-invalidate']); - var jsonResponse = res.body; + const jsonResponse = res.body; should.exist(jsonResponse.posts); localUtils.API.checkResponse(jsonResponse, 'posts'); jsonResponse.posts.should.have.length(11); diff --git a/test/regression/api/v2/admin/authentication_spec.js b/test/regression/api/v2/admin/authentication_spec.js index 9ea1cc8233..b78923b055 100644 --- a/test/regression/api/v2/admin/authentication_spec.js +++ b/test/regression/api/v2/admin/authentication_spec.js @@ -361,7 +361,7 @@ describe('Authentication API v2', function () { it('reset password', function (done) { models.User.getOwnerUser(testUtils.context.internal) .then(function (ownerUser) { - var token = security.tokens.resetToken.generateHash({ + const token = security.tokens.resetToken.generateHash({ expires: Date.now() + (1000 * 60), email: user.email, dbHash: settingsCache.get('db_hash'), diff --git a/test/regression/api/v2/admin/oembed_spec.js b/test/regression/api/v2/admin/oembed_spec.js index 35948eb197..1c338c7756 100644 --- a/test/regression/api/v2/admin/oembed_spec.js +++ b/test/regression/api/v2/admin/oembed_spec.js @@ -8,7 +8,8 @@ const localUtils = require('./utils'); const ghost = testUtils.startGhost; describe('Oembed API (v2)', function () { - let ghostServer, request; + let ghostServer; + let request; before(function () { return ghost() diff --git a/test/regression/api/v2/admin/posts_spec.js b/test/regression/api/v2/admin/posts_spec.js index 47c3d9c428..992271b355 100644 --- a/test/regression/api/v2/admin/posts_spec.js +++ b/test/regression/api/v2/admin/posts_spec.js @@ -105,7 +105,7 @@ describe('Posts API (v2)', function () { } should.not.exist(res.headers['x-cache-invalidate']); - var jsonResponse = res.body; + const jsonResponse = res.body; should.exist(jsonResponse); should.exist(jsonResponse.errors); testUtils.API.checkResponseValue(jsonResponse.errors[0], [ diff --git a/test/regression/api/v2/admin/settings_spec.js b/test/regression/api/v2/admin/settings_spec.js index 1ca5e6ff62..43d2df1883 100644 --- a/test/regression/api/v2/admin/settings_spec.js +++ b/test/regression/api/v2/admin/settings_spec.js @@ -58,7 +58,7 @@ describe('Settings API (v2)', function () { } should.not.exist(res.headers['x-cache-invalidate']); - var jsonResponse = res.body; + const jsonResponse = res.body; should.exist(jsonResponse); should.exist(jsonResponse.errors); testUtils.API.checkResponseValue(jsonResponse.errors[0], [ @@ -85,16 +85,17 @@ describe('Settings API (v2)', function () { return done(err); } - var jsonResponse = res.body, - changedValue = [], - settingToChange = { - settings: [ - { - key: 'labs', - value: '{"subscribers":false,"members":false}' - } - ] - }; + const jsonResponse = res.body; + const changedValue = []; + + const settingToChange = { + settings: [ + { + key: 'labs', + value: '{"subscribers":false,"members":false}' + } + ] + }; should.exist(jsonResponse); should.exist(jsonResponse.settings); @@ -153,8 +154,8 @@ describe('Settings API (v2)', function () { return done(err); } - var jsonResponse = res.body, - newValue = 'new value'; + let jsonResponse = res.body; + const newValue = 'new value'; should.exist(jsonResponse); should.exist(jsonResponse.settings); jsonResponse.settings = [{key: 'testvalue', value: newValue}]; @@ -198,15 +199,16 @@ describe('Settings API (v2)', function () { return done(err); } - const jsonResponse = res.body, - settingToChange = { - settings: [ - { - key: 'is_private', - value: '1' - } - ] - }; + const jsonResponse = res.body; + + const settingToChange = { + settings: [ + { + key: 'is_private', + value: '1' + } + ] + }; should.exist(jsonResponse); should.exist(jsonResponse.settings); @@ -320,8 +322,8 @@ describe('Settings API (v2)', function () { return done(err); } - var jsonResponse = res.body, - newValue = 'new value'; + let jsonResponse = res.body; + const newValue = 'new value'; should.exist(jsonResponse); should.exist(jsonResponse.settings); jsonResponse.settings = [{key: 'visibility', value: 'public'}]; @@ -390,8 +392,8 @@ describe('Settings API (v2)', function () { return done(err); } - var jsonResponse = res.body, - newValue = 'new value'; + let jsonResponse = res.body; + const newValue = 'new value'; should.exist(jsonResponse); should.exist(jsonResponse.settings); jsonResponse.settings = [{key: 'visibility', value: 'public'}]; diff --git a/test/regression/api/v2/admin/users_spec.js b/test/regression/api/v2/admin/users_spec.js index 21d5382f4c..f49ce7d690 100644 --- a/test/regression/api/v2/admin/users_spec.js +++ b/test/regression/api/v2/admin/users_spec.js @@ -8,7 +8,11 @@ const ghost = testUtils.startGhost; let request; describe('User API', function () { - let editor, author, ghostServer, otherAuthor, admin; + let editor; + let author; + let ghostServer; + let otherAuthor; + let admin; describe('As Owner', function () { before(function () { @@ -55,7 +59,7 @@ describe('User API', function () { } should.not.exist(res.headers['x-cache-invalidate']); - var jsonResponse = res.body; + const jsonResponse = res.body; should.exist(jsonResponse); should.exist(jsonResponse.errors); testUtils.API.checkResponseValue(jsonResponse.errors[0], [ @@ -85,7 +89,7 @@ describe('User API', function () { } should.not.exist(res.headers['x-cache-invalidate']); - var jsonResponse = res.body; + const jsonResponse = res.body; should.exist(jsonResponse); should.exist(jsonResponse.errors); testUtils.API.checkResponseValue(jsonResponse.errors[0], [ diff --git a/test/regression/api/v2/content/posts_spec.js b/test/regression/api/v2/content/posts_spec.js index 0560edf211..9258bf1f1b 100644 --- a/test/regression/api/v2/content/posts_spec.js +++ b/test/regression/api/v2/content/posts_spec.js @@ -48,7 +48,7 @@ describe('api/v2/content/posts', function () { should.exist(res.headers['access-control-allow-origin']); should.not.exist(res.headers['x-cache-invalidate']); - var jsonResponse = res.body; + const jsonResponse = res.body; should.exist(jsonResponse.posts); localUtils.API.checkResponse(jsonResponse, 'posts'); jsonResponse.posts.should.have.length(11); diff --git a/test/regression/api/v3/admin/authentication_spec.js b/test/regression/api/v3/admin/authentication_spec.js index df97ad75af..2fc87301f5 100644 --- a/test/regression/api/v3/admin/authentication_spec.js +++ b/test/regression/api/v3/admin/authentication_spec.js @@ -237,7 +237,7 @@ describe('Authentication API v3', function () { it('reset password', function (done) { models.User.getOwnerUser(testUtils.context.internal) .then(function (ownerUser) { - var token = security.tokens.resetToken.generateHash({ + const token = security.tokens.resetToken.generateHash({ expires: Date.now() + (1000 * 60), email: user.email, dbHash: settingsCache.get('db_hash'), diff --git a/test/regression/api/v3/admin/posts_spec.js b/test/regression/api/v3/admin/posts_spec.js index 81c99163e4..9dd5d2afb0 100644 --- a/test/regression/api/v3/admin/posts_spec.js +++ b/test/regression/api/v3/admin/posts_spec.js @@ -105,7 +105,7 @@ describe('Posts API (v3)', function () { } should.not.exist(res.headers['x-cache-invalidate']); - var jsonResponse = res.body; + const jsonResponse = res.body; should.exist(jsonResponse); should.exist(jsonResponse.errors); testUtils.API.checkResponseValue(jsonResponse.errors[0], [ diff --git a/test/regression/api/v3/admin/settings_spec.js b/test/regression/api/v3/admin/settings_spec.js index 06811bca67..1c319141c4 100644 --- a/test/regression/api/v3/admin/settings_spec.js +++ b/test/regression/api/v3/admin/settings_spec.js @@ -57,7 +57,7 @@ describe('Settings API', function () { } should.not.exist(res.headers['x-cache-invalidate']); - var jsonResponse = res.body; + const jsonResponse = res.body; should.exist(jsonResponse); should.exist(jsonResponse.errors); testUtils.API.checkResponseValue(jsonResponse.errors[0], [ @@ -105,8 +105,8 @@ describe('Settings API', function () { return done(err); } - var jsonResponse = res.body, - newValue = 'new value'; + let jsonResponse = res.body; + const newValue = 'new value'; should.exist(jsonResponse); should.exist(jsonResponse.settings); jsonResponse.settings = [{key: 'testvalue', value: newValue}]; @@ -150,15 +150,16 @@ describe('Settings API', function () { return done(err); } - const jsonResponse = res.body, - settingToChange = { - settings: [ - { - key: 'is_private', - value: '1' - } - ] - }; + const jsonResponse = res.body; + + const settingToChange = { + settings: [ + { + key: 'is_private', + value: '1' + } + ] + }; should.exist(jsonResponse); should.exist(jsonResponse.settings); diff --git a/test/regression/api/v3/admin/users_spec.js b/test/regression/api/v3/admin/users_spec.js index 21d5382f4c..f49ce7d690 100644 --- a/test/regression/api/v3/admin/users_spec.js +++ b/test/regression/api/v3/admin/users_spec.js @@ -8,7 +8,11 @@ const ghost = testUtils.startGhost; let request; describe('User API', function () { - let editor, author, ghostServer, otherAuthor, admin; + let editor; + let author; + let ghostServer; + let otherAuthor; + let admin; describe('As Owner', function () { before(function () { @@ -55,7 +59,7 @@ describe('User API', function () { } should.not.exist(res.headers['x-cache-invalidate']); - var jsonResponse = res.body; + const jsonResponse = res.body; should.exist(jsonResponse); should.exist(jsonResponse.errors); testUtils.API.checkResponseValue(jsonResponse.errors[0], [ @@ -85,7 +89,7 @@ describe('User API', function () { } should.not.exist(res.headers['x-cache-invalidate']); - var jsonResponse = res.body; + const jsonResponse = res.body; should.exist(jsonResponse); should.exist(jsonResponse.errors); testUtils.API.checkResponseValue(jsonResponse.errors[0], [ diff --git a/test/regression/api/v3/content/posts_spec.js b/test/regression/api/v3/content/posts_spec.js index 9d423ddac0..88bfe63bea 100644 --- a/test/regression/api/v3/content/posts_spec.js +++ b/test/regression/api/v3/content/posts_spec.js @@ -46,7 +46,7 @@ describe('api/v3/content/posts', function () { should.exist(res.headers['access-control-allow-origin']); should.not.exist(res.headers['x-cache-invalidate']); - var jsonResponse = res.body; + const jsonResponse = res.body; should.exist(jsonResponse.posts); localUtils.API.checkResponse(jsonResponse, 'posts'); jsonResponse.posts.should.have.length(11); @@ -87,7 +87,7 @@ describe('api/v3/content/posts', function () { should.exist(res.headers['access-control-allow-origin']); should.not.exist(res.headers['x-cache-invalidate']); - var jsonResponse = res.body; + const jsonResponse = res.body; should.exist(jsonResponse.posts); localUtils.API.checkResponse(jsonResponse, 'posts'); jsonResponse.posts.should.have.length(11); diff --git a/test/regression/exporter/exporter_spec.js b/test/regression/exporter/exporter_spec.js index 2e24de29bd..ce4e98fb5f 100644 --- a/test/regression/exporter/exporter_spec.js +++ b/test/regression/exporter/exporter_spec.js @@ -1,11 +1,12 @@ -var should = require('should'), - sinon = require('sinon'), - testUtils = require('../../utils'), - _ = require('lodash'), +const should = require('should'); +const sinon = require('sinon'); +const testUtils = require('../../utils'); +const _ = require('lodash'); - // Stuff we are testing - exporter = require('../../../core/server/data/exporter'), - ghostVersion = require('../../../core/server/lib/ghost-version'); +// Stuff we are testing +const exporter = require('../../../core/server/data/exporter'); + +const ghostVersion = require('../../../core/server/lib/ghost-version'); describe('Exporter', function () { before(testUtils.teardownDb); @@ -19,7 +20,7 @@ describe('Exporter', function () { it('exports data', function (done) { exporter.doExport().then(function (exportData) { - var tables = ['posts', 'users', 'roles', 'roles_users', 'permissions', 'permissions_roles', + const tables = ['posts', 'users', 'roles', 'roles_users', 'permissions', 'permissions_roles', 'permissions_users', 'settings', 'tags', 'posts_tags']; should.exist(exportData); diff --git a/test/regression/importer/importer_spec.js b/test/regression/importer/importer_spec.js index fdb9065aaf..2ed0cb962e 100644 --- a/test/regression/importer/importer_spec.js +++ b/test/regression/importer/importer_spec.js @@ -1,23 +1,25 @@ -var should = require('should'), - sinon = require('sinon'), - testUtils = require('../../utils'), - Promise = require('bluebird'), - moment = require('moment'), - ObjectId = require('bson-objectid'), - assert = require('assert'), - _ = require('lodash'), - validator = require('validator'), +const should = require('should'); +const sinon = require('sinon'); +const testUtils = require('../../utils'); +const Promise = require('bluebird'); +const moment = require('moment'); +const ObjectId = require('bson-objectid'); +const assert = require('assert'); +const _ = require('lodash'); +const validator = require('validator'); - // Stuff we are testing - db = require('../../../core/server/data/db'), - models = require('../../../core/server/models'), - importer = require('../../../core/server/data/importer'), - dataImporter = importer.importers[1], - importOptions = { - returnImportedData: true - }, +// Stuff we are testing +const db = require('../../../core/server/data/db'); - knex = db.knex; +const models = require('../../../core/server/models'); +const importer = require('../../../core/server/data/importer'); +const dataImporter = importer.importers[1]; + +const importOptions = { + returnImportedData: true +}; + +const knex = db.knex; const exportedLatestBody = () => { return _.clone({ @@ -396,10 +398,10 @@ describe('Integration: Importer', function () { importedData.length.should.equal(4, 'Did not get data successfully'); - const users = importedData[0], - posts = importedData[1].data, - settings = importedData[2], - tags = importedData[3]; + const users = importedData[0]; + const posts = importedData[1].data; + const settings = importedData[2]; + const tags = importedData[3]; // we always have 1 user, the owner user we added users.length.should.equal(1, 'There should only be one user'); diff --git a/test/regression/migrations/migration_spec.js b/test/regression/migrations/migration_spec.js index 51e4d2e973..4b6e3e3052 100644 --- a/test/regression/migrations/migration_spec.js +++ b/test/regression/migrations/migration_spec.js @@ -1,9 +1,9 @@ -var should = require('should'), - sinon = require('sinon'), - testUtils = require('../../utils'), - _ = require('lodash'), - Promise = require('bluebird'), - Models = require('../../../core/server/models'); +const should = require('should'); +const sinon = require('sinon'); +const testUtils = require('../../utils'); +const _ = require('lodash'); +const Promise = require('bluebird'); +const Models = require('../../../core/server/models'); describe('Database Migration (special functions)', function () { before(testUtils.teardownDb); @@ -15,7 +15,7 @@ describe('Database Migration (special functions)', function () { describe('Fixtures', function () { // Custom assertion for detection that a permissions is assigned to the correct roles should.Assertion.add('AssignedToRoles', function (roles) { - var roleNames; + let roleNames; this.params = {operator: 'to have role'}; should.exist(this.obj); @@ -31,7 +31,7 @@ describe('Database Migration (special functions)', function () { // Custom assertion to wrap all permissions should.Assertion.add('CompletePermissions', function () { this.params = {operator: 'to have a complete set of permissions'}; - var permissions = this.obj; + const permissions = this.obj; // DB permissions[0].name.should.eql('Export database'); @@ -213,7 +213,7 @@ describe('Database Migration (special functions)', function () { beforeEach(testUtils.setup('default')); it('should populate all fixtures correctly', function () { - var props = { + const props = { posts: Models.Post.findAll({withRelated: ['tags']}), tags: Models.Tag.findAll(), users: Models.User.findAll({ diff --git a/test/regression/models/base/listeners_spec.js b/test/regression/models/base/listeners_spec.js index 51ba7cae56..e72a058ee6 100644 --- a/test/regression/models/base/listeners_spec.js +++ b/test/regression/models/base/listeners_spec.js @@ -1,24 +1,25 @@ -var should = require('should'), - sinon = require('sinon'), - Promise = require('bluebird'), - moment = require('moment-timezone'), - rewire = require('rewire'), - _ = require('lodash'), - common = require('../../../../core/server/lib/common'), - models = require('../../../../core/server/models'), - testUtils = require('../../../utils'), - sequence = require('../../../../core/server/lib/promise/sequence'); +const should = require('should'); +const sinon = require('sinon'); +const Promise = require('bluebird'); +const moment = require('moment-timezone'); +const rewire = require('rewire'); +const _ = require('lodash'); +const common = require('../../../../core/server/lib/common'); +const models = require('../../../../core/server/models'); +const testUtils = require('../../../utils'); +const sequence = require('../../../../core/server/lib/promise/sequence'); describe('Models: listeners', function () { - var eventsToRemember = {}, - now = moment(), - listeners, - scope = { - posts: [], - publishedAtFutureMoment1: moment().add(2, 'days').startOf('hour'), - publishedAtFutureMoment2: moment().add(2, 'hours').startOf('hour'), - publishedAtFutureMoment3: moment().add(10, 'hours').startOf('hour') - }; + const eventsToRemember = {}; + const now = moment(); + let listeners; + + const scope = { + posts: [], + publishedAtFutureMoment1: moment().add(2, 'days').startOf('hour'), + publishedAtFutureMoment2: moment().add(2, 'hours').startOf('hour'), + publishedAtFutureMoment3: moment().add(10, 'hours').startOf('hour') + }; before(testUtils.teardownDb); @@ -40,7 +41,7 @@ describe('Models: listeners', function () { }); describe('on timezone changed', function () { - var posts; + let posts; describe('db has scheduled posts', function () { beforeEach(function (done) { @@ -77,7 +78,7 @@ describe('Models: listeners', function () { }); it('active_timezone changes from London to Los Angeles', function (done) { - var timeout; + let timeout; /** * From London +1 @@ -108,23 +109,25 @@ describe('Models: listeners', function () { (function retry() { models.Post.findAll({context: {internal: true}}) .then(function (results) { - var post1 = _.find(results.models, function (post) { - return post.get('title') === '1'; - }), - post2 = _.find(results.models, function (post) { - return post.get('title') === '2'; - }), - post3 = _.find(results.models, function (post) { - return post.get('title') === '3'; - }); + const post1 = _.find(results.models, function (post) { + return post.get('title') === '1'; + }); + + const post2 = _.find(results.models, function (post) { + return post.get('title') === '2'; + }); + + const post3 = _.find(results.models, function (post) { + return post.get('title') === '3'; + }); if (results.models.length === posts.length && - post1.get('status') === 'scheduled' && - post2.get('status') === 'scheduled' && - post3.get('status') === 'scheduled' && - moment(post1.get('published_at')).diff(scope.publishedAtFutureMoment1.clone().add(scope.timezoneOffset, 'minutes')) === 0 && - moment(post2.get('published_at')).diff(scope.publishedAtFutureMoment2.clone().add(scope.timezoneOffset, 'minutes')) === 0 && - moment(post3.get('published_at')).diff(scope.publishedAtFutureMoment3.clone().add(scope.timezoneOffset, 'minutes')) === 0) { + post1.get('status') === 'scheduled' && + post2.get('status') === 'scheduled' && + post3.get('status') === 'scheduled' && + moment(post1.get('published_at')).diff(scope.publishedAtFutureMoment1.clone().add(scope.timezoneOffset, 'minutes')) === 0 && + moment(post2.get('published_at')).diff(scope.publishedAtFutureMoment2.clone().add(scope.timezoneOffset, 'minutes')) === 0 && + moment(post3.get('published_at')).diff(scope.publishedAtFutureMoment3.clone().add(scope.timezoneOffset, 'minutes')) === 0) { return done(); } @@ -136,7 +139,7 @@ describe('Models: listeners', function () { }); it('active_timezone changes from Baghdad to UTC', function (done) { - var timeout; + let timeout; /** * From Baghdad +3 @@ -165,23 +168,25 @@ describe('Models: listeners', function () { (function retry() { models.Post.findAll({context: {internal: true}}) .then(function (results) { - var post1 = _.find(results.models, function (post) { - return post.get('title') === '1'; - }), - post2 = _.find(results.models, function (post) { - return post.get('title') === '2'; - }), - post3 = _.find(results.models, function (post) { - return post.get('title') === '3'; - }); + const post1 = _.find(results.models, function (post) { + return post.get('title') === '1'; + }); + + const post2 = _.find(results.models, function (post) { + return post.get('title') === '2'; + }); + + const post3 = _.find(results.models, function (post) { + return post.get('title') === '3'; + }); if (results.models.length === posts.length && - post1.get('status') === 'scheduled' && - post2.get('status') === 'scheduled' && - post3.get('status') === 'scheduled' && - moment(post1.get('published_at')).diff(scope.publishedAtFutureMoment1.clone().add(scope.timezoneOffset, 'minutes')) === 0 && - moment(post2.get('published_at')).diff(scope.publishedAtFutureMoment2.clone().add(scope.timezoneOffset, 'minutes')) === 0 && - moment(post3.get('published_at')).diff(scope.publishedAtFutureMoment3.clone().add(scope.timezoneOffset, 'minutes')) === 0) { + post1.get('status') === 'scheduled' && + post2.get('status') === 'scheduled' && + post3.get('status') === 'scheduled' && + moment(post1.get('published_at')).diff(scope.publishedAtFutureMoment1.clone().add(scope.timezoneOffset, 'minutes')) === 0 && + moment(post2.get('published_at')).diff(scope.publishedAtFutureMoment2.clone().add(scope.timezoneOffset, 'minutes')) === 0 && + moment(post3.get('published_at')).diff(scope.publishedAtFutureMoment3.clone().add(scope.timezoneOffset, 'minutes')) === 0) { return done(); } @@ -193,7 +198,7 @@ describe('Models: listeners', function () { }); it('active_timezone changes from Amsterdam to Seoul', function (done) { - var timeout; + let timeout; /** * From Amsterdam +2 @@ -222,22 +227,24 @@ describe('Models: listeners', function () { (function retry() { models.Post.findAll({context: {internal: true}}) .then(function (results) { - var post1 = _.find(results.models, function (post) { - return post.get('title') === '1'; - }), - post2 = _.find(results.models, function (post) { - return post.get('title') === '2'; - }), - post3 = _.find(results.models, function (post) { - return post.get('title') === '3'; - }); + const post1 = _.find(results.models, function (post) { + return post.get('title') === '1'; + }); + + const post2 = _.find(results.models, function (post) { + return post.get('title') === '2'; + }); + + const post3 = _.find(results.models, function (post) { + return post.get('title') === '3'; + }); if (results.models.length === posts.length && - post1.get('status') === 'scheduled' && - post2.get('status') === 'draft' && - post3.get('status') === 'scheduled' && - moment(post1.get('published_at')).diff(scope.publishedAtFutureMoment1.clone().add(scope.timezoneOffset, 'minutes')) === 0 && - moment(post3.get('published_at')).diff(scope.publishedAtFutureMoment3.clone().add(scope.timezoneOffset, 'minutes')) === 0) { + post1.get('status') === 'scheduled' && + post2.get('status') === 'draft' && + post3.get('status') === 'scheduled' && + moment(post1.get('published_at')).diff(scope.publishedAtFutureMoment1.clone().add(scope.timezoneOffset, 'minutes')) === 0 && + moment(post3.get('published_at')).diff(scope.publishedAtFutureMoment3.clone().add(scope.timezoneOffset, 'minutes')) === 0) { return done(); } @@ -268,7 +275,7 @@ describe('Models: listeners', function () { describe('on notifications changed', function () { it('nothing to delete', function (done) { - var notifications = JSON.stringify([ + const notifications = JSON.stringify([ { addedAt: moment().subtract(1, 'week').format(), seen: true @@ -299,7 +306,7 @@ describe('Models: listeners', function () { }); it('expect deletion', function (done) { - var notifications = JSON.stringify([ + const notifications = JSON.stringify([ { content: 'keep-1', addedAt: moment().subtract(1, 'week').toDate(), diff --git a/test/regression/models/model_posts_spec.js b/test/regression/models/model_posts_spec.js index 022ff230b4..ac55edadc9 100644 --- a/test/regression/models/model_posts_spec.js +++ b/test/regression/models/model_posts_spec.js @@ -1,19 +1,19 @@ -var should = require('should'), - sinon = require('sinon'), - testUtils = require('../../utils'), - moment = require('moment'), - _ = require('lodash'), - Promise = require('bluebird'), - sequence = require('../../../core/server/lib/promise/sequence'), - urlService = require('../../../core/frontend/services/url'), - ghostBookshelf = require('../../../core/server/models/base'), - models = require('../../../core/server/models'), - settingsCache = require('../../../core/server/services/settings/cache'), - common = require('../../../core/server/lib/common'), - configUtils = require('../../utils/configUtils'), - DataGenerator = testUtils.DataGenerator, - context = testUtils.context.owner, - markdownToMobiledoc = testUtils.DataGenerator.markdownToMobiledoc; +const should = require('should'); +const sinon = require('sinon'); +const testUtils = require('../../utils'); +const moment = require('moment'); +const _ = require('lodash'); +const Promise = require('bluebird'); +const sequence = require('../../../core/server/lib/promise/sequence'); +const urlService = require('../../../core/frontend/services/url'); +const ghostBookshelf = require('../../../core/server/models/base'); +const models = require('../../../core/server/models'); +const settingsCache = require('../../../core/server/services/settings/cache'); +const common = require('../../../core/server/lib/common'); +const configUtils = require('../../utils/configUtils'); +const DataGenerator = testUtils.DataGenerator; +const context = testUtils.context.owner; +const markdownToMobiledoc = testUtils.DataGenerator.markdownToMobiledoc; /** * IMPORTANT: @@ -23,7 +23,7 @@ var should = require('should'), * - rewire would add 1 registry, a file who requires the models, tries to register the model another time */ describe('Post Model', function () { - var eventsTriggered = {}; + let eventsTriggered = {}; before(testUtils.teardownDb); before(testUtils.stopGhost); @@ -195,10 +195,11 @@ describe('Post Model', function () { }); it('[failure] multiple edits in one transaction', function () { - const options = _.cloneDeep(context), - data = { - status: 'published' - }; + const options = _.cloneDeep(context); + + const data = { + status: 'published' + }; return models.Base.transaction(function (txn) { options.transacting = txn; @@ -218,10 +219,11 @@ describe('Post Model', function () { }); it('multiple edits in one transaction', function () { - const options = _.cloneDeep(context), - data = { - status: 'published' - }; + const options = _.cloneDeep(context); + + const data = { + status: 'published' + }; return models.Base.transaction(function (txn) { options.transacting = txn; @@ -237,10 +239,10 @@ describe('Post Model', function () { }); it('can change title', function (done) { - var postId = testUtils.DataGenerator.Content.posts[0].id; + const postId = testUtils.DataGenerator.Content.posts[0].id; models.Post.findOne({id: postId}).then(function (results) { - var post; + let post; should.exist(results); post = results.toJSON(); post.id.should.equal(postId); @@ -260,10 +262,10 @@ describe('Post Model', function () { }); it('[failure] custom excerpt soft limit reached', function (done) { - var postId = testUtils.DataGenerator.Content.posts[0].id; + const postId = testUtils.DataGenerator.Content.posts[0].id; models.Post.findOne({id: postId}).then(function (results) { - var post; + let post; should.exist(results); post = results.toJSON(); post.id.should.equal(postId); @@ -280,10 +282,10 @@ describe('Post Model', function () { }); it('can publish draft post', function (done) { - var postId = testUtils.DataGenerator.Content.posts[3].id; + const postId = testUtils.DataGenerator.Content.posts[3].id; models.Post.findOne({id: postId, status: 'draft'}).then(function (results) { - var post; + let post; should.exist(results); post = results.toJSON(); post.id.should.equal(postId); @@ -305,10 +307,10 @@ describe('Post Model', function () { }); it('can unpublish published post', function (done) { - var postId = testUtils.DataGenerator.Content.posts[0].id; + const postId = testUtils.DataGenerator.Content.posts[0].id; models.Post.findOne({id: postId}).then(function (results) { - var post; + let post; should.exist(results); post = results.toJSON(); post.id.should.equal(postId); @@ -328,7 +330,7 @@ describe('Post Model', function () { }); it('draft -> scheduled without published_at update', function (done) { - var post; + let post; models.Post.findOne({status: 'draft'}).then(function (results) { should.exist(results); @@ -351,10 +353,10 @@ describe('Post Model', function () { }); it('draft -> scheduled: expect update of published_at', function (done) { - var newPublishedAt = moment().add(1, 'day').toDate(); + const newPublishedAt = moment().add(1, 'day').toDate(); models.Post.findOne({status: 'draft'}).then(function (results) { - var post; + let post; should.exist(results); post = results.toJSON(); @@ -381,7 +383,7 @@ describe('Post Model', function () { it('scheduled -> draft: expect unschedule', function (done) { models.Post.findOne({status: 'scheduled'}).then(function (results) { - var post; + let post; should.exist(results); post = results.toJSON(); @@ -404,7 +406,7 @@ describe('Post Model', function () { it('scheduled -> scheduled with updated published_at', function (done) { models.Post.findOne({status: 'scheduled'}).then(function (results) { - var post; + let post; should.exist(results); post = results.toJSON(); @@ -428,7 +430,7 @@ describe('Post Model', function () { it('scheduled -> scheduled with unchanged published_at', function (done) { models.Post.findOne({status: 'scheduled'}).then(function (results) { - var post; + let post; should.exist(results); post = results.toJSON(); @@ -449,7 +451,7 @@ describe('Post Model', function () { }); it('scheduled -> scheduled with unchanged published_at (within the 2 minutes window)', function (done) { - var post; + let post; models.Post.findOne({status: 'scheduled'}).then(function (results) { should.exist(results); @@ -481,10 +483,10 @@ describe('Post Model', function () { }); it('published -> scheduled and expect update of published_at', function (done) { - var postId = testUtils.DataGenerator.Content.posts[0].id; + const postId = testUtils.DataGenerator.Content.posts[0].id; models.Post.findOne({id: postId}).then(function (results) { - var post; + let post; should.exist(results); post = results.toJSON(); post.id.should.equal(postId); @@ -504,10 +506,10 @@ describe('Post Model', function () { }); it('can convert draft post to page and back', function (done) { - var postId = testUtils.DataGenerator.Content.posts[3].id; + const postId = testUtils.DataGenerator.Content.posts[3].id; models.Post.findOne({id: postId, status: 'draft'}).then(function (results) { - var post; + let post; should.exist(results); post = results.toJSON(); post.id.should.equal(postId); @@ -541,7 +543,7 @@ describe('Post Model', function () { it('can convert draft to schedule AND post to page and back', function (done) { models.Post.findOne({status: 'draft'}).then(function (results) { - var post; + let post; should.exist(results); post = results.toJSON(); post.status.should.equal('draft'); @@ -578,10 +580,10 @@ describe('Post Model', function () { }); it('can convert published post to page and back', function (done) { - var postId = testUtils.DataGenerator.Content.posts[0].id; + const postId = testUtils.DataGenerator.Content.posts[0].id; models.Post.findOne({id: postId}).then(function (results) { - var post; + let post; should.exist(results); post = results.toJSON(); post.id.should.equal(postId); @@ -616,10 +618,10 @@ describe('Post Model', function () { }); it('can change type and status at the same time', function (done) { - var postId = testUtils.DataGenerator.Content.posts[3].id; + const postId = testUtils.DataGenerator.Content.posts[3].id; models.Post.findOne({id: postId, status: 'draft'}).then(function (results) { - var post; + let post; should.exist(results); post = results.toJSON(); post.id.should.equal(postId); @@ -654,10 +656,10 @@ describe('Post Model', function () { }); it('cannot override the published_by setting', function (done) { - var postId = testUtils.DataGenerator.Content.posts[3].id; + const postId = testUtils.DataGenerator.Content.posts[3].id; models.Post.findOne({id: postId, status: 'draft'}).then(function (results) { - var post; + let post; should.exist(results); post = results.toJSON(); post.id.should.equal(postId); @@ -711,9 +713,9 @@ describe('Post Model', function () { }); it('can add, defaults are all correct', function (done) { - var createdPostUpdatedDate, - newPost = testUtils.DataGenerator.forModel.posts[2], - newPostDB = testUtils.DataGenerator.Content.posts[2]; + let createdPostUpdatedDate; + const newPost = testUtils.DataGenerator.forModel.posts[2]; + const newPostDB = testUtils.DataGenerator.Content.posts[2]; models.Post.add(newPost, _.merge({withRelated: ['author']}, context)).then(function (createdPost) { return models.Post.findOne({id: createdPost.id, status: 'all'}); @@ -771,7 +773,7 @@ describe('Post Model', function () { }); it('can add, default visibility is taken from settings cache', function (done) { - var originalSettingsCacheGetFn = settingsCache.get; + const originalSettingsCacheGetFn = settingsCache.get; sinon.stub(settingsCache, 'get') .callsFake(function (key, options) { if (key === 'labs') { @@ -785,9 +787,9 @@ describe('Post Model', function () { return originalSettingsCacheGetFn(key, options); }); - var createdPostUpdatedDate, - newPost = testUtils.DataGenerator.forModel.posts[2], - newPostDB = testUtils.DataGenerator.Content.posts[2]; + let createdPostUpdatedDate; + const newPost = testUtils.DataGenerator.forModel.posts[2]; + const newPostDB = testUtils.DataGenerator.Content.posts[2]; models.Post.add(newPost, _.merge({withRelated: ['author']}, context)).then(function (createdPost) { return models.Post.findOne({id: createdPost.id, status: 'all'}); @@ -845,7 +847,7 @@ describe('Post Model', function () { }); it('can add, with previous published_at date', function (done) { - var previousPublishedAtDate = new Date(2013, 8, 21, 12); + const previousPublishedAtDate = new Date(2013, 8, 21, 12); models.Post.add({ status: 'published', @@ -991,7 +993,7 @@ describe('Post Model', function () { // Should have unique slugs and contents _(createdPosts).each(function (post, i) { - var num = i + 1; + const num = i + 1; // First one has normal title if (num === 1) { @@ -1013,7 +1015,7 @@ describe('Post Model', function () { }); it('can generate slugs without duplicate hyphens', function (done) { - var newPost = { + const newPost = { title: 'apprehensive titles have too many spaces—and m-dashes — – and also n-dashes ', mobiledoc: markdownToMobiledoc('Test Content 1') }; @@ -1030,7 +1032,7 @@ describe('Post Model', function () { }); it('can generate a safe slug when a protected keyword is used', function (done) { - var newPost = { + const newPost = { title: 'rss', mobiledoc: markdownToMobiledoc('Test Content 1') }; @@ -1047,7 +1049,7 @@ describe('Post Model', function () { }); it('can generate slugs without non-ascii characters', function (done) { - var newPost = { + const newPost = { title: 'भुते धडकी भरवणारा आहेत', mobiledoc: markdownToMobiledoc('Test Content 1') }; @@ -1059,14 +1061,15 @@ describe('Post Model', function () { }); it('detects duplicate slugs before saving', function (done) { - var firstPost = { - title: 'First post', - mobiledoc: markdownToMobiledoc('First content 1') - }, - secondPost = { - title: 'Second post', - mobiledoc: markdownToMobiledoc('Second content 1') - }; + const firstPost = { + title: 'First post', + mobiledoc: markdownToMobiledoc('First content 1') + }; + + const secondPost = { + title: 'Second post', + mobiledoc: markdownToMobiledoc('Second content 1') + }; // Create the first post models.Post.add(firstPost, context) @@ -1185,11 +1188,11 @@ describe('Post Model', function () { it('published post', function (done) { // We're going to try deleting post id 1 which has tag id 1 - var firstItemData = {id: testUtils.DataGenerator.Content.posts[0].id}; + const firstItemData = {id: testUtils.DataGenerator.Content.posts[0].id}; // Test that we have the post we expect, with exactly one tag models.Post.findOne(firstItemData, {withRelated: ['tags']}).then(function (results) { - var post; + let post; should.exist(results); post = results.toJSON(); post.id.should.equal(firstItemData.id); @@ -1200,7 +1203,7 @@ describe('Post Model', function () { // Destroy the post return results.destroy(); }).then(function (response) { - var deleted = response.toJSON(); + const deleted = response.toJSON(); should.equal(deleted.author, undefined); @@ -1227,11 +1230,11 @@ describe('Post Model', function () { it('draft post', function (done) { // We're going to try deleting post 4 which also has tag 4 - var firstItemData = {id: testUtils.DataGenerator.Content.posts[3].id, status: 'draft'}; + const firstItemData = {id: testUtils.DataGenerator.Content.posts[3].id, status: 'draft'}; // Test that we have the post we expect, with exactly one tag models.Post.findOne(firstItemData, {withRelated: ['tags']}).then(function (results) { - var post; + let post; should.exist(results); post = results.toJSON(); post.id.should.equal(firstItemData.id); @@ -1241,7 +1244,7 @@ describe('Post Model', function () { // Destroy the post return results.destroy(firstItemData); }).then(function (response) { - var deleted = response.toJSON(); + const deleted = response.toJSON(); should.equal(deleted.author, undefined); @@ -1267,11 +1270,11 @@ describe('Post Model', function () { it('published page', function (done) { // We're going to try deleting page 6 which has tag 1 - var firstItemData = {id: testUtils.DataGenerator.Content.posts[5].id}; + const firstItemData = {id: testUtils.DataGenerator.Content.posts[5].id}; // Test that we have the post we expect, with exactly one tag models.Post.findOne(firstItemData, {withRelated: ['tags']}).then(function (results) { - var page; + let page; should.exist(results); page = results.toJSON(); page.id.should.equal(firstItemData.id); @@ -1281,7 +1284,7 @@ describe('Post Model', function () { // Destroy the page return results.destroy(firstItemData); }).then(function (response) { - var deleted = response.toJSON(); + const deleted = response.toJSON(); should.equal(deleted.author, undefined); @@ -1306,11 +1309,11 @@ describe('Post Model', function () { it('draft page', function (done) { // We're going to try deleting post 7 which has tag 4 - var firstItemData = {id: testUtils.DataGenerator.Content.posts[6].id, status: 'draft'}; + const firstItemData = {id: testUtils.DataGenerator.Content.posts[6].id, status: 'draft'}; // Test that we have the post we expect, with exactly one tag models.Post.findOne(firstItemData, {withRelated: ['tags']}).then(function (results) { - var page; + let page; should.exist(results); page = results.toJSON(); page.id.should.equal(firstItemData.id); @@ -1318,7 +1321,7 @@ describe('Post Model', function () { // Destroy the page return results.destroy(firstItemData); }).then(function (response) { - var deleted = response.toJSON(); + const deleted = response.toJSON(); should.equal(deleted.author, undefined); @@ -1355,7 +1358,7 @@ describe('Post Model', function () { }); it('update post title, but updated_at is out of sync', function () { - var postToUpdate = {id: testUtils.DataGenerator.Content.posts[1].id}; + const postToUpdate = {id: testUtils.DataGenerator.Content.posts[1].id}; return models.Post.edit({ title: 'New Post Title', @@ -1370,7 +1373,7 @@ describe('Post Model', function () { }); it('update post tags and updated_at is out of sync', function () { - var postToUpdate = {id: testUtils.DataGenerator.Content.posts[1].id}; + const postToUpdate = {id: testUtils.DataGenerator.Content.posts[1].id}; return models.Post.edit({ tags: [{name: 'new-tag-1'}], @@ -1385,7 +1388,7 @@ describe('Post Model', function () { }); it('update post authors and updated_at is out of sync', function () { - var postToUpdate = {id: testUtils.DataGenerator.Content.posts[1].id}; + const postToUpdate = {id: testUtils.DataGenerator.Content.posts[1].id}; return models.Post.edit({ authors: [testUtils.DataGenerator.Content.users[3]], @@ -1400,7 +1403,7 @@ describe('Post Model', function () { }); it('update post tags and updated_at is NOT out of sync', function () { - var postToUpdate = {id: testUtils.DataGenerator.Content.posts[1].id}; + const postToUpdate = {id: testUtils.DataGenerator.Content.posts[1].id}; return models.Post.edit({ tags: [{name: 'new-tag-1'}] @@ -1408,7 +1411,7 @@ describe('Post Model', function () { }); it('update post with no changes, but updated_at is out of sync', function () { - var postToUpdate = {id: testUtils.DataGenerator.Content.posts[1].id}; + const postToUpdate = {id: testUtils.DataGenerator.Content.posts[1].id}; return models.Post.edit({ updated_at: moment().subtract(1, 'day').format() @@ -1416,7 +1419,7 @@ describe('Post Model', function () { }); it('update post with old post title, but updated_at is out of sync', function () { - var postToUpdate = { + const postToUpdate = { id: testUtils.DataGenerator.Content.posts[1].id, title: testUtils.DataGenerator.forModel.posts[1].title }; @@ -1556,7 +1559,7 @@ describe('Post Model', function () { it('can destroy multiple posts by author', function (done) { // We're going to delete all posts by user 1 - var authorData = {id: testUtils.DataGenerator.Content.users[0].id}; + const authorData = {id: testUtils.DataGenerator.Content.users[0].id}; models.Post.findAll({context: {internal: true}}).then(function (found) { // There are 10 posts created by posts:mu fixture @@ -1577,10 +1580,10 @@ describe('Post Model', function () { }); describe('Post tag handling edge cases', function () { - var postJSON, - tagJSON, - editOptions, - createTag = testUtils.DataGenerator.forKnex.createTag; + let postJSON; + let tagJSON; + let editOptions; + const createTag = testUtils.DataGenerator.forKnex.createTag; beforeEach(function () { return testUtils.truncate('posts_tags') @@ -1595,17 +1598,19 @@ describe('Post Model', function () { beforeEach(function () { tagJSON = []; - var post = _.cloneDeep(testUtils.DataGenerator.forModel.posts[0]), - postTags = [ - createTag({name: 'tag1', slug: 'tag1'}), - createTag({name: 'tag2', slug: 'tag2'}), - createTag({name: 'tag3', slug: 'tag3'}) - ], - extraTags = [ - createTag({name: 'existing tag a', slug: 'existing-tag-a'}), - createTag({name: 'existing-tag-b', slug: 'existing-tag-b'}), - createTag({name: 'existing_tag_c', slug: 'existing_tag_c'}) - ]; + const post = _.cloneDeep(testUtils.DataGenerator.forModel.posts[0]); + + const postTags = [ + createTag({name: 'tag1', slug: 'tag1'}), + createTag({name: 'tag2', slug: 'tag2'}), + createTag({name: 'tag3', slug: 'tag3'}) + ]; + + const extraTags = [ + createTag({name: 'existing tag a', slug: 'existing-tag-a'}), + createTag({name: 'existing-tag-b', slug: 'existing-tag-b'}), + createTag({name: 'existing_tag_c', slug: 'existing_tag_c'}) + ]; post.tags = postTags; post.status = 'published'; @@ -1650,7 +1655,7 @@ describe('Post Model', function () { }); it('can edit slug of existing tag', function () { - var newJSON = _.cloneDeep(postJSON); + const newJSON = _.cloneDeep(postJSON); // Add an existing tag to the beginning of the array newJSON.tags = [{id: postJSON.tags[0].id, slug: 'eins'}]; @@ -1667,7 +1672,9 @@ describe('Post Model', function () { }); it('can\'t edit dates and authors of existing tag', function () { - var newJSON = _.cloneDeep(postJSON), updatedAtFormat, createdAtFormat; + const newJSON = _.cloneDeep(postJSON); + let updatedAtFormat; + let createdAtFormat; // Add an existing tag to the beginning of the array newJSON.tags = [_.cloneDeep(postJSON.tags[0])]; @@ -1706,8 +1713,8 @@ describe('Post Model', function () { }); it('can reorder existing, added and deleted tags', function () { - var newJSON = _.cloneDeep(postJSON), - lastTag = [postJSON.tags[2]]; + const newJSON = _.cloneDeep(postJSON); + const lastTag = [postJSON.tags[2]]; // remove tag in the middle (tag1, tag2, tag3 -> tag1, tag3) newJSON.tags.splice(1, 1); @@ -1737,7 +1744,7 @@ describe('Post Model', function () { }); it('can add multiple tags with conflicting slugs', function () { - var newJSON = _.cloneDeep(postJSON); + const newJSON = _.cloneDeep(postJSON); // Add conflicting tags to the end of the array newJSON.tags = []; @@ -1758,7 +1765,7 @@ describe('Post Model', function () { }); it('can handle lowercase/uppercase tags', function () { - var newJSON = _.cloneDeep(postJSON); + const newJSON = _.cloneDeep(postJSON); // Add conflicting tags to the end of the array newJSON.tags = []; diff --git a/test/regression/models/model_users_spec.js b/test/regression/models/model_users_spec.js index 722e385ced..3b31d6a3cd 100644 --- a/test/regression/models/model_users_spec.js +++ b/test/regression/models/model_users_spec.js @@ -1,18 +1,19 @@ -var should = require('should'), - sinon = require('sinon'), - testUtils = require('../../utils'), - Promise = require('bluebird'), - _ = require('lodash'), +const should = require('should'); +const sinon = require('sinon'); +const testUtils = require('../../utils'); +const Promise = require('bluebird'); +const _ = require('lodash'); - // Stuff we are testing - common = require('../../../core/server/lib/common'), - imageLib = require('../../../core/server/lib/image'), - UserModel = require('../../../core/server/models/user').User, - RoleModel = require('../../../core/server/models/role').Role, - context = testUtils.context.admin; +// Stuff we are testing +const common = require('../../../core/server/lib/common'); + +const imageLib = require('../../../core/server/lib/image'); +const UserModel = require('../../../core/server/models/user').User; +const RoleModel = require('../../../core/server/models/role').Role; +const context = testUtils.context.admin; describe('User Model', function run() { - var eventsTriggered = {}; + let eventsTriggered = {}; before(testUtils.teardownDb); afterEach(testUtils.teardownDb); @@ -28,7 +29,7 @@ describe('User Model', function run() { beforeEach(testUtils.setup('roles')); it('can add first', function (done) { - var userData = testUtils.DataGenerator.forModel.users[0]; + const userData = testUtils.DataGenerator.forModel.users[0]; UserModel.add(userData, context).then(function (createdUser) { should.exist(createdUser); @@ -40,7 +41,7 @@ describe('User Model', function run() { }); it('shortens slug if possible', function (done) { - var userData = testUtils.DataGenerator.forModel.users[2]; + const userData = testUtils.DataGenerator.forModel.users[2]; UserModel.add(userData, context).then(function (createdUser) { should.exist(createdUser); @@ -51,7 +52,7 @@ describe('User Model', function run() { }); it('does not short slug if not possible', function (done) { - var userData = testUtils.DataGenerator.forModel.users[2]; + const userData = testUtils.DataGenerator.forModel.users[2]; UserModel.add(userData, context).then(function (createdUser) { should.exist(createdUser); @@ -76,7 +77,7 @@ describe('User Model', function run() { }); it('does NOT lowercase email', function (done) { - var userData = testUtils.DataGenerator.forModel.users[2]; + const userData = testUtils.DataGenerator.forModel.users[2]; UserModel.add(userData, context).then(function (createdUser) { should.exist(createdUser); @@ -86,7 +87,7 @@ describe('User Model', function run() { }); it('can find gravatar', function (done) { - var userData = testUtils.DataGenerator.forModel.users[4]; + const userData = testUtils.DataGenerator.forModel.users[4]; sinon.stub(imageLib.gravatar, 'lookup').callsFake(function (userData) { userData.image = 'http://www.gravatar.com/avatar/2fab21a4c4ed88e76add10650c73bae1?d=404'; @@ -103,7 +104,7 @@ describe('User Model', function run() { }); it('can handle no gravatar', function (done) { - var userData = testUtils.DataGenerator.forModel.users[0]; + const userData = testUtils.DataGenerator.forModel.users[0]; sinon.stub(imageLib.gravatar, 'lookup').callsFake(function (userData) { return Promise.resolve(userData); @@ -117,8 +118,8 @@ describe('User Model', function run() { }); it('can find by email and is case insensitive', function (done) { - var userData = testUtils.DataGenerator.forModel.users[2], - email = testUtils.DataGenerator.forModel.users[2].email; + const userData = testUtils.DataGenerator.forModel.users[2]; + const email = testUtils.DataGenerator.forModel.users[2].email; UserModel.add(userData, context).then(function () { // Test same case @@ -165,7 +166,7 @@ describe('User Model', function run() { }); it('sets last login time on successful login', function (done) { - var userData = testUtils.DataGenerator.forModel.users[0]; + const userData = testUtils.DataGenerator.forModel.users[0]; UserModel.check({email: userData.email, password: userData.password}).then(function (activeUser) { should.exist(activeUser.get('last_seen')); @@ -174,14 +175,14 @@ describe('User Model', function run() { }); it('converts fetched dateTime fields to Date objects', function (done) { - var userData = testUtils.DataGenerator.forModel.users[0]; + const userData = testUtils.DataGenerator.forModel.users[0]; UserModel.check({email: userData.email, password: userData.password}).then(function (user) { return UserModel.findOne({id: user.id}); }).then(function (user) { - var lastLogin, - createdAt, - updatedAt; + let lastLogin; + let createdAt; + let updatedAt; should.exist(user); @@ -212,8 +213,8 @@ describe('User Model', function run() { return testUtils.fixtures.createExtraUsers().then(function () { return Promise.join(UserModel.findOne({role: 'Owner'}), UserModel.findOne({role: 'Editor'})); }).then(function (results) { - var owner = results[0], - editor = results[1]; + let owner = results[0]; + let editor = results[1]; should.exist(owner); should.exist(editor); @@ -230,7 +231,7 @@ describe('User Model', function run() { }); it('can invite user', function (done) { - var userData = testUtils.DataGenerator.forModel.users[4]; + const userData = testUtils.DataGenerator.forModel.users[4]; UserModel.add(_.extend({}, userData, {status: 'invited'}), context).then(function (createdUser) { should.exist(createdUser); @@ -245,7 +246,7 @@ describe('User Model', function run() { }); it('can add active user', function (done) { - var userData = testUtils.DataGenerator.forModel.users[4]; + const userData = testUtils.DataGenerator.forModel.users[4]; RoleModel.findOne().then(function (role) { userData.roles = [role.toJSON()]; @@ -266,7 +267,7 @@ describe('User Model', function run() { }); it('can NOT add active user with invalid email address', function (done) { - var userData = _.clone(testUtils.DataGenerator.forModel.users[4]); + const userData = _.clone(testUtils.DataGenerator.forModel.users[4]); userData.email = 'invalidemailaddress'; @@ -282,10 +283,10 @@ describe('User Model', function run() { }); it('can edit active user', function (done) { - var firstUser = testUtils.DataGenerator.Content.users[0].id; + const firstUser = testUtils.DataGenerator.Content.users[0].id; UserModel.findOne({id: firstUser}).then(function (results) { - var user; + let user; should.exist(results); user = results.toJSON(); user.id.should.equal(firstUser); @@ -305,7 +306,7 @@ describe('User Model', function run() { }); it('can NOT set an invalid email address', function (done) { - var firstUser = testUtils.DataGenerator.Content.users[0].id; + const firstUser = testUtils.DataGenerator.Content.users[0].id; UserModel.findOne({id: firstUser}).then(function (user) { return user.edit({email: 'notanemailaddress'}); @@ -317,8 +318,8 @@ describe('User Model', function run() { }); it('can NOT set an already existing email address', function (done) { - var firstUser = testUtils.DataGenerator.Content.users[0], - secondUser = testUtils.DataGenerator.Content.users[1]; + const firstUser = testUtils.DataGenerator.Content.users[0]; + const secondUser = testUtils.DataGenerator.Content.users[1]; UserModel.edit({email: secondUser.email}, {id: firstUser.id}) .then(function () { @@ -331,8 +332,8 @@ describe('User Model', function run() { }); it('can edit invited user', function (done) { - var userData = testUtils.DataGenerator.forModel.users[4], - userId; + const userData = testUtils.DataGenerator.forModel.users[4]; + let userId; UserModel.add(_.extend({}, userData, {status: 'invited'}), context).then(function (createdUser) { should.exist(createdUser); @@ -357,8 +358,8 @@ describe('User Model', function run() { }); it('can activate invited user', function (done) { - var userData = testUtils.DataGenerator.forModel.users[4], - userId; + const userData = testUtils.DataGenerator.forModel.users[4]; + let userId; UserModel.add(_.extend({}, userData, {status: 'invited'}), context).then(function (createdUser) { should.exist(createdUser); @@ -384,8 +385,8 @@ describe('User Model', function run() { }); it('can destroy invited user', function (done) { - var userData = testUtils.DataGenerator.forModel.users[4], - userId; + const userData = testUtils.DataGenerator.forModel.users[4]; + let userId; UserModel.add(_.extend({}, userData, {status: 'invited'}), context).then(function (createdUser) { should.exist(createdUser); @@ -538,7 +539,7 @@ describe('User Model', function run() { beforeEach(testUtils.setup('owner')); it('setup user', function (done) { - var userData = { + const userData = { name: 'Max Mustermann', email: 'test@ghost.org', password: 'thisissupersafe' diff --git a/test/regression/site/UrlService_spec.js b/test/regression/site/UrlService_spec.js index 398f27d61f..f4b9467352 100644 --- a/test/regression/site/UrlService_spec.js +++ b/test/regression/site/UrlService_spec.js @@ -29,7 +29,10 @@ describe('Integration: services/url/UrlService', function () { }); describe('functional: default routing set', function () { - let router1, router2, router3, router4; + let router1; + let router2; + let router3; + let router4; before(function (done) { urlService = new UrlService(); @@ -203,7 +206,11 @@ describe('Integration: services/url/UrlService', function () { }); describe('functional: extended/modified routing set', function () { - let router1, router2, router3, router4, router5; + let router1; + let router2; + let router3; + let router4; + let router5; before(testUtils.teardownDb); before(testUtils.setup('users:roles', 'posts')); @@ -401,7 +408,11 @@ describe('Integration: services/url/UrlService', function () { }); describe('functional: subdirectory', function () { - let router1, router2, router3, router4, router5; + let router1; + let router2; + let router3; + let router4; + let router5; beforeEach(function (done) { configUtils.set('url', 'http://localhost:2388/blog/'); diff --git a/test/regression/site/dynamic_routing_spec.js b/test/regression/site/dynamic_routing_spec.js index a463f2dde4..0d66f8eae2 100644 --- a/test/regression/site/dynamic_routing_spec.js +++ b/test/regression/site/dynamic_routing_spec.js @@ -37,7 +37,7 @@ describe('Dynamic Routing', function () { before(function () { // Default is always casper. We use the old compatible 1.4 casper theme for these tests. Available in the test content folder. - var originalSettingsCacheGetFn = settingsCache.get; + const originalSettingsCacheGetFn = settingsCache.get; sinon.stub(settingsCache, 'get').callsFake(function (key, options) { if (key === 'active_theme') { return 'casper-1.4'; @@ -68,7 +68,7 @@ describe('Dynamic Routing', function () { return done(err); } - var $ = cheerio.load(res.text); + const $ = cheerio.load(res.text); should.not.exist(res.headers['x-cache-invalidate']); should.not.exist(res.headers['X-CSRF-Token']); @@ -200,7 +200,7 @@ describe('Dynamic Routing', function () { return done(err); } - var $ = cheerio.load(res.text); + const $ = cheerio.load(res.text); should.not.exist(res.headers['x-cache-invalidate']); should.not.exist(res.headers['X-CSRF-Token']); @@ -412,19 +412,21 @@ describe('Dynamic Routing', function () { }); describe('Author', function () { - var lockedUser = { - name: 'Locked so what', - slug: 'locked-so-what', - email: 'locked@example.com', - status: 'locked' - }, - suspendedUser = { - name: 'Suspended meeh', - slug: 'suspended-meeh', - email: 'suspended@example.com', - status: 'inactive' - }, - ownerSlug = 'ghost-owner'; + const lockedUser = { + name: 'Locked so what', + slug: 'locked-so-what', + email: 'locked@example.com', + status: 'locked' + }; + + const suspendedUser = { + name: 'Suspended meeh', + slug: 'suspended-meeh', + email: 'suspended@example.com', + status: 'inactive' + }; + + const ownerSlug = 'ghost-owner'; before(function (done) { testUtils.clearData().then(function () { diff --git a/test/regression/site/frontend_spec.js b/test/regression/site/frontend_spec.js index b2587dba3c..2d8571b49c 100644 --- a/test/regression/site/frontend_spec.js +++ b/test/regression/site/frontend_spec.js @@ -2,20 +2,21 @@ // As it stands, these tests depend on the database, and as such are integration tests. // Mocking out the models to not touch the DB would turn these into unit tests, and should probably be done in future, // But then again testing real code, rather than mock code, might be more useful... -var should = require('should'), - sinon = require('sinon'), - supertest = require('supertest'), - moment = require('moment'), - cheerio = require('cheerio'), - _ = require('lodash'), - testUtils = require('../../utils'), - configUtils = require('../../utils/configUtils'), - urlUtils = require('../../utils/urlUtils'), - config = require('../../../core/server/config'), - settingsCache = require('../../../core/server/services/settings/cache'), - origCache = _.cloneDeep(settingsCache), - ghost = testUtils.startGhost, - request; +const should = require('should'); + +const sinon = require('sinon'); +const supertest = require('supertest'); +const moment = require('moment'); +const cheerio = require('cheerio'); +const _ = require('lodash'); +const testUtils = require('../../utils'); +const configUtils = require('../../utils/configUtils'); +const urlUtils = require('../../utils/urlUtils'); +const config = require('../../../core/server/config'); +const settingsCache = require('../../../core/server/services/settings/cache'); +const origCache = _.cloneDeep(settingsCache); +const ghost = testUtils.startGhost; +let request; describe('Frontend Routing', function () { function doEnd(done) { @@ -135,7 +136,7 @@ describe('Frontend Routing', function () { .expect('Cache-Control', testUtils.cacheRules.public) .expect(200) .end(function (err, res) { - var $ = cheerio.load(res.text); + const $ = cheerio.load(res.text); should.not.exist(res.headers['x-cache-invalidate']); should.not.exist(res.headers['X-CSRF-Token']); @@ -244,7 +245,7 @@ describe('Frontend Routing', function () { return done(err); } - var $ = cheerio.load(res.text); + const $ = cheerio.load(res.text); should.not.exist(res.headers['x-cache-invalidate']); should.not.exist(res.headers['X-CSRF-Token']); @@ -290,7 +291,7 @@ describe('Frontend Routing', function () { }); describe('Subdirectory (no slash)', function () { - var ghostServer; + let ghostServer; before(function () { configUtils.set('url', 'http://localhost/blog'); @@ -370,7 +371,7 @@ describe('Frontend Routing', function () { }); describe('Subdirectory (with slash)', function () { - var ghostServer; + let ghostServer; before(function () { configUtils.set('url', 'http://localhost/blog/'); @@ -458,7 +459,7 @@ describe('Frontend Routing', function () { // we'll use X-Forwarded-Proto: https to simulate an 'https://' request behind a proxy describe('HTTPS', function () { - var ghostServer; + let ghostServer; before(function () { configUtils.set('url', 'http://localhost:2370/'); @@ -496,7 +497,7 @@ describe('Frontend Routing', function () { // TODO: convert to unit tests describe('Redirects (use redirects.json from test/utils/fixtures/data)', function () { - var ghostServer; + let ghostServer; before(function () { configUtils.set('url', 'http://localhost:2370/'); diff --git a/test/regression/site/site_spec.js b/test/regression/site/site_spec.js index 083d15e9d0..a594c29f41 100644 --- a/test/regression/site/site_spec.js +++ b/test/regression/site/site_spec.js @@ -1,15 +1,15 @@ -const should = require('should'), - sinon = require('sinon'), - _ = require('lodash'), - cheerio = require('cheerio'), - testUtils = require('../../utils'), - mockUtils = require('../../utils/mocks'), - configUtils = require('../../utils/configUtils'), - urlUtils = require('../../utils/urlUtils'), - appService = require('../../../core/frontend/services/apps'), - frontendSettingsService = require('../../../core/frontend/services/settings'), - themeService = require('../../../core/frontend/services/themes'), - siteApp = require('../../../core/server/web/parent/app'); +const should = require('should'); +const sinon = require('sinon'); +const _ = require('lodash'); +const cheerio = require('cheerio'); +const testUtils = require('../../utils'); +const mockUtils = require('../../utils/mocks'); +const configUtils = require('../../utils/configUtils'); +const urlUtils = require('../../utils/urlUtils'); +const appService = require('../../../core/frontend/services/apps'); +const frontendSettingsService = require('../../../core/frontend/services/settings'); +const themeService = require('../../../core/frontend/services/themes'); +const siteApp = require('../../../core/server/web/parent/app'); describe('Integration - Web - Site', function () { let app; diff --git a/test/regression/update-check/update_check_spec.js b/test/regression/update-check/update_check_spec.js index 170c4878b5..4592f05a7e 100644 --- a/test/regression/update-check/update_check_spec.js +++ b/test/regression/update-check/update_check_spec.js @@ -27,9 +27,9 @@ describe('Update Check', function () { after(testUtils.teardownDb); describe('fn: updateCheck', function () { - var updateCheckRequestSpy, - updateCheckResponseSpy, - updateCheckErrorSpy; + let updateCheckRequestSpy; + let updateCheckResponseSpy; + let updateCheckErrorSpy; beforeEach(testUtils.teardownDb); beforeEach(testUtils.setup('roles', 'owner')); @@ -107,7 +107,7 @@ describe('Update Check', function () { }); describe('fn: updateCheckData', function () { - var environmentsOrig; + let environmentsOrig; before(function () { configUtils.set('privacy:useUpdateCheck', true); @@ -121,7 +121,7 @@ describe('Update Check', function () { beforeEach(testUtils.setup('roles', 'owner', 'settings', 'posts', 'perms:setting', 'perms:user', 'perms:init')); it('should report the correct data', function (done) { - var updateCheckData = updateCheck.__get__('updateCheckData'); + const updateCheckData = updateCheck.__get__('updateCheckData'); updateCheckData().then(function (data) { should.exist(data); @@ -144,7 +144,7 @@ describe('Update Check', function () { }); describe('fn: createCustomNotification', function () { - var currentVersionOrig; + let currentVersionOrig; before(function () { currentVersionOrig = updateCheck.__get__('ghostVersion.original'); @@ -163,18 +163,19 @@ describe('Update Check', function () { }); it('should create a release notification for target version', function (done) { - var createCustomNotification = updateCheck.__get__('createCustomNotification'), - notification = { - id: 1, - custom: 0, - messages: [{ - id: uuid.v4(), - version: '0.9.x', - content: '

    Hey there! This is for 0.9.0 version

    ', - dismissible: true, - top: true - }] - }; + const createCustomNotification = updateCheck.__get__('createCustomNotification'); + + const notification = { + id: 1, + custom: 0, + messages: [{ + id: uuid.v4(), + version: '0.9.x', + content: '

    Hey there! This is for 0.9.0 version

    ', + dismissible: true, + top: true + }] + }; NotificationsAPI.__set__('ghostVersion.full', '0.8.1'); @@ -185,7 +186,7 @@ describe('Update Check', function () { should.exist(results.notifications); results.notifications.length.should.eql(1); - var targetNotification = _.find(results.notifications, {id: notification.messages[0].id}); + const targetNotification = _.find(results.notifications, {id: notification.messages[0].id}); should.exist(targetNotification); targetNotification.dismissible.should.eql(notification.messages[0].dismissible); @@ -198,18 +199,19 @@ describe('Update Check', function () { }); it('release notification version format is wrong', function (done) { - var createCustomNotification = updateCheck.__get__('createCustomNotification'), - notification = { - id: 1, - custom: 0, - messages: [{ - id: uuid.v4(), - version: '0.9.x', - content: '

    Hey there! This is for 0.9 version

    ', - dismissible: true, - top: true - }] - }; + const createCustomNotification = updateCheck.__get__('createCustomNotification'); + + const notification = { + id: 1, + custom: 0, + messages: [{ + id: uuid.v4(), + version: '0.9.x', + content: '

    Hey there! This is for 0.9 version

    ', + dismissible: true, + top: true + }] + }; NotificationsAPI.__set__('ghostVersion.full', '0.8.1'); @@ -224,18 +226,19 @@ describe('Update Check', function () { }); it('blog version format is wrong', function (done) { - var createCustomNotification = updateCheck.__get__('createCustomNotification'), - notification = { - id: 1, - custom: 0, - messages: [{ - id: uuid.v4(), - version: '0.9.x', - content: '

    Hey there! This is for 0.9.0 version

    ', - dismissible: true, - top: true - }] - }; + const createCustomNotification = updateCheck.__get__('createCustomNotification'); + + const notification = { + id: 1, + custom: 0, + messages: [{ + id: uuid.v4(), + version: '0.9.x', + content: '

    Hey there! This is for 0.9.0 version

    ', + dismissible: true, + top: true + }] + }; NotificationsAPI.__set__('ghostVersion.full', '0.8'); @@ -250,19 +253,20 @@ describe('Update Check', function () { }); it('should create a custom notification', function (done) { - var createCustomNotification = updateCheck.__get__('createCustomNotification'), - notification = { - id: 1, - custom: 1, - messages: [{ - id: uuid.v4(), - version: 'custom1', - content: '

    How about migrating your blog?

    ', - dismissible: false, - top: true, - type: 'warn' - }] - }; + const createCustomNotification = updateCheck.__get__('createCustomNotification'); + + const notification = { + id: 1, + custom: 1, + messages: [{ + id: uuid.v4(), + version: 'custom1', + content: '

    How about migrating your blog?

    ', + dismissible: false, + top: true, + type: 'warn' + }] + }; createCustomNotification(notification).then(function () { return api.notifications.browse(testUtils.context.internal); @@ -271,7 +275,7 @@ describe('Update Check', function () { should.exist(results.notifications); results.notifications.length.should.eql(1); - var targetNotification = _.find(results.notifications, {id: notification.messages[0].id}); + const targetNotification = _.find(results.notifications, {id: notification.messages[0].id}); should.exist(targetNotification); targetNotification.dismissible.should.eql(notification.messages[0].dismissible); targetNotification.top.should.eql(notification.messages[0].top); @@ -281,19 +285,20 @@ describe('Update Check', function () { }); it('should not add duplicates', function (done) { - var createCustomNotification = updateCheck.__get__('createCustomNotification'), - notification = { - id: 1, - custom: 1, - messages: [{ - id: uuid.v4(), - version: 'custom1', - content: '

    How about migrating your blog?

    ', - dismissible: false, - top: true, - type: 'warn' - }] - }; + const createCustomNotification = updateCheck.__get__('createCustomNotification'); + + const notification = { + id: 1, + custom: 1, + messages: [{ + id: uuid.v4(), + version: 'custom1', + content: '

    How about migrating your blog?

    ', + dismissible: false, + top: true, + type: 'warn' + }] + }; createCustomNotification(notification) .then(function () { @@ -325,15 +330,16 @@ describe('Update Check', function () { beforeEach(testUtils.setup('roles', 'settings', 'perms:setting', 'perms:init')); it('receives a notifications with messages', function (done) { - var updateCheckResponse = updateCheck.__get__('updateCheckResponse'), - createNotificationSpy = sinon.spy(), - message = { - id: uuid.v4(), - version: '^0.11.11', - content: 'Test', - dismissible: true, - top: true - }; + const updateCheckResponse = updateCheck.__get__('updateCheckResponse'); + const createNotificationSpy = sinon.spy(); + + const message = { + id: uuid.v4(), + version: '^0.11.11', + content: 'Test', + dismissible: true, + top: true + }; updateCheck.__set__('createCustomNotification', createNotificationSpy); @@ -346,26 +352,29 @@ describe('Update Check', function () { }); it('receives multiple notifications', function (done) { - var updateCheckResponse = updateCheck.__get__('updateCheckResponse'), - createNotificationSpy = sinon.spy(), - message1 = { - id: uuid.v4(), - version: '^0.11.11', - content: 'Test1', - dismissible: true, - top: true - }, - message2 = { - id: uuid.v4(), - version: '^0', - content: 'Test2', - dismissible: true, - top: false - }, - notifications = [ - {version: '0.11.12', messages: [message1]}, - {version: 'custom1', messages: [message2]} - ]; + const updateCheckResponse = updateCheck.__get__('updateCheckResponse'); + const createNotificationSpy = sinon.spy(); + + const message1 = { + id: uuid.v4(), + version: '^0.11.11', + content: 'Test1', + dismissible: true, + top: true + }; + + const message2 = { + id: uuid.v4(), + version: '^0', + content: 'Test2', + dismissible: true, + top: false + }; + + const notifications = [ + {version: '0.11.12', messages: [message1]}, + {version: 'custom1', messages: [message2]} + ]; updateCheck.__set__('createCustomNotification', createNotificationSpy); @@ -378,34 +387,38 @@ describe('Update Check', function () { }); it('ignores some custom notifications which are not marked as group', function (done) { - var updateCheckResponse = updateCheck.__get__('updateCheckResponse'), - createNotificationSpy = sinon.spy(), - message1 = { - id: uuid.v4(), - version: '^0.11.11', - content: 'Test1', - dismissible: true, - top: true - }, - message2 = { - id: uuid.v4(), - version: '^0', - content: 'Test2', - dismissible: true, - top: false - }, - message3 = { - id: uuid.v4(), - version: '^0', - content: 'Test2', - dismissible: true, - top: false - }, - notifications = [ - {version: '0.11.12', messages: [message1]}, - {version: 'all1', messages: [message2], custom: 1}, - {version: 'migration1', messages: [message3], custom: 1} - ]; + const updateCheckResponse = updateCheck.__get__('updateCheckResponse'); + const createNotificationSpy = sinon.spy(); + + const message1 = { + id: uuid.v4(), + version: '^0.11.11', + content: 'Test1', + dismissible: true, + top: true + }; + + const message2 = { + id: uuid.v4(), + version: '^0', + content: 'Test2', + dismissible: true, + top: false + }; + + const message3 = { + id: uuid.v4(), + version: '^0', + content: 'Test2', + dismissible: true, + top: false + }; + + const notifications = [ + {version: '0.11.12', messages: [message1]}, + {version: 'all1', messages: [message2], custom: 1}, + {version: 'migration1', messages: [message3], custom: 1} + ]; updateCheck.__set__('createCustomNotification', createNotificationSpy); @@ -418,34 +431,38 @@ describe('Update Check', function () { }); it('group matches', function (done) { - var updateCheckResponse = updateCheck.__get__('updateCheckResponse'), - createNotificationSpy = sinon.spy(), - message1 = { - id: uuid.v4(), - version: '^0.11.11', - content: 'Test1', - dismissible: true, - top: true - }, - message2 = { - id: uuid.v4(), - version: '^0', - content: 'Test2', - dismissible: true, - top: false - }, - message3 = { - id: uuid.v4(), - version: '^0', - content: 'Test2', - dismissible: true, - top: false - }, - notifications = [ - {version: '0.11.12', messages: [message1], custom: 0}, - {version: 'all1', messages: [message2], custom: 1}, - {version: 'migration1', messages: [message3], custom: 1} - ]; + const updateCheckResponse = updateCheck.__get__('updateCheckResponse'); + const createNotificationSpy = sinon.spy(); + + const message1 = { + id: uuid.v4(), + version: '^0.11.11', + content: 'Test1', + dismissible: true, + top: true + }; + + const message2 = { + id: uuid.v4(), + version: '^0', + content: 'Test2', + dismissible: true, + top: false + }; + + const message3 = { + id: uuid.v4(), + version: '^0', + content: 'Test2', + dismissible: true, + top: false + }; + + const notifications = [ + {version: '0.11.12', messages: [message1], custom: 0}, + {version: 'all1', messages: [message2], custom: 1}, + {version: 'migration1', messages: [message3], custom: 1} + ]; updateCheck.__set__('createCustomNotification', createNotificationSpy); @@ -460,18 +477,20 @@ describe('Update Check', function () { }); it('single custom notification received, group matches', function (done) { - var updateCheckResponse = updateCheck.__get__('updateCheckResponse'), - createNotificationSpy = sinon.spy(), - message1 = { - id: uuid.v4(), - version: '^0.11.11', - content: 'Custom', - dismissible: true, - top: true - }, - notifications = [ - {version: 'something', messages: [message1], custom: 1} - ]; + const updateCheckResponse = updateCheck.__get__('updateCheckResponse'); + const createNotificationSpy = sinon.spy(); + + const message1 = { + id: uuid.v4(), + version: '^0.11.11', + content: 'Custom', + dismissible: true, + top: true + }; + + const notifications = [ + {version: 'something', messages: [message1], custom: 1} + ]; updateCheck.__set__('createCustomNotification', createNotificationSpy); @@ -486,18 +505,20 @@ describe('Update Check', function () { }); it('single custom notification received, group does not match', function (done) { - var updateCheckResponse = updateCheck.__get__('updateCheckResponse'), - createNotificationSpy = sinon.spy(), - message1 = { - id: uuid.v4(), - version: '^0.11.11', - content: 'Custom', - dismissible: true, - top: true - }, - notifications = [ - {version: 'something', messages: [message1], custom: 1} - ]; + const updateCheckResponse = updateCheck.__get__('updateCheckResponse'); + const createNotificationSpy = sinon.spy(); + + const message1 = { + id: uuid.v4(), + version: '^0.11.11', + content: 'Custom', + dismissible: true, + top: true + }; + + const notifications = [ + {version: 'something', messages: [message1], custom: 1} + ]; updateCheck.__set__('createCustomNotification', createNotificationSpy); @@ -522,15 +543,16 @@ describe('Update Check', function () { }); it('[default]', function () { - var updateCheckRequest = updateCheck.__get__('updateCheckRequest'), - updateCheckDataSpy = sinon.stub(), - hostname, - reqObj, - data = { - ghost_version: '0.11.11', - blog_id: 'something', - npm_version: 'something' - }; + const updateCheckRequest = updateCheck.__get__('updateCheckRequest'); + const updateCheckDataSpy = sinon.stub(); + let hostname; + let reqObj; + + const data = { + ghost_version: '0.11.11', + blog_id: 'something', + npm_version: 'something' + }; updateCheck.__set__('request', function (_hostname, _reqObj) { hostname = _hostname; @@ -556,10 +578,10 @@ describe('Update Check', function () { }); it('privacy flag is used', function () { - var updateCheckRequest = updateCheck.__get__('updateCheckRequest'), - updateCheckDataSpy = sinon.stub(), - reqObj, - hostname; + const updateCheckRequest = updateCheck.__get__('updateCheckRequest'); + const updateCheckDataSpy = sinon.stub(); + let reqObj; + let hostname; configUtils.set({ privacy: { @@ -599,10 +621,10 @@ describe('Update Check', function () { }); it('received 500 from the service', function () { - var updateCheckRequest = updateCheck.__get__('updateCheckRequest'), - updateCheckDataSpy = sinon.stub(), - reqObj, - hostname; + const updateCheckRequest = updateCheck.__get__('updateCheckRequest'); + const updateCheckDataSpy = sinon.stub(); + let reqObj; + let hostname; updateCheck.__set__('request', function (_hostname, _reqObj) { hostname = _hostname; @@ -632,10 +654,10 @@ describe('Update Check', function () { }); it('received 404 from the service', function () { - var updateCheckRequest = updateCheck.__get__('updateCheckRequest'), - updateCheckDataSpy = sinon.stub(), - reqObj, - hostname; + const updateCheckRequest = updateCheck.__get__('updateCheckRequest'); + const updateCheckDataSpy = sinon.stub(); + let reqObj; + let hostname; updateCheck.__set__('request', function (_hostname, _reqObj) { hostname = _hostname; @@ -666,10 +688,10 @@ describe('Update Check', function () { }); it('custom url', function () { - var updateCheckRequest = updateCheck.__get__('updateCheckRequest'), - updateCheckDataSpy = sinon.stub(), - reqObj, - hostname; + const updateCheckRequest = updateCheck.__get__('updateCheckRequest'); + const updateCheckDataSpy = sinon.stub(); + let reqObj; + let hostname; configUtils.set({ updateCheck: { diff --git a/test/unit/adapters/scheduling/SchedulingDefault_spec.js b/test/unit/adapters/scheduling/SchedulingDefault_spec.js index 4aeb51c380..a57fed12f5 100644 --- a/test/unit/adapters/scheduling/SchedulingDefault_spec.js +++ b/test/unit/adapters/scheduling/SchedulingDefault_spec.js @@ -1,14 +1,14 @@ -var should = require('should'), - sinon = require('sinon'), - moment = require('moment'), - _ = require('lodash'), - express = require('express'), - bodyParser = require('body-parser'), - http = require('http'), - SchedulingDefault = require('../../../../core/server/adapters/scheduling/SchedulingDefault'); +const should = require('should'); +const sinon = require('sinon'); +const moment = require('moment'); +const _ = require('lodash'); +const express = require('express'); +const bodyParser = require('body-parser'); +const http = require('http'); +const SchedulingDefault = require('../../../../core/server/adapters/scheduling/SchedulingDefault'); describe('Scheduling Default Adapter', function () { - var scope = {}; + const scope = {}; beforeEach(function () { scope.adapter = new SchedulingDefault(); @@ -23,7 +23,7 @@ describe('Scheduling Default Adapter', function () { sinon.stub(scope.adapter, 'run'); sinon.stub(scope.adapter, '_execute'); - var dates = [ + const dates = [ moment().add(1, 'day').subtract(30, 'seconds').toDate(), moment().add(7, 'minutes').toDate(), @@ -128,10 +128,11 @@ describe('Scheduling Default Adapter', function () { it('run', function (done) { // 1000 jobs, but only the number x are under 1 minute - var timestamps = _.map(_.range(1000), function (i) { - return moment().add(i, 'seconds').valueOf(); - }), - allJobs = {}; + const timestamps = _.map(_.range(1000), function (i) { + return moment().add(i, 'seconds').valueOf(); + }); + + const allJobs = {}; sinon.stub(scope.adapter, '_execute').callsFake(function (nextJobs) { Object.keys(nextJobs).length.should.eql(121); @@ -164,12 +165,14 @@ describe('Scheduling Default Adapter', function () { }); it('execute', function (done) { - var pinged = 0, - jobs = 3, - timestamps = _.map(_.range(jobs), function (i) { - return moment().add(i * 50, 'milliseconds').valueOf(); - }), - nextJobs = {}; + let pinged = 0; + const jobs = 3; + + const timestamps = _.map(_.range(jobs), function (i) { + return moment().add(i * 50, 'milliseconds').valueOf(); + }); + + const nextJobs = {}; sinon.stub(scope.adapter, 'run'); sinon.stub(scope.adapter, '_pingUrl').callsFake(function () { @@ -192,9 +195,9 @@ describe('Scheduling Default Adapter', function () { }); it('delete job (unschedule)', function (done) { - var pinged = 0, - jobsToDelete = {}, - jobsToExecute = {}; + let pinged = 0; + const jobsToDelete = {}; + const jobsToExecute = {}; sinon.stub(scope.adapter, 'run'); sinon.stub(scope.adapter, '_pingUrl').callsFake(function () { @@ -237,10 +240,10 @@ describe('Scheduling Default Adapter', function () { }); it('pingUrl (PUT)', function (done) { - var app = express(), - server = http.createServer(app), - wasPinged = false, - reqBody; + const app = express(); + const server = http.createServer(app); + let wasPinged = false; + let reqBody; app.use(bodyParser.json()); @@ -271,10 +274,10 @@ describe('Scheduling Default Adapter', function () { }); it('pingUrl (GET)', function (done) { - var app = express(), - server = http.createServer(app), - wasPinged = false, - reqQuery; + const app = express(); + const server = http.createServer(app); + let wasPinged = false; + let reqQuery; app.get('/ping', function (req, res) { wasPinged = true; @@ -298,10 +301,10 @@ describe('Scheduling Default Adapter', function () { }); it('pingUrl (PUT, and detect publish in the past)', function (done) { - var app = express(), - server = http.createServer(app), - wasPinged = false, - reqBody; + const app = express(); + const server = http.createServer(app); + let wasPinged = false; + let reqBody; app.use(bodyParser.json()); @@ -327,10 +330,10 @@ describe('Scheduling Default Adapter', function () { }); it('pingUrl (GET, and detect publish in the past)', function (done) { - var app = express(), - server = http.createServer(app), - wasPinged = false, - reqQuery; + const app = express(); + const server = http.createServer(app); + let wasPinged = false; + let reqQuery; app.get('/ping', function (req, res) { wasPinged = true; @@ -354,11 +357,11 @@ describe('Scheduling Default Adapter', function () { }); it('pingUrl, but blog returns 503', function (done) { - var app = express(), - server = http.createServer(app), - returned500Count = 0, - returned200 = false, - reqBody; + const app = express(); + const server = http.createServer(app); + let returned500Count = 0; + let returned200 = false; + let reqBody; scope.adapter.retryTimeoutInMs = 10; diff --git a/test/unit/adapters/scheduling/index_spec.js b/test/unit/adapters/scheduling/index_spec.js index 65ebeee309..4819e7ea84 100644 --- a/test/unit/adapters/scheduling/index_spec.js +++ b/test/unit/adapters/scheduling/index_spec.js @@ -1,11 +1,11 @@ -var should = require('should'), - sinon = require('sinon'), - rewire = require('rewire'), - Promise = require('bluebird'), - postScheduling = require('../../../../core/server/adapters/scheduling/post-scheduling'); +const should = require('should'); +const sinon = require('sinon'); +const rewire = require('rewire'); +const Promise = require('bluebird'); +const postScheduling = require('../../../../core/server/adapters/scheduling/post-scheduling'); describe('Scheduling', function () { - var scope = {}; + const scope = {}; before(function () { sinon.stub(postScheduling, 'init').returns(Promise.resolve()); diff --git a/test/unit/adapters/scheduling/post-scheduling/index_spec.js b/test/unit/adapters/scheduling/post-scheduling/index_spec.js index 55d1e72fb2..ca346f5915 100644 --- a/test/unit/adapters/scheduling/post-scheduling/index_spec.js +++ b/test/unit/adapters/scheduling/post-scheduling/index_spec.js @@ -1,19 +1,19 @@ -var should = require('should'), - sinon = require('sinon'), - Promise = require('bluebird'), - moment = require('moment'), - testUtils = require('../../../../utils'), - common = require('../../../../../core/server/lib/common'), - models = require('../../../../../core/server/models'), - api = require('../../../../../core/server/api'), - schedulingUtils = require('../../../../../core/server/adapters/scheduling/utils'), - SchedulingDefault = require('../../../../../core/server/adapters/scheduling/SchedulingDefault'), - postScheduling = require('../../../../../core/server/adapters/scheduling/post-scheduling'), - urlUtils = require('../../../../../core/server/lib/url-utils'); +const should = require('should'); +const sinon = require('sinon'); +const Promise = require('bluebird'); +const moment = require('moment'); +const testUtils = require('../../../../utils'); +const common = require('../../../../../core/server/lib/common'); +const models = require('../../../../../core/server/models'); +const api = require('../../../../../core/server/api'); +const schedulingUtils = require('../../../../../core/server/adapters/scheduling/utils'); +const SchedulingDefault = require('../../../../../core/server/adapters/scheduling/SchedulingDefault'); +const postScheduling = require('../../../../../core/server/adapters/scheduling/post-scheduling'); +const urlUtils = require('../../../../../core/server/lib/url-utils'); // NOTE: to be unskiped and corrected once default scheduler code is migrated describe.skip('Scheduling: Post Scheduling', function () { - var scope = { + const scope = { events: {}, scheduledPosts: [], apiUrl: 'localhost:1111/', diff --git a/test/unit/adapters/scheduling/utils_spec.js b/test/unit/adapters/scheduling/utils_spec.js index 46658fc341..fa3cc04c54 100644 --- a/test/unit/adapters/scheduling/utils_spec.js +++ b/test/unit/adapters/scheduling/utils_spec.js @@ -1,12 +1,12 @@ -var should = require('should'), - fs = require('fs-extra'), - configUtils = require('../../../utils/configUtils'), - config = require('../../../../core/server/config'), - schedulingUtils = require('../../../../core/server/adapters/scheduling/utils'); +const should = require('should'); +const fs = require('fs-extra'); +const configUtils = require('../../../utils/configUtils'); +const config = require('../../../../core/server/config'); +const schedulingUtils = require('../../../../core/server/adapters/scheduling/utils'); const schedulingPath = configUtils.config.getContentPath('adapters') + 'scheduling/'; describe('Scheduling: utils', function () { - var scope = {adapter: null}; + const scope = {adapter: null}; before(function () { if (!fs.existsSync(schedulingPath)) { @@ -40,7 +40,7 @@ describe('Scheduling: utils', function () { } }); - var jsFile = '' + + const jsFile = '' + 'var util = require(\'util\');' + 'var SchedulingBase = require(\'../../../core/server/adapters/scheduling/SchedulingBase\');' + 'var AnotherAdapter = function (){ SchedulingBase.call(this); };' + @@ -63,7 +63,7 @@ describe('Scheduling: utils', function () { describe('error', function () { it('create with adapter, but missing fn\'s', function (done) { scope.adapter = schedulingPath + 'bad-adapter.js'; - var jsFile = '' + + const jsFile = '' + 'var util = require(\'util\');' + 'var SchedulingBase = require(\'../../../core/server/adapters/scheduling/SchedulingBase\');' + 'var BadAdapter = function (){ SchedulingBase.call(this); };' + diff --git a/test/unit/adapters/storage/LocalFileStorage_spec.js b/test/unit/adapters/storage/LocalFileStorage_spec.js index fbff030d24..1c2b7629f4 100644 --- a/test/unit/adapters/storage/LocalFileStorage_spec.js +++ b/test/unit/adapters/storage/LocalFileStorage_spec.js @@ -1,21 +1,21 @@ -var should = require('should'), - sinon = require('sinon'), - fs = require('fs-extra'), - moment = require('moment'), - Promise = require('bluebird'), - path = require('path'), - common = require('../../../../core/server/lib/common'), - LocalFileStore = require('../../../../core/server/adapters/storage/LocalFileStorage'), - localFileStore, - configUtils = require('../../../utils/configUtils'); +const should = require('should'); +const sinon = require('sinon'); +const fs = require('fs-extra'); +const moment = require('moment'); +const Promise = require('bluebird'); +const path = require('path'); +const common = require('../../../../core/server/lib/common'); +const LocalFileStore = require('../../../../core/server/adapters/storage/LocalFileStorage'); +let localFileStore; +const configUtils = require('../../../utils/configUtils'); describe('Local File System Storage', function () { - var image, - momentStub; + let image; + let momentStub; function fakeDate(mm, yyyy) { - var month = parseInt(mm, 10), - year = parseInt(yyyy, 10); + const month = parseInt(mm, 10); + const year = parseInt(yyyy, 10); momentStub.withArgs('YYYY').returns(year.toString()); momentStub.withArgs('MM').returns(month < 10 ? '0' + month.toString() : month.toString()); @@ -206,7 +206,7 @@ describe('Local File System Storage', function () { describe('when a custom content path is used', function () { beforeEach(function () { - var configPaths = configUtils.defaultConfig.paths; + const configPaths = configUtils.defaultConfig.paths; configUtils.set('paths:contentPath', configPaths.appRoot + '/var/ghostcms'); }); @@ -221,7 +221,7 @@ describe('Local File System Storage', function () { // @TODO: remove path.join mock... describe('on Windows', function () { - var truePathSep = path.sep; + const truePathSep = path.sep; beforeEach(function () { sinon.stub(path, 'join'); diff --git a/test/unit/adapters/storage/index_spec.js b/test/unit/adapters/storage/index_spec.js index c0820bd1a9..938a36a64c 100644 --- a/test/unit/adapters/storage/index_spec.js +++ b/test/unit/adapters/storage/index_spec.js @@ -1,13 +1,13 @@ -var should = require('should'), - fs = require('fs-extra'), - StorageBase = require('ghost-storage-base'), - configUtils = require('../../../utils/configUtils'), - storage = require('../../../../core/server/adapters/storage'), - LocalFileStorage = require('../../../../core/server/adapters/storage/LocalFileStorage'); +const should = require('should'); +const fs = require('fs-extra'); +const StorageBase = require('ghost-storage-base'); +const configUtils = require('../../../utils/configUtils'); +const storage = require('../../../../core/server/adapters/storage'); +const LocalFileStorage = require('../../../../core/server/adapters/storage/LocalFileStorage'); const storagePath = configUtils.config.getContentPath('adapters') + 'storage/'; describe('storage: index_spec', function () { - var scope = {adapter: null}; + const scope = {adapter: null}; before(function () { if (!fs.existsSync(storagePath)) { @@ -25,7 +25,7 @@ describe('storage: index_spec', function () { }); it('default image storage is local file storage', function () { - var chosenStorage = storage.getStorage(); + const chosenStorage = storage.getStorage(); (chosenStorage instanceof StorageBase).should.eql(true); (chosenStorage instanceof LocalFileStorage).should.eql(true); }); @@ -39,7 +39,7 @@ describe('storage: index_spec', function () { } }); - var jsFile = '' + + const jsFile = '' + '\'use strict\';' + 'var StorageBase = require(\'ghost-storage-base\');' + 'class AnotherAdapter extends StorageBase {' + @@ -49,7 +49,9 @@ describe('storage: index_spec', function () { 'delete(){}' + 'read(){}' + '}' + - 'module.exports = AnotherAdapter', chosenStorage; + 'module.exports = AnotherAdapter'; + + let chosenStorage; fs.writeFileSync(scope.adapter, jsFile); @@ -71,7 +73,7 @@ describe('storage: index_spec', function () { } }); - var jsFile = '' + + const jsFile = '' + '\'use strict\';' + 'var StorageBase = require(\'ghost-storage-base\');' + 'class AnotherAdapter extends StorageBase {' + diff --git a/test/unit/adapters/storage/utils_spec.js b/test/unit/adapters/storage/utils_spec.js index acd67419ec..216e1948b6 100644 --- a/test/unit/adapters/storage/utils_spec.js +++ b/test/unit/adapters/storage/utils_spec.js @@ -1,13 +1,13 @@ -var should = require('should'), - sinon = require('sinon'), - urlUtils = require('../../../../core/server/lib/url-utils'), +const should = require('should'); +const sinon = require('sinon'); +const urlUtils = require('../../../../core/server/lib/url-utils'); - // Stuff we are testing - storageUtils = require('../../../../core/server/adapters/storage/utils'); +// Stuff we are testing +const storageUtils = require('../../../../core/server/adapters/storage/utils'); describe('storage utils', function () { - var urlForStub, - urlGetSubdirStub; + let urlForStub; + let urlGetSubdirStub; beforeEach(function () { urlForStub = sinon.stub(); @@ -19,8 +19,8 @@ describe('storage utils', function () { describe('fn: getLocalFileStoragePath', function () { it('should return local file storage path for absolute URL', function () { - var url = 'http://myblog.com/content/images/2017/07/ghost-logo.png', - result; + const url = 'http://myblog.com/content/images/2017/07/ghost-logo.png'; + let result; urlForStub = sinon.stub(urlUtils, 'urlFor'); urlForStub.withArgs('home').returns('http://myblog.com/'); @@ -36,8 +36,8 @@ describe('storage utils', function () { // See https://github.com/TryGhost/Ghost/blob/master/core/server/web/shared/middlewares/url-redirects.js#L76 // TODO: Change the code to make this test work it.skip('should return local file storage path for https request, when blog setup as http', function () { - var url = 'https://myblog.com/content/images/2017/07/ghost-logo.png', - result; + const url = 'https://myblog.com/content/images/2017/07/ghost-logo.png'; + let result; urlForStub = sinon.stub(urlUtils, 'urlFor'); urlForStub.withArgs('home').returns('http://myblog.com/'); @@ -50,8 +50,8 @@ describe('storage utils', function () { }); it('should return local file storage path for absolute URL with subdirectory', function () { - var url = 'http://myblog.com/blog/content/images/2017/07/ghost-logo.png', - result; + const url = 'http://myblog.com/blog/content/images/2017/07/ghost-logo.png'; + let result; urlForStub = sinon.stub(urlUtils, 'urlFor'); urlForStub.withArgs('home').returns('http://myblog.com/'); @@ -64,8 +64,8 @@ describe('storage utils', function () { }); it('should return local file storage path for relative URL', function () { - var filePath = '/content/images/2017/07/ghost-logo.png', - result; + const filePath = '/content/images/2017/07/ghost-logo.png'; + let result; urlForStub = sinon.stub(urlUtils, 'urlFor'); urlForStub.withArgs('home').returns('http://myblog.com/'); @@ -78,8 +78,8 @@ describe('storage utils', function () { }); it('should return local file storage path for relative URL with subdirectory', function () { - var filePath = '/blog/content/images/2017/07/ghost-logo.png', - result; + const filePath = '/blog/content/images/2017/07/ghost-logo.png'; + let result; urlForStub = sinon.stub(urlUtils, 'urlFor'); urlForStub.withArgs('home').returns('http://myblog.com/'); @@ -92,8 +92,8 @@ describe('storage utils', function () { }); it('should not sanitize URL if not local file storage', function () { - var url = 'http://example-blog.com/ghost-logo.png', - result; + const url = 'http://example-blog.com/ghost-logo.png'; + let result; urlForStub = sinon.stub(urlUtils, 'urlFor'); urlForStub.withArgs('home').returns('http://myblog.com/'); @@ -108,8 +108,8 @@ describe('storage utils', function () { describe('fn: isLocalImage', function () { it('should return true when absolute URL and local file', function () { - var url = 'http://myblog.com/content/images/2017/07/ghost-logo.png', - result; + const url = 'http://myblog.com/content/images/2017/07/ghost-logo.png'; + let result; urlForStub = sinon.stub(urlUtils, 'urlFor'); urlForStub.withArgs('home').returns('http://myblog.com/'); @@ -125,8 +125,8 @@ describe('storage utils', function () { // See https://github.com/TryGhost/Ghost/blob/master/core/server/web/shared/middlewares/url-redirects.js#L76 // TODO: Change the code to make this test work it.skip('should return local file storage path for https request, when blog setup as http', function () { - var url = 'https://myblog.com/content/images/2017/07/ghost-logo.png', - result; + const url = 'https://myblog.com/content/images/2017/07/ghost-logo.png'; + let result; urlForStub = sinon.stub(urlUtils, 'urlFor'); urlForStub.withArgs('home').returns('http://myblog.com/'); @@ -139,8 +139,8 @@ describe('storage utils', function () { }); it('should return true when absolute URL with subdirectory and local file', function () { - var url = 'http://myblog.com/blog/content/images/2017/07/ghost-logo.png', - result; + const url = 'http://myblog.com/blog/content/images/2017/07/ghost-logo.png'; + let result; urlForStub = sinon.stub(urlUtils, 'urlFor'); urlForStub.withArgs('home').returns('http://myblog.com/'); @@ -153,8 +153,8 @@ describe('storage utils', function () { }); it('should return true when relative URL and local file', function () { - var url = '/content/images/2017/07/ghost-logo.png', - result; + const url = '/content/images/2017/07/ghost-logo.png'; + let result; urlForStub = sinon.stub(urlUtils, 'urlFor'); urlForStub.withArgs('home').returns('http://myblog.com/'); @@ -167,8 +167,8 @@ describe('storage utils', function () { }); it('should return true when relative URL and local file', function () { - var url = '/blog/content/images/2017/07/ghost-logo.png', - result; + const url = '/blog/content/images/2017/07/ghost-logo.png'; + let result; urlForStub = sinon.stub(urlUtils, 'urlFor'); urlForStub.withArgs('home').returns('http://myblog.com/'); @@ -181,8 +181,8 @@ describe('storage utils', function () { }); it('should return false when no local file', function () { - var url = 'http://somewebsite.com/ghost-logo.png', - result; + const url = 'http://somewebsite.com/ghost-logo.png'; + let result; urlForStub = sinon.stub(urlUtils, 'urlFor'); urlForStub.withArgs('home').returns('http://myblog.com/'); diff --git a/test/unit/apps/amp/amp_components_spec.js b/test/unit/apps/amp/amp_components_spec.js index ee0b66603d..5698572a8a 100644 --- a/test/unit/apps/amp/amp_components_spec.js +++ b/test/unit/apps/amp/amp_components_spec.js @@ -1,14 +1,15 @@ -var should = require('should'), +const should = require('should'); - // Stuff we are testing - ampComponentsHelper = require('../../../../core/frontend/apps/amp/lib/helpers/amp_components'); +// Stuff we are testing +const ampComponentsHelper = require('../../../../core/frontend/apps/amp/lib/helpers/amp_components'); describe('{{amp_components}} helper', function () { it('adds script tag for a gif', function () { - var post = { - html: 'yoda' - }, - rendered; + const post = { + html: 'yoda' + }; + + let rendered; rendered = ampComponentsHelper.call( {relativeUrl: '/post/amp/', safeVersion: '0.3', context: ['amp', 'post'], post: post}, @@ -19,10 +20,11 @@ describe('{{amp_components}} helper', function () { }); it('adds script tag for an iframe tag', function () { - var post = { - html: '' - }, - rendered; + const post = { + html: '' + }; + + let rendered; rendered = ampComponentsHelper.call( {relativeUrl: '/post/amp/', safeVersion: '0.3', context: ['amp', 'post'], post: post}, @@ -33,10 +35,11 @@ describe('{{amp_components}} helper', function () { }); it('adds script tag for a youtube embed', function () { - var post = { - html: '' - }, - rendered; + const post = { + html: '' + }; + + let rendered; rendered = ampComponentsHelper.call( {relativeUrl: '/post/amp/', safeVersion: '0.3', context: ['amp', 'post'], post: post}, @@ -47,13 +50,14 @@ describe('{{amp_components}} helper', function () { }); it('adds scripts for youtube embeds and iframes', function () { - var post = { - html: ` + const post = { + html: ` ` - }, - rendered; + }; + + let rendered; rendered = ampComponentsHelper.call( {relativeUrl: '/post/amp/', safeVersion: '0.3', context: ['amp', 'post'], post: post}, @@ -65,10 +69,11 @@ describe('{{amp_components}} helper', function () { }); it('adds script tag for an audio tag', function () { - var post = { - html: '
    Table of Content', - updated_at: 'Wed Jul 27 2016 18:17:22 GMT+0200 (CEST)', - id: 1 - }, - ampResult = ampContentHelper.call(testData), - sanitizedHTML, - ampedHTML; + const testData = { + html: 'Table of Content', + updated_at: 'Wed Jul 27 2016 18:17:22 GMT+0200 (CEST)', + id: 1 + }; + + const ampResult = ampContentHelper.call(testData); + let sanitizedHTML; + let ampedHTML; ampResult.then(function (rendered) { sanitizedHTML = ampContentHelper.__get__('cleanHTML'); @@ -291,14 +307,15 @@ describe('{{amp_content}} helper', function () { }); it('sanitizes remaining and not valid tags', function (done) { - var testData = { - html: '' + + const testData = { + html: '' + '' + '', - updated_at: 'Wed Jul 27 2016 18:17:22 GMT+0200 (CEST)', - id: 1 - }, - ampResult = ampContentHelper.call(testData); + updated_at: 'Wed Jul 27 2016 18:17:22 GMT+0200 (CEST)', + id: 1 + }; + + const ampResult = ampContentHelper.call(testData); ampResult.then(function (rendered) { should.exist(rendered); diff --git a/test/unit/apps/amp/router_spec.js b/test/unit/apps/amp/router_spec.js index 0163c70a13..a51a9654f5 100644 --- a/test/unit/apps/amp/router_spec.js +++ b/test/unit/apps/amp/router_spec.js @@ -1,12 +1,12 @@ -const should = require('should'), - sinon = require('sinon'), - path = require('path'), - ampController = require('../../../../core/frontend/apps/amp/lib/router'), - urlService = require('../../../../core/frontend/services/url'), - helpers = require('../../../../core/frontend/services/routing/helpers'), - common = require('../../../../core/server/lib/common'), - testUtils = require('../../../utils'), - configUtils = require('../../../utils/configUtils'); +const should = require('should'); +const sinon = require('sinon'); +const path = require('path'); +const ampController = require('../../../../core/frontend/apps/amp/lib/router'); +const urlService = require('../../../../core/frontend/services/url'); +const helpers = require('../../../../core/frontend/services/routing/helpers'); +const common = require('../../../../core/server/lib/common'); +const testUtils = require('../../../utils'); +const configUtils = require('../../../utils/configUtils'); // Helper function to prevent unit tests // from failing via timeout when they @@ -18,10 +18,10 @@ function failTest(done) { } describe('Unit - apps/amp/lib/router', function () { - let res, - req, - defaultPath, - rendererStub; + let res; + let req; + let defaultPath; + let rendererStub; beforeEach(function () { rendererStub = sinon.stub(); @@ -93,7 +93,10 @@ describe('Unit - apps/amp/lib/router', function () { }); describe('fn: getPostData', function () { - let res, req, entryLookupStub, post; + let res; + let req; + let entryLookupStub; + let post; beforeEach(function () { post = testUtils.DataGenerator.forKnex.createPost({slug: 'welcome'}); diff --git a/test/unit/apps/private-blogging/controller_spec.js b/test/unit/apps/private-blogging/controller_spec.js index b52b35532c..c137ffdc1b 100644 --- a/test/unit/apps/private-blogging/controller_spec.js +++ b/test/unit/apps/private-blogging/controller_spec.js @@ -1,12 +1,15 @@ -var should = require('should'), - sinon = require('sinon'), - path = require('path'), - configUtils = require('../../../utils/configUtils'), - themes = require('../../../../core/frontend/services/themes'), - privateController = require('../../../../core/frontend/apps/private-blogging/lib/router'); +const should = require('should'); +const sinon = require('sinon'); +const path = require('path'); +const configUtils = require('../../../utils/configUtils'); +const themes = require('../../../../core/frontend/services/themes'); +const privateController = require('../../../../core/frontend/apps/private-blogging/lib/router'); describe('Private Controller', function () { - var res, req, defaultPath, hasTemplateStub; + let res; + let req; + let defaultPath; + let hasTemplateStub; // Helper function to prevent unit tests // from failing via timeout when they diff --git a/test/unit/apps/private-blogging/input_password_spec.js b/test/unit/apps/private-blogging/input_password_spec.js index bfbae4d88e..555097625e 100644 --- a/test/unit/apps/private-blogging/input_password_spec.js +++ b/test/unit/apps/private-blogging/input_password_spec.js @@ -1,8 +1,8 @@ // We use the name input_password to match the helper for consistency: -var should = require('should'), +const should = require('should'); - // Stuff we are testing - input_password = require('../../../../core/frontend/apps/private-blogging/lib/helpers/input_password'); +// Stuff we are testing +const input_password = require('../../../../core/frontend/apps/private-blogging/lib/helpers/input_password'); describe('{{input_password}} helper', function () { it('has input_password helper', function () { @@ -10,21 +10,23 @@ describe('{{input_password}} helper', function () { }); it('returns the correct input when no custom options are specified', function () { - var markup = '', - rendered = input_password(); + const markup = ''; + const rendered = input_password(); should.exist(rendered); String(rendered).should.equal(markup); }); it('returns the correct input when a custom class is specified', function () { - var markup = '', - options = { - hash: { - class: 'test-class' - } - }, - rendered = input_password(options); + const markup = ''; + + const options = { + hash: { + class: 'test-class' + } + }; + + const rendered = input_password(options); should.exist(rendered); @@ -32,13 +34,15 @@ describe('{{input_password}} helper', function () { }); it('returns the correct input when a custom placeholder is specified', function () { - var markup = '', - options = { - hash: { - placeholder: 'Test' - } - }, - rendered = input_password(options); + const markup = ''; + + const options = { + hash: { + placeholder: 'Test' + } + }; + + const rendered = input_password(options); should.exist(rendered); diff --git a/test/unit/apps/private-blogging/middleware_spec.js b/test/unit/apps/private-blogging/middleware_spec.js index d39fd4a2ed..5cf3c81e84 100644 --- a/test/unit/apps/private-blogging/middleware_spec.js +++ b/test/unit/apps/private-blogging/middleware_spec.js @@ -1,26 +1,28 @@ -var should = require('should'), - sinon = require('sinon'), - crypto = require('crypto'), - fs = require('fs-extra'), - common = require('../../../../core/server/lib/common'), - settingsCache = require('../../../../core/server/services/settings/cache'), - privateBlogging = require('../../../../core/frontend/apps/private-blogging/lib/middleware'); +const should = require('should'); +const sinon = require('sinon'); +const crypto = require('crypto'); +const fs = require('fs-extra'); +const common = require('../../../../core/server/lib/common'); +const settingsCache = require('../../../../core/server/services/settings/cache'); +const privateBlogging = require('../../../../core/frontend/apps/private-blogging/lib/middleware'); function hash(password, salt) { - var hasher = crypto.createHash('sha256'); + const hasher = crypto.createHash('sha256'); hasher.update(password + salt, 'utf8'); return hasher.digest('hex'); } describe('Private Blogging', function () { - var settingsStub; + let settingsStub; afterEach(function () { sinon.restore(); }); describe('passProtect', function () { - var req, res, next; + let req; + let res; + let next; beforeEach(function () { req = { @@ -156,7 +158,7 @@ describe('Private Blogging', function () { }); it('authenticatePrivateSession should return next if hash is verified', function () { - var salt = Date.now().toString(); + const salt = Date.now().toString(); req.session = { token: hash('rightpassword', salt), @@ -180,7 +182,7 @@ describe('Private Blogging', function () { }); it('isPrivateSessionAuth should redirect if hash is verified', function () { - var salt = Date.now().toString(); + const salt = Date.now().toString(); req.session = { token: hash('rightpassword', salt), @@ -233,7 +235,7 @@ describe('Private Blogging', function () { }); it('filterPrivateRoutes should 404 for /rss/ requests', function () { - var salt = Date.now().toString(); + const salt = Date.now().toString(); req.url = req.path = '/rss/'; req.session = { @@ -250,7 +252,7 @@ describe('Private Blogging', function () { }); it('filterPrivateRoutes should 404 for /rss requests', function () { - var salt = Date.now().toString(); + const salt = Date.now().toString(); req.url = req.path = '/rss'; req.session = { @@ -267,7 +269,7 @@ describe('Private Blogging', function () { }); it('filterPrivateRoutes should 404 for rss with pagination requests', function () { - var salt = Date.now().toString(); + const salt = Date.now().toString(); req.url = req.path = '/rss/1'; req.session = { @@ -284,7 +286,7 @@ describe('Private Blogging', function () { }); it('filterPrivateRoutes should 404 for tag rss requests', function () { - var salt = Date.now().toString(); + const salt = Date.now().toString(); req.url = req.path = '/tag/welcome/rss/'; req.session = { @@ -301,7 +303,7 @@ describe('Private Blogging', function () { }); it('filterPrivateRoutes should return next if tag contains rss', function () { - var salt = Date.now().toString(); + const salt = Date.now().toString(); req.url = req.path = '/tag/rss-test/'; req.session = { @@ -318,7 +320,7 @@ describe('Private Blogging', function () { }); it('filterPrivateRoutes should not 404 for very short post url', function () { - var salt = Date.now().toString(); + const salt = Date.now().toString(); req.url = req.path = '/ab/'; req.session = { diff --git a/test/unit/config/index_spec.js b/test/unit/config/index_spec.js index cb3d17d396..4dbe782812 100644 --- a/test/unit/config/index_spec.js +++ b/test/unit/config/index_spec.js @@ -1,8 +1,8 @@ -var should = require('should'), - path = require('path'), - rewire = require('rewire'), - _ = require('lodash'), - configUtils = require('../../utils/configUtils'); +const should = require('should'); +const path = require('path'); +const rewire = require('rewire'); +const _ = require('lodash'); +const configUtils = require('../../utils/configUtils'); describe('Config', function () { before(function () { @@ -14,7 +14,10 @@ describe('Config', function () { }); describe('hierarchy of config channels', function () { - var originalEnv, originalArgv, customConfig, config; + let originalEnv; + let originalArgv; + let customConfig; + let config; beforeEach(function () { originalEnv = _.clone(process.env); @@ -84,7 +87,7 @@ describe('Config', function () { describe('Index', function () { it('should have exactly the right keys', function () { - var pathConfig = configUtils.config.get('paths'); + const pathConfig = configUtils.config.get('paths'); // This will fail if there are any extra keys pathConfig.should.have.keys( @@ -100,14 +103,14 @@ describe('Config', function () { }); it('should have the correct values for each key', function () { - var pathConfig = configUtils.config.get('paths'), - appRoot = path.resolve(__dirname, '../../../'); + const pathConfig = configUtils.config.get('paths'); + const appRoot = path.resolve(__dirname, '../../../'); pathConfig.should.have.property('appRoot', appRoot); }); it('should allow specific properties to be user defined', function () { - var contentPath = path.join(configUtils.config.get('paths').appRoot, 'otherContent', '/'); + const contentPath = path.join(configUtils.config.get('paths').appRoot, 'otherContent', '/'); configUtils.set('paths:contentPath', contentPath); configUtils.config.get('paths').should.have.property('contentPath', contentPath); diff --git a/test/unit/config/utils_spec.js b/test/unit/config/utils_spec.js index a617f30551..bd3e712cd2 100644 --- a/test/unit/config/utils_spec.js +++ b/test/unit/config/utils_spec.js @@ -1,18 +1,19 @@ -var should = require('should'), - configUtils = require('../../../core/server/config/utils'); +const should = require('should'); +const configUtils = require('../../../core/server/config/utils'); describe('UNIT: Config utils', function () { describe('makePathsAbsolute', function () { it('ensure we change paths only', function () { - var changedKey = [], - obj = { - database: { - client: 'mysql', - connection: { - filename: 'content/data/ghost.db' - } + const changedKey = []; + + const obj = { + database: { + client: 'mysql', + connection: { + filename: 'content/data/ghost.db' } - }; + } + }; this.set = function (key, value) { changedKey.push([key, value]); @@ -26,12 +27,13 @@ describe('UNIT: Config utils', function () { }); it('ensure it skips non strings', function () { - var changedKey = [], - obj = { - database: { - test: 10 - } - }; + const changedKey = []; + + const obj = { + database: { + test: 10 + } + }; this.set = function (key, value) { changedKey.push([key, value]); @@ -42,15 +44,16 @@ describe('UNIT: Config utils', function () { }); it('ensure we don\'t change absolute paths', function () { - var changedKey = [], - obj = { - database: { - client: 'mysql', - connection: { - filename: '/content/data/ghost.db' - } + const changedKey = []; + + const obj = { + database: { + client: 'mysql', + connection: { + filename: '/content/data/ghost.db' } - }; + } + }; this.set = function (key, value) { changedKey.push([key, value]); @@ -61,12 +64,13 @@ describe('UNIT: Config utils', function () { }); it('match paths on windows', function () { - var changedKey = [], - obj = { - database: { - filename: 'content\\data\\ghost.db' - } - }; + const changedKey = []; + + const obj = { + database: { + filename: 'content\\data\\ghost.db' + } + }; this.set = function (key, value) { changedKey.push([key, value]); diff --git a/test/unit/data/db/backup_spec.js b/test/unit/data/db/backup_spec.js index 56be963219..1abbb6e0f9 100644 --- a/test/unit/data/db/backup_spec.js +++ b/test/unit/data/db/backup_spec.js @@ -1,13 +1,15 @@ -var should = require('should'), - sinon = require('sinon'), - _ = require('lodash'), - fs = require('fs-extra'), - models = require('../../../../core/server/models'), - exporter = require('../../../../core/server/data/exporter'), - dbBackup = require('../../../../core/server/data/db/backup'); +const should = require('should'); +const sinon = require('sinon'); +const _ = require('lodash'); +const fs = require('fs-extra'); +const models = require('../../../../core/server/models'); +const exporter = require('../../../../core/server/data/exporter'); +const dbBackup = require('../../../../core/server/data/db/backup'); describe('Backup', function () { - var exportStub, filenameStub, fsStub; + let exportStub; + let filenameStub; + let fsStub; before(function () { models.init(); diff --git a/test/unit/data/exporter/index_spec.js b/test/unit/data/exporter/index_spec.js index b39660944e..66c9192e24 100644 --- a/test/unit/data/exporter/index_spec.js +++ b/test/unit/data/exporter/index_spec.js @@ -1,16 +1,18 @@ -var should = require('should'), - sinon = require('sinon'), - rewire = require('rewire'), - Promise = require('bluebird'), - db = require('../../../../core/server/data/db'), - common = require('../../../../core/server/lib/common'), - exporter = rewire('../../../../core/server/data/exporter'), - schema = require('../../../../core/server/data/schema'), - models = require('../../../../core/server/models'), - schemaTables = Object.keys(schema.tables); +const should = require('should'); +const sinon = require('sinon'); +const rewire = require('rewire'); +const Promise = require('bluebird'); +const db = require('../../../../core/server/data/db'); +const common = require('../../../../core/server/lib/common'); +const exporter = rewire('../../../../core/server/data/exporter'); +const schema = require('../../../../core/server/data/schema'); +const models = require('../../../../core/server/models'); +const schemaTables = Object.keys(schema.tables); describe('Exporter', function () { - var tablesStub, queryMock, knexMock; + let tablesStub; + let queryMock; + let knexMock; before(function () { models.init(); @@ -47,7 +49,7 @@ describe('Exporter', function () { // Execute exporter.doExport().then(function (exportData) { // No tables, less the number of excluded tables - var expectedCallCount = schemaTables.length - exporter.EXCLUDED_TABLES.length; + const expectedCallCount = schemaTables.length - exporter.EXCLUDED_TABLES.length; should.exist(exportData); @@ -145,7 +147,7 @@ describe('Exporter', function () { describe('exportFileName', function () { it('should return a correctly structured filename', function (done) { - var settingsStub = sinon.stub(models.Settings, 'findOne').returns( + const settingsStub = sinon.stub(models.Settings, 'findOne').returns( new Promise.resolve({ get: function () { return 'testblog'; @@ -163,7 +165,7 @@ describe('Exporter', function () { }); it('should return a correctly structured filename if settings is empty', function (done) { - var settingsStub = sinon.stub(models.Settings, 'findOne').returns( + const settingsStub = sinon.stub(models.Settings, 'findOne').returns( new Promise.resolve() ); @@ -177,7 +179,7 @@ describe('Exporter', function () { }); it('should return a correctly structured filename if settings errors', function (done) { - var settingsStub = sinon.stub(models.Settings, 'findOne').returns( + const settingsStub = sinon.stub(models.Settings, 'findOne').returns( new Promise.reject() ); diff --git a/test/unit/data/importer/index_spec.js b/test/unit/data/importer/index_spec.js index 7294620f99..1823f8ec39 100644 --- a/test/unit/data/importer/index_spec.js +++ b/test/unit/data/importer/index_spec.js @@ -1,24 +1,23 @@ -var should = require('should'), - sinon = require('sinon'), - rewire = require('rewire'), - Promise = require('bluebird'), - _ = require('lodash'), - testUtils = require('../../../utils'), - moment = require('moment'), - path = require('path'), - common = require('../../../../core/server/lib/common'), +const should = require('should'); +const sinon = require('sinon'); +const rewire = require('rewire'); +const Promise = require('bluebird'); +const _ = require('lodash'); +const testUtils = require('../../../utils'); +const moment = require('moment'); +const path = require('path'); +const common = require('../../../../core/server/lib/common'); - // Stuff we are testing - ImportManager = require('../../../../core/server/data/importer'), - JSONHandler = require('../../../../core/server/data/importer/handlers/json'), - ImageHandler = rewire('../../../../core/server/data/importer/handlers/image'), - MarkdownHandler = require('../../../../core/server/data/importer/handlers/markdown'), - DataImporter = require('../../../../core/server/data/importer/importers/data'), - ImageImporter = require('../../../../core/server/data/importer/importers/image'), +// Stuff we are testing +const ImportManager = require('../../../../core/server/data/importer'); - storage = require('../../../../core/server/adapters/storage'), - - urlUtils = require('../../../utils/urlUtils'); +const JSONHandler = require('../../../../core/server/data/importer/handlers/json'); +let ImageHandler = rewire('../../../../core/server/data/importer/handlers/image'); +const MarkdownHandler = require('../../../../core/server/data/importer/handlers/markdown'); +const DataImporter = require('../../../../core/server/data/importer/importers/data'); +const ImageImporter = require('../../../../core/server/data/importer/importers/image'); +const storage = require('../../../../core/server/adapters/storage'); +const urlUtils = require('../../../utils/urlUtils'); describe('Importer', function () { afterEach(function () { @@ -89,9 +88,9 @@ describe('Importer', function () { // Step 1 of importing is loadFile describe('loadFile', function () { it('knows when to process a file', function (done) { - var testFile = {name: 'myFile.json', path: '/my/path/myFile.json'}, - zipSpy = sinon.stub(ImportManager, 'processZip').returns(Promise.resolve()), - fileSpy = sinon.stub(ImportManager, 'processFile').returns(Promise.resolve()); + const testFile = {name: 'myFile.json', path: '/my/path/myFile.json'}; + const zipSpy = sinon.stub(ImportManager, 'processZip').returns(Promise.resolve()); + const fileSpy = sinon.stub(ImportManager, 'processFile').returns(Promise.resolve()); ImportManager.loadFile(testFile).then(function () { zipSpy.calledOnce.should.be.false(); @@ -102,9 +101,9 @@ describe('Importer', function () { // We need to make sure we don't actually extract a zip and leave temporary files everywhere! it('knows when to process a zip', function (done) { - var testZip = {name: 'myFile.zip', path: '/my/path/myFile.zip'}, - zipSpy = sinon.stub(ImportManager, 'processZip').returns(Promise.resolve()), - fileSpy = sinon.stub(ImportManager, 'processFile').returns(Promise.resolve()); + const testZip = {name: 'myFile.zip', path: '/my/path/myFile.zip'}; + const zipSpy = sinon.stub(ImportManager, 'processZip').returns(Promise.resolve()); + const fileSpy = sinon.stub(ImportManager, 'processFile').returns(Promise.resolve()); ImportManager.loadFile(testZip).then(function () { zipSpy.calledOnce.should.be.true(); @@ -114,16 +113,18 @@ describe('Importer', function () { }); it('has same result for zips and files', function (done) { - var testFile = {name: 'myFile.json', path: '/my/path/myFile.json'}, - testZip = {name: 'myFile.zip', path: '/my/path/myFile.zip'}, - // need to stub out the extract and glob function for zip - extractSpy = sinon.stub(ImportManager, 'extractZip').returns(Promise.resolve('/tmp/dir/')), - validSpy = sinon.stub(ImportManager, 'isValidZip').returns(true), - baseDirSpy = sinon.stub(ImportManager, 'getBaseDirectory').returns(), - getFileSpy = sinon.stub(ImportManager, 'getFilesFromZip'), - jsonSpy = sinon.stub(JSONHandler, 'loadFile').returns(Promise.resolve({posts: []})), - imageSpy = sinon.stub(ImageHandler, 'loadFile'), - mdSpy = sinon.stub(MarkdownHandler, 'loadFile'); + const testFile = {name: 'myFile.json', path: '/my/path/myFile.json'}; + const testZip = {name: 'myFile.zip', path: '/my/path/myFile.zip'}; + + // need to stub out the extract and glob function for zip + const extractSpy = sinon.stub(ImportManager, 'extractZip').returns(Promise.resolve('/tmp/dir/')); + + const validSpy = sinon.stub(ImportManager, 'isValidZip').returns(true); + const baseDirSpy = sinon.stub(ImportManager, 'getBaseDirectory').returns(); + const getFileSpy = sinon.stub(ImportManager, 'getFilesFromZip'); + const jsonSpy = sinon.stub(JSONHandler, 'loadFile').returns(Promise.resolve({posts: []})); + const imageSpy = sinon.stub(ImageHandler, 'loadFile'); + const mdSpy = sinon.stub(MarkdownHandler, 'loadFile'); getFileSpy.returns([]); getFileSpy.withArgs(JSONHandler).returns(['/tmp/dir/myFile.json']); @@ -151,39 +152,40 @@ describe('Importer', function () { describe('Validate Zip', function () { it('accepts a zip with a base directory', function () { - var testDir = path.resolve('test/utils/fixtures/import/zips/zip-with-base-dir'); + const testDir = path.resolve('test/utils/fixtures/import/zips/zip-with-base-dir'); ImportManager.isValidZip(testDir).should.be.ok(); }); it('accepts a zip without a base directory', function () { - var testDir = path.resolve('test/utils/fixtures/import/zips/zip-without-base-dir'); + const testDir = path.resolve('test/utils/fixtures/import/zips/zip-without-base-dir'); ImportManager.isValidZip(testDir).should.be.ok(); }); it('accepts a zip with an image directory', function () { - var testDir = path.resolve('test/utils/fixtures/import/zips/zip-image-dir'); + const testDir = path.resolve('test/utils/fixtures/import/zips/zip-image-dir'); ImportManager.isValidZip(testDir).should.be.ok(); }); it('fails a zip with two base directories', function () { - var testDir = path.resolve('test/utils/fixtures/import/zips/zip-with-double-base-dir'); + const testDir = path.resolve('test/utils/fixtures/import/zips/zip-with-double-base-dir'); ImportManager.isValidZip.bind(ImportManager, testDir).should.throw(common.errors.UnsupportedMediaTypeError); }); it('fails a zip with no content', function () { - var testDir = path.resolve('test/utils/fixtures/import/zips/zip-invalid'); + const testDir = path.resolve('test/utils/fixtures/import/zips/zip-invalid'); ImportManager.isValidZip.bind(ImportManager, testDir).should.throw(common.errors.UnsupportedMediaTypeError); }); it('shows a special error for old Roon exports', function () { - var testDir = path.resolve('test/utils/fixtures/import/zips/zip-old-roon-export'), - msg = 'Your zip file looks like an old format Roon export, ' + - 'please re-export your Roon blog and try again.'; + const testDir = path.resolve('test/utils/fixtures/import/zips/zip-old-roon-export'); + + const msg = 'Your zip file looks like an old format Roon export, ' + + 'please re-export your Roon blog and try again.'; ImportManager.isValidZip.bind(ImportManager, testDir).should.throw(common.errors.UnsupportedMediaTypeError); ImportManager.isValidZip.bind(ImportManager, testDir).should.throw(msg); @@ -192,13 +194,13 @@ describe('Importer', function () { describe('Get Base Dir', function () { it('returns string for base directory', function () { - var testDir = path.resolve('test/utils/fixtures/import/zips/zip-with-base-dir'); + const testDir = path.resolve('test/utils/fixtures/import/zips/zip-with-base-dir'); ImportManager.getBaseDirectory(testDir).should.equal('basedir'); }); it('returns empty for no base directory', function () { - var testDir = path.resolve('test/utils/fixtures/import/zips/zip-without-base-dir'); + const testDir = path.resolve('test/utils/fixtures/import/zips/zip-without-base-dir'); should.not.exist(ImportManager.getBaseDirectory(testDir)); }); @@ -224,11 +226,13 @@ describe('Importer', function () { describe('preProcess', function () { // preProcess can modify the data prior to importing it('calls the DataImporter preProcess method', function (done) { - var input = {data: {}, images: []}, - // pass a copy so that input doesn't get modified - inputCopy = _.cloneDeep(input), - dataSpy = sinon.spy(DataImporter, 'preProcess'), - imageSpy = sinon.spy(ImageImporter, 'preProcess'); + const input = {data: {}, images: []}; + + // pass a copy so that input doesn't get modified + const inputCopy = _.cloneDeep(input); + + const dataSpy = sinon.spy(DataImporter, 'preProcess'); + const imageSpy = sinon.spy(ImageImporter, 'preProcess'); ImportManager.preProcess(inputCopy).then(function (output) { dataSpy.calledOnce.should.be.true(); @@ -250,19 +254,23 @@ describe('Importer', function () { // doImport calls the real importers and has an effect on the DB. We don't want any of those calls to be made, // but to test that the right calls would be made it('calls the DataImporter doImport method with the data object', function (done) { - var input = {data: {posts: []}, images: []}, - // pass a copy so that input doesn't get modified - inputCopy = _.cloneDeep(input), - dataSpy = sinon.stub(DataImporter, 'doImport').callsFake(function (i) { - return Promise.resolve(i); - }), - imageSpy = sinon.stub(ImageImporter, 'doImport').callsFake(function (i) { - return Promise.resolve(i); - }), + const input = {data: {posts: []}, images: []}; - // The data importer should get the data object - expectedData = input.data, - expectedImages = input.images; + // pass a copy so that input doesn't get modified + const inputCopy = _.cloneDeep(input); + + const dataSpy = sinon.stub(DataImporter, 'doImport').callsFake(function (i) { + return Promise.resolve(i); + }); + + const imageSpy = sinon.stub(ImageImporter, 'doImport').callsFake(function (i) { + return Promise.resolve(i); + }); + + // The data importer should get the data object + const expectedData = input.data; + + const expectedImages = input.images; ImportManager.doImport(inputCopy).then(function (output) { // eql checks for equality @@ -284,7 +292,7 @@ describe('Importer', function () { // generateReport is intended to create a message to show to the user about what has been imported // it is currently a noop it('is currently a noop', function (done) { - var input = {data: {}, images: []}; + const input = {data: {}, images: []}; ImportManager.generateReport(input).then(function (output) { output.should.equal(input); done(); @@ -294,11 +302,11 @@ describe('Importer', function () { describe('importFromFile', function () { it('does the import steps in order', function (done) { - var loadFileSpy = sinon.stub(ImportManager, 'loadFile').returns(Promise.resolve()), - preProcessSpy = sinon.stub(ImportManager, 'preProcess').returns(Promise.resolve()), - doImportSpy = sinon.stub(ImportManager, 'doImport').returns(Promise.resolve()), - generateReportSpy = sinon.stub(ImportManager, 'generateReport').returns(Promise.resolve()), - cleanupSpy = sinon.stub(ImportManager, 'cleanUp').returns({}); + const loadFileSpy = sinon.stub(ImportManager, 'loadFile').returns(Promise.resolve()); + const preProcessSpy = sinon.stub(ImportManager, 'preProcess').returns(Promise.resolve()); + const doImportSpy = sinon.stub(ImportManager, 'doImport').returns(Promise.resolve()); + const generateReportSpy = sinon.stub(ImportManager, 'generateReport').returns(Promise.resolve()); + const cleanupSpy = sinon.stub(ImportManager, 'cleanUp').returns({}); ImportManager.importFromFile({}).then(function () { loadFileSpy.calledOnce.should.be.true(); @@ -326,7 +334,7 @@ describe('Importer', function () { }); it('correctly handles a valid db api wrapper', function (done) { - var file = [{ + const file = [{ path: testUtils.fixtures.getExportFixturePath('valid'), name: 'valid.json' }]; @@ -338,7 +346,7 @@ describe('Importer', function () { }); it('correctly errors when given a bad db api wrapper', function (done) { - var file = [{ + const file = [{ path: testUtils.fixtures.getExportFixturePath('broken'), name: 'broken.json' }]; @@ -353,7 +361,7 @@ describe('Importer', function () { }); describe('ImageHandler', function () { - var store = storage.getStorage(); + const store = storage.getStorage(); it('has the correct interface', function () { ImageHandler.type.should.eql('images'); @@ -376,13 +384,15 @@ describe('Importer', function () { }); it('can load a single file', function (done) { - var filename = 'test-image.jpeg', - file = [{ - path: '/my/test/' + filename, - name: filename - }], - storeSpy = sinon.spy(store, 'getUniqueFileName'), - storageSpy = sinon.spy(storage, 'getStorage'); + const filename = 'test-image.jpeg'; + + const file = [{ + path: '/my/test/' + filename, + name: filename + }]; + + const storeSpy = sinon.spy(store, 'getUniqueFileName'); + const storageSpy = sinon.spy(storage, 'getStorage'); ImageHandler.loadFile(_.clone(file)).then(function () { storageSpy.calledOnce.should.be.true(); @@ -396,13 +406,15 @@ describe('Importer', function () { }); it('can load a single file, maintaining structure', function (done) { - var filename = 'photos/my-cat.jpeg', - file = [{ - path: '/my/test/' + filename, - name: filename - }], - storeSpy = sinon.spy(store, 'getUniqueFileName'), - storageSpy = sinon.spy(storage, 'getStorage'); + const filename = 'photos/my-cat.jpeg'; + + const file = [{ + path: '/my/test/' + filename, + name: filename + }]; + + const storeSpy = sinon.spy(store, 'getUniqueFileName'); + const storageSpy = sinon.spy(storage, 'getStorage'); ImageHandler.loadFile(_.clone(file)).then(function () { storageSpy.calledOnce.should.be.true(); @@ -416,13 +428,15 @@ describe('Importer', function () { }); it('can load a single file, removing ghost dirs', function (done) { - var filename = 'content/images/my-cat.jpeg', - file = [{ - path: '/my/test/content/images/' + filename, - name: filename - }], - storeSpy = sinon.spy(store, 'getUniqueFileName'), - storageSpy = sinon.spy(storage, 'getStorage'); + const filename = 'content/images/my-cat.jpeg'; + + const file = [{ + path: '/my/test/content/images/' + filename, + name: filename + }]; + + const storeSpy = sinon.spy(store, 'getUniqueFileName'); + const storageSpy = sinon.spy(storage, 'getStorage'); ImageHandler.loadFile(_.clone(file)).then(function () { storageSpy.calledOnce.should.be.true(); @@ -438,13 +452,15 @@ describe('Importer', function () { it('can load a file (subdirectory)', function (done) { ImageHandler.__set__('urlUtils', urlUtils.getInstance({url: 'http://localhost:65535/subdir'})); - var filename = 'test-image.jpeg', - file = [{ - path: '/my/test/' + filename, - name: filename - }], - storeSpy = sinon.spy(store, 'getUniqueFileName'), - storageSpy = sinon.spy(storage, 'getStorage'); + const filename = 'test-image.jpeg'; + + const file = [{ + path: '/my/test/' + filename, + name: filename + }]; + + const storeSpy = sinon.spy(store, 'getUniqueFileName'); + const storageSpy = sinon.spy(storage, 'getStorage'); ImageHandler.loadFile(_.clone(file)).then(function () { storageSpy.calledOnce.should.be.true(); @@ -458,24 +474,25 @@ describe('Importer', function () { }); it('can load multiple files', function (done) { - var files = [{ - path: '/my/test/testing.png', - name: 'testing.png' - }, - { - path: '/my/test/photo/kitten.jpg', - name: 'photo/kitten.jpg' - }, - { - path: '/my/test/content/images/animated/bunny.gif', - name: 'content/images/animated/bunny.gif' - }, - { - path: '/my/test/images/puppy.jpg', - name: 'images/puppy.jpg' - }], - storeSpy = sinon.spy(store, 'getUniqueFileName'), - storageSpy = sinon.spy(storage, 'getStorage'); + const files = [{ + path: '/my/test/testing.png', + name: 'testing.png' + }, + { + path: '/my/test/photo/kitten.jpg', + name: 'photo/kitten.jpg' + }, + { + path: '/my/test/content/images/animated/bunny.gif', + name: 'content/images/animated/bunny.gif' + }, + { + path: '/my/test/images/puppy.jpg', + name: 'images/puppy.jpg' + }]; + + const storeSpy = sinon.spy(store, 'getUniqueFileName'); + const storageSpy = sinon.spy(storage, 'getStorage'); ImageHandler.loadFile(_.clone(files)).then(function () { storageSpy.calledOnce.should.be.true(); @@ -511,11 +528,12 @@ describe('Importer', function () { }); it('does convert a markdown file into a post object', function (done) { - var filename = 'draft-2014-12-19-test-1.md', - file = [{ - path: testUtils.fixtures.getImportFixturePath(filename), - name: filename - }]; + const filename = 'draft-2014-12-19-test-1.md'; + + const file = [{ + path: testUtils.fixtures.getImportFixturePath(filename), + name: filename + }]; MarkdownHandler.loadFile(file).then(function (result) { result.data.posts[0].markdown.should.eql('You\'re live! Nice.'); @@ -531,11 +549,12 @@ describe('Importer', function () { }); it('can parse a title from a markdown file', function (done) { - var filename = 'draft-2014-12-19-test-2.md', - file = [{ - path: testUtils.fixtures.getImportFixturePath(filename), - name: filename - }]; + const filename = 'draft-2014-12-19-test-2.md'; + + const file = [{ + path: testUtils.fixtures.getImportFixturePath(filename), + name: filename + }]; MarkdownHandler.loadFile(file).then(function (result) { result.data.posts[0].markdown.should.eql('You\'re live! Nice.'); @@ -550,11 +569,12 @@ describe('Importer', function () { }); it('can parse a featured image from a markdown file if there is a title', function (done) { - var filename = 'draft-2014-12-19-test-3.md', - file = [{ - path: testUtils.fixtures.getImportFixturePath(filename), - name: filename - }]; + const filename = 'draft-2014-12-19-test-3.md'; + + const file = [{ + path: testUtils.fixtures.getImportFixturePath(filename), + name: filename + }]; MarkdownHandler.loadFile(file).then(function (result) { result.data.posts[0].markdown.should.eql('You\'re live! Nice.'); @@ -569,11 +589,12 @@ describe('Importer', function () { }); it('can import a published post', function (done) { - var filename = 'published-2014-12-19-test-1.md', - file = [{ - path: testUtils.fixtures.getImportFixturePath(filename), - name: filename - }]; + const filename = 'published-2014-12-19-test-1.md'; + + const file = [{ + path: testUtils.fixtures.getImportFixturePath(filename), + name: filename + }]; MarkdownHandler.loadFile(file).then(function (result) { result.data.posts[0].markdown.should.eql('You\'re live! Nice.'); @@ -589,11 +610,12 @@ describe('Importer', function () { }); it('does not import deleted posts', function (done) { - var filename = 'deleted-2014-12-19-test-1.md', - file = [{ - path: testUtils.fixtures.getImportFixturePath(filename), - name: filename - }]; + const filename = 'deleted-2014-12-19-test-1.md'; + + const file = [{ + path: testUtils.fixtures.getImportFixturePath(filename), + name: filename + }]; MarkdownHandler.loadFile(file).then(function (result) { result.data.posts.should.be.empty(); @@ -603,7 +625,7 @@ describe('Importer', function () { }); it('can import multiple files', function (done) { - var files = [{ + const files = [{ path: testUtils.fixtures.getImportFixturePath('deleted-2014-12-19-test-1.md'), name: 'deleted-2014-12-19-test-1.md' }, { @@ -619,8 +641,9 @@ describe('Importer', function () { // doesn't get imported ;) // loadFile doesn't guarantee order of results - var one = result.data.posts[0].status === 'published' ? 0 : 1, - two = one === 0 ? 1 : 0; + const one = result.data.posts[0].status === 'published' ? 0 : 1; + + const two = one === 0 ? 1 : 0; // published-2014-12-19-test-1.md result.data.posts[one].markdown.should.eql('You\'re live! Nice.'); @@ -652,8 +675,8 @@ describe('Importer', function () { }); it('does preprocess posts, users and tags correctly', function () { - var inputData = require('../../../utils/fixtures/import/import-data-1.json'), - outputData = DataImporter.preProcess(_.cloneDeep(inputData)); + const inputData = require('../../../utils/fixtures/import/import-data-1.json'); + const outputData = DataImporter.preProcess(_.cloneDeep(inputData)); // Data preprocess is a noop inputData.data.data.posts[0].should.eql(outputData.data.data.posts[0]); @@ -670,8 +693,8 @@ describe('Importer', function () { }); it('does preprocess posts, users and tags correctly', function () { - var inputData = require('../../../utils/fixtures/import/import-data-1.json'), - outputData = ImageImporter.preProcess(_.cloneDeep(inputData)); + let inputData = require('../../../utils/fixtures/import/import-data-1.json'); + let outputData = ImageImporter.preProcess(_.cloneDeep(inputData)); inputData = inputData.data.data; outputData = outputData.data.data; @@ -699,13 +722,15 @@ describe('Importer', function () { }); it('does import the images correctly', function () { - var inputData = require('../../../utils/fixtures/import/import-data-1.json'), - storageApi = { - save: sinon.stub().returns(Promise.resolve()) - }, - storageSpy = sinon.stub(storage, 'getStorage').callsFake(function () { - return storageApi; - }); + const inputData = require('../../../utils/fixtures/import/import-data-1.json'); + + const storageApi = { + save: sinon.stub().returns(Promise.resolve()) + }; + + const storageSpy = sinon.stub(storage, 'getStorage').callsFake(function () { + return storageApi; + }); ImageImporter.doImport(inputData.images).then(function () { storageSpy.calledOnce.should.be.true(); diff --git a/test/unit/data/meta/amp_url_spec.js b/test/unit/data/meta/amp_url_spec.js index e0e8711d18..05757e5c06 100644 --- a/test/unit/data/meta/amp_url_spec.js +++ b/test/unit/data/meta/amp_url_spec.js @@ -1,8 +1,8 @@ -const should = require('should'), - sinon = require('sinon'), - rewire = require('rewire'), - urlUtils = require('../../../../core/server/lib/url-utils'), - testUtils = require('../../../utils'); +const should = require('should'); +const sinon = require('sinon'); +const rewire = require('rewire'); +const urlUtils = require('../../../../core/server/lib/url-utils'); +const testUtils = require('../../../utils'); let getAmpUrl = rewire('../../../../core/frontend/meta/amp_url'); diff --git a/test/unit/data/meta/asset_url_spec.js b/test/unit/data/meta/asset_url_spec.js index 7005efb1c8..9a87edb3f5 100644 --- a/test/unit/data/meta/asset_url_spec.js +++ b/test/unit/data/meta/asset_url_spec.js @@ -1,11 +1,11 @@ -var should = require('should'), - sinon = require('sinon'), - rewire = require('rewire'), - imageLib = require('../../../../core/server/lib/image'), - settingsCache = require('../../../../core/server/services/settings/cache'), - configUtils = require('../../../utils/configUtils'), - urlUtils = require('../../../utils/urlUtils'), - config = configUtils.config; +const should = require('should'); +const sinon = require('sinon'); +const rewire = require('rewire'); +const imageLib = require('../../../../core/server/lib/image'); +const settingsCache = require('../../../../core/server/services/settings/cache'); +const configUtils = require('../../../utils/configUtils'); +const urlUtils = require('../../../utils/urlUtils'); +const config = configUtils.config; const getAssetUrl = rewire('../../../../core/frontend/meta/asset_url'); @@ -16,39 +16,39 @@ describe('getAssetUrl', function () { }); it('should return asset url with just context', function () { - var testUrl = getAssetUrl('myfile.js'); + const testUrl = getAssetUrl('myfile.js'); testUrl.should.equal('/assets/myfile.js?v=' + config.get('assetHash')); }); it('should return asset url with just context even with leading /', function () { - var testUrl = getAssetUrl('/myfile.js'); + const testUrl = getAssetUrl('/myfile.js'); testUrl.should.equal('/assets/myfile.js?v=' + config.get('assetHash')); }); it('should not add asset to url if ghost.css for default templates', function () { - var testUrl = getAssetUrl('public/ghost.css'); + const testUrl = getAssetUrl('public/ghost.css'); testUrl.should.equal('/public/ghost.css?v=' + config.get('assetHash')); }); it('should not add asset to url has public in it', function () { - var testUrl = getAssetUrl('public/myfile.js'); + const testUrl = getAssetUrl('public/myfile.js'); testUrl.should.equal('/public/myfile.js?v=' + config.get('assetHash')); }); describe('favicon', function () { it('should not add asset to url if favicon.ico', function () { - var testUrl = getAssetUrl('favicon.ico'); + const testUrl = getAssetUrl('favicon.ico'); testUrl.should.equal('/favicon.ico'); }); it('should not add asset to url if favicon.png', function () { - var testUrl = getAssetUrl('favicon.png'); + const testUrl = getAssetUrl('favicon.png'); testUrl.should.equal('/favicon.ico'); }); it('should correct favicon path for custom png', function () { sinon.stub(settingsCache, 'get').withArgs('icon').returns('/content/images/2017/04/my-icon.png'); - var testUrl = getAssetUrl('favicon.ico'); + const testUrl = getAssetUrl('favicon.ico'); testUrl.should.equal('/favicon.png'); }); }); @@ -56,25 +56,25 @@ describe('getAssetUrl', function () { describe('minify', function () { it('should return asset minified url when hasMinFile & useMinFiles are both set to true', function () { configUtils.set('useMinFiles', true); - var testUrl = getAssetUrl('myfile.js', true); + const testUrl = getAssetUrl('myfile.js', true); testUrl.should.equal('/assets/myfile.min.js?v=' + config.get('assetHash')); }); it('should NOT return asset minified url when hasMinFile true but useMinFiles is false', function () { configUtils.set('useMinFiles', false); - var testUrl = getAssetUrl('myfile.js', true); + const testUrl = getAssetUrl('myfile.js', true); testUrl.should.equal('/assets/myfile.js?v=' + config.get('assetHash')); }); it('should NOT return asset minified url when hasMinFile false but useMinFiles is true', function () { configUtils.set('useMinFiles', true); - var testUrl = getAssetUrl('myfile.js', false); + const testUrl = getAssetUrl('myfile.js', false); testUrl.should.equal('/assets/myfile.js?v=' + config.get('assetHash')); }); it('should not add min to anything besides the last .', function () { configUtils.set('useMinFiles', true); - var testUrl = getAssetUrl('test.page/myfile.js', true); + const testUrl = getAssetUrl('test.page/myfile.js', true); testUrl.should.equal('/assets/test.page/myfile.min.js?v=' + config.get('assetHash')); }); }); @@ -85,42 +85,42 @@ describe('getAssetUrl', function () { }); it('should return asset url with just context', function () { - var testUrl = getAssetUrl('myfile.js'); + const testUrl = getAssetUrl('myfile.js'); testUrl.should.equal('/blog/assets/myfile.js?v=' + config.get('assetHash')); }); it('should return asset url with just context even with leading /', function () { - var testUrl = getAssetUrl('/myfile.js'); + const testUrl = getAssetUrl('/myfile.js'); testUrl.should.equal('/blog/assets/myfile.js?v=' + config.get('assetHash')); }); it('should not add asset to url if ghost.css for default templates', function () { - var testUrl = getAssetUrl('public/ghost.css'); + const testUrl = getAssetUrl('public/ghost.css'); testUrl.should.equal('/blog/public/ghost.css?v=' + config.get('assetHash')); }); it('should not add asset to url has public in it', function () { - var testUrl = getAssetUrl('public/myfile.js'); + const testUrl = getAssetUrl('public/myfile.js'); testUrl.should.equal('/blog/public/myfile.js?v=' + config.get('assetHash')); }); describe('favicon', function () { it('should not add asset to url if favicon.ico', function () { sinon.stub(imageLib.blogIcon, 'getIconUrl').returns('/blog/favicon.ico'); - var testUrl = getAssetUrl('favicon.ico'); + const testUrl = getAssetUrl('favicon.ico'); testUrl.should.equal('/blog/favicon.ico'); }); it('should not add asset to url if favicon.png', function () { sinon.stub(imageLib.blogIcon, 'getIconUrl').returns('/blog/favicon.ico'); - var testUrl = getAssetUrl('favicon.png'); + const testUrl = getAssetUrl('favicon.png'); testUrl.should.equal('/blog/favicon.ico'); }); it('should return correct favicon path for custom png', function () { sinon.stub(imageLib.blogIcon, 'getIconUrl').returns('/blog/favicon.png'); sinon.stub(settingsCache, 'get').withArgs('icon').returns('/content/images/2017/04/my-icon.png'); - var testUrl = getAssetUrl('favicon.ico'); + const testUrl = getAssetUrl('favicon.ico'); testUrl.should.equal('/blog/favicon.png'); }); }); @@ -128,25 +128,25 @@ describe('getAssetUrl', function () { describe('minify', function () { it('should return asset minified url when hasMinFile & useMinFiles are both set to true', function () { configUtils.set('useMinFiles', true); - var testUrl = getAssetUrl('myfile.js', true); + const testUrl = getAssetUrl('myfile.js', true); testUrl.should.equal('/blog/assets/myfile.min.js?v=' + config.get('assetHash')); }); it('should NOT return asset minified url when hasMinFile true but useMinFiles is false', function () { configUtils.set('useMinFiles', false); - var testUrl = getAssetUrl('myfile.js', true); + const testUrl = getAssetUrl('myfile.js', true); testUrl.should.equal('/blog/assets/myfile.js?v=' + config.get('assetHash')); }); it('should NOT return asset minified url when hasMinFile false but useMinFiles is true', function () { configUtils.set('useMinFiles', true); - var testUrl = getAssetUrl('myfile.js', false); + const testUrl = getAssetUrl('myfile.js', false); testUrl.should.equal('/blog/assets/myfile.js?v=' + config.get('assetHash')); }); it('should not add min to anything besides the last .', function () { configUtils.set('useMinFiles', true); - var testUrl = getAssetUrl('test.page/myfile.js', true); + const testUrl = getAssetUrl('test.page/myfile.js', true); testUrl.should.equal('/blog/assets/test.page/myfile.min.js?v=' + config.get('assetHash')); }); }); diff --git a/test/unit/data/meta/author_fb_url_spec.js b/test/unit/data/meta/author_fb_url_spec.js index 7a6617992d..96d734e159 100644 --- a/test/unit/data/meta/author_fb_url_spec.js +++ b/test/unit/data/meta/author_fb_url_spec.js @@ -1,10 +1,10 @@ -var should = require('should'), - getAuthorFacebookUrl = require('../../../../core/frontend/meta/author_fb_url'); +const should = require('should'); +const getAuthorFacebookUrl = require('../../../../core/frontend/meta/author_fb_url'); describe('getAuthorFacebookUrl', function () { it('should return author facebook url if post and has url', function () { - var facebookUrl = getAuthorFacebookUrl({ + const facebookUrl = getAuthorFacebookUrl({ context: ['post'], post: { primary_author: { @@ -17,7 +17,7 @@ describe('getAuthorFacebookUrl', function () { it('should return author facebook url if AMP post and has url', function () { - var facebookUrl = getAuthorFacebookUrl({ + const facebookUrl = getAuthorFacebookUrl({ context: ['amp', 'post'], post: { primary_author: { @@ -30,7 +30,7 @@ describe('getAuthorFacebookUrl', function () { it('should return null if context does not contain author facebook url and is a post', function () { - var facebookUrl = getAuthorFacebookUrl({ + const facebookUrl = getAuthorFacebookUrl({ context: ['post'], post: { primary_author: { @@ -42,7 +42,7 @@ describe('getAuthorFacebookUrl', function () { }); it('should return null if context does not contain author and is a post', function () { - var facebookUrl = getAuthorFacebookUrl({ + const facebookUrl = getAuthorFacebookUrl({ context: ['post'], post: {} }); @@ -51,7 +51,7 @@ describe('getAuthorFacebookUrl', function () { it('should return author facebook url if author and has url', function () { - var facebookUrl = getAuthorFacebookUrl({ + const facebookUrl = getAuthorFacebookUrl({ context: ['author'], author: { facebook: 'https://www.facebook.com/user' @@ -62,7 +62,7 @@ describe('getAuthorFacebookUrl', function () { it('should return null if context does not contain author facebook url and is a author', function () { - var facebookUrl = getAuthorFacebookUrl({ + const facebookUrl = getAuthorFacebookUrl({ context: ['author'], author: { facebook: '' @@ -72,7 +72,7 @@ describe('getAuthorFacebookUrl', function () { }); it('should return null if context is not a post', function () { - var facebookUrl = getAuthorFacebookUrl({ + const facebookUrl = getAuthorFacebookUrl({ context: ['tag'] }); should(facebookUrl).equal(null); diff --git a/test/unit/data/meta/author_image_spec.js b/test/unit/data/meta/author_image_spec.js index 8f7abfb6e9..c45b907be3 100644 --- a/test/unit/data/meta/author_image_spec.js +++ b/test/unit/data/meta/author_image_spec.js @@ -1,6 +1,6 @@ -var should = require('should'), - sinon = require('sinon'), - getAuthorImage = require('../../../../core/frontend/meta/author_image'); +const should = require('should'); +const sinon = require('sinon'); +const getAuthorImage = require('../../../../core/frontend/meta/author_image'); describe('getAuthorImage', function () { afterEach(function () { @@ -8,7 +8,7 @@ describe('getAuthorImage', function () { }); it('should return author image url if post and has url', function () { - var imageUrl = getAuthorImage({ + const imageUrl = getAuthorImage({ context: ['post'], post: { primary_author: { @@ -21,7 +21,7 @@ describe('getAuthorImage', function () { }); it('should return absolute author image url if post and has url', function () { - var imageUrl = getAuthorImage({ + const imageUrl = getAuthorImage({ context: ['post'], post: { primary_author: { @@ -34,7 +34,7 @@ describe('getAuthorImage', function () { }); it('should return author image url if AMP post and has url', function () { - var imageUrl = getAuthorImage({ + const imageUrl = getAuthorImage({ context: ['amp', 'post'], post: { primary_author: { @@ -46,7 +46,7 @@ describe('getAuthorImage', function () { }); it('should return absolute author image url if AMP post and has url', function () { - var imageUrl = getAuthorImage({ + const imageUrl = getAuthorImage({ context: ['amp', 'post'], post: { primary_author: { @@ -59,7 +59,7 @@ describe('getAuthorImage', function () { }); it('should return null if context does not contain author image url and is a post', function () { - var imageUrl = getAuthorImage({ + const imageUrl = getAuthorImage({ context: ['post'], post: { primary_author: { @@ -72,7 +72,7 @@ describe('getAuthorImage', function () { }); it('should return null if context does not contain author and is a post', function () { - var imageUrl = getAuthorImage({ + const imageUrl = getAuthorImage({ context: ['post'], post: {} }); @@ -81,7 +81,7 @@ describe('getAuthorImage', function () { }); it('should return null if context is not a post', function () { - var imageUrl = getAuthorImage({ + const imageUrl = getAuthorImage({ context: ['tag'] }); diff --git a/test/unit/data/meta/author_url_spec.js b/test/unit/data/meta/author_url_spec.js index 7c39b2aa4e..82427d5caf 100644 --- a/test/unit/data/meta/author_url_spec.js +++ b/test/unit/data/meta/author_url_spec.js @@ -1,8 +1,8 @@ -const should = require('should'), - sinon = require('sinon'), - ObjectId = require('bson-objectid'), - urlService = require('../../../../core/frontend/services/url'), - getAuthorUrl = require('../../../../core/frontend/meta/author_url'); +const should = require('should'); +const sinon = require('sinon'); +const ObjectId = require('bson-objectid'); +const urlService = require('../../../../core/frontend/services/url'); +const getAuthorUrl = require('../../../../core/frontend/meta/author_url'); describe('getAuthorUrl', function () { beforeEach(function () { diff --git a/test/unit/data/meta/blog_logo_spec.js b/test/unit/data/meta/blog_logo_spec.js index 5d2239f289..1778418ea0 100644 --- a/test/unit/data/meta/blog_logo_spec.js +++ b/test/unit/data/meta/blog_logo_spec.js @@ -1,7 +1,7 @@ -var should = require('should'), - getBlogLogo = require('../../../../core/frontend/meta/blog_logo'), - sinon = require('sinon'), - settingsCache = require('../../../../core/server/services/settings/cache'); +const should = require('should'); +const getBlogLogo = require('../../../../core/frontend/meta/blog_logo'); +const sinon = require('sinon'); +const settingsCache = require('../../../../core/server/services/settings/cache'); describe('getBlogLogo', function () { afterEach(function () { @@ -9,7 +9,7 @@ describe('getBlogLogo', function () { }); it('should return logo if uploaded', function () { - var blogLogo; + let blogLogo; sinon.stub(settingsCache, 'get').callsFake(function (key) { return { @@ -24,7 +24,7 @@ describe('getBlogLogo', function () { }); it('should return custom uploaded png icon if no logo given', function () { - var blogLogo; + let blogLogo; sinon.stub(settingsCache, 'get').callsFake(function (key) { return { diff --git a/test/unit/data/meta/canonical_url_spec.js b/test/unit/data/meta/canonical_url_spec.js index 236fa8bf55..0f3e4fbb1f 100644 --- a/test/unit/data/meta/canonical_url_spec.js +++ b/test/unit/data/meta/canonical_url_spec.js @@ -1,8 +1,8 @@ -const should = require('should'), - sinon = require('sinon'), - rewire = require('rewire'), - urlUtils = require('../../../../core/server/lib/url-utils'), - testUtils = require('../../../utils'); +const should = require('should'); +const sinon = require('sinon'); +const rewire = require('rewire'); +const urlUtils = require('../../../../core/server/lib/url-utils'); +const testUtils = require('../../../utils'); let getCanonicalUrl = rewire('../../../../core/frontend/meta/canonical_url'); diff --git a/test/unit/data/meta/context_object_spec.js b/test/unit/data/meta/context_object_spec.js index fe5e8d2153..5a66bc8e3f 100644 --- a/test/unit/data/meta/context_object_spec.js +++ b/test/unit/data/meta/context_object_spec.js @@ -1,10 +1,12 @@ -var should = require('should'), - sinon = require('sinon'), - getContextObject = require('../../../../core/frontend/meta/context_object.js'), - settingsCache = require('../../../../core/server/services/settings/cache'); +const should = require('should'); +const sinon = require('sinon'); +const getContextObject = require('../../../../core/frontend/meta/context_object.js'); +const settingsCache = require('../../../../core/server/services/settings/cache'); describe('getContextObject', function () { - var data, context, contextObject; + let data; + let context; + let contextObject; it('should be a function', function () { should.exist(getContextObject); diff --git a/test/unit/data/meta/cover_image_spec.js b/test/unit/data/meta/cover_image_spec.js index ed583b399e..f98d94cc9c 100644 --- a/test/unit/data/meta/cover_image_spec.js +++ b/test/unit/data/meta/cover_image_spec.js @@ -1,9 +1,9 @@ -var should = require('should'), - getCoverImage = require('../../../../core/frontend/meta/cover_image'); +const should = require('should'); +const getCoverImage = require('../../../../core/frontend/meta/cover_image'); describe('getCoverImage', function () { it('should return absolute cover image url for home', function () { - var coverImageUrl = getCoverImage({ + const coverImageUrl = getCoverImage({ context: ['home'], home: { cover_image: '/content/images/my-test-image.jpg' @@ -14,7 +14,7 @@ describe('getCoverImage', function () { }); it('should return absolute cover image url for author', function () { - var coverImageUrl = getCoverImage({ + const coverImageUrl = getCoverImage({ context: ['author'], author: { cover_image: '/content/images/my-test-image.jpg' @@ -25,7 +25,7 @@ describe('getCoverImage', function () { }); it('should return absolute image url for post', function () { - var coverImageUrl = getCoverImage({ + const coverImageUrl = getCoverImage({ context: ['post'], post: { feature_image: '/content/images/my-test-image.jpg' @@ -36,7 +36,7 @@ describe('getCoverImage', function () { }); it('should return absolute image url for AMP post', function () { - var coverImageUrl = getCoverImage({ + const coverImageUrl = getCoverImage({ context: ['amp', 'post'], post: { feature_image: '/content/images/my-test-image.jpg' @@ -47,7 +47,7 @@ describe('getCoverImage', function () { }); it('should return null if missing image', function () { - var coverImageUrl = getCoverImage({ + const coverImageUrl = getCoverImage({ context: ['post'], post: {} }); @@ -55,7 +55,7 @@ describe('getCoverImage', function () { }); it('should return null if author missing cover', function () { - var coverImageUrl = getCoverImage({ + const coverImageUrl = getCoverImage({ context: ['author'], author: {} }); @@ -63,7 +63,7 @@ describe('getCoverImage', function () { }); it('should return null if home missing cover', function () { - var coverImageUrl = getCoverImage({ + const coverImageUrl = getCoverImage({ context: ['home'], home: {} }); diff --git a/test/unit/data/meta/creator_url_spec.js b/test/unit/data/meta/creator_url_spec.js index 7313bf18da..9c600474ce 100644 --- a/test/unit/data/meta/creator_url_spec.js +++ b/test/unit/data/meta/creator_url_spec.js @@ -1,10 +1,10 @@ -var should = require('should'), - getCreatorTwitterUrl = require('../../../../core/frontend/meta/creator_url'); +const should = require('should'); +const getCreatorTwitterUrl = require('../../../../core/frontend/meta/creator_url'); describe('getCreatorTwitterUrl', function () { it('should return author twitter url if post and has url', function () { - var twitterUrl = getCreatorTwitterUrl({ + const twitterUrl = getCreatorTwitterUrl({ context: ['post'], post: { primary_author: { @@ -17,7 +17,7 @@ describe('getCreatorTwitterUrl', function () { it('should return null if context does not contain author twitter url and is a post', function () { - var twitterUrl = getCreatorTwitterUrl({ + const twitterUrl = getCreatorTwitterUrl({ context: ['post'], post: { primary_author: { @@ -29,7 +29,7 @@ describe('getCreatorTwitterUrl', function () { }); it('should return null if context does not contain author and is a post', function () { - var twitterUrl = getCreatorTwitterUrl({ + const twitterUrl = getCreatorTwitterUrl({ context: ['post'], post: {} }); @@ -38,7 +38,7 @@ describe('getCreatorTwitterUrl', function () { it('should return author twitter url if AMP post and has url', function () { - var twitterUrl = getCreatorTwitterUrl({ + const twitterUrl = getCreatorTwitterUrl({ context: ['amp', 'post'], post: { primary_author: { @@ -51,7 +51,7 @@ describe('getCreatorTwitterUrl', function () { it('should return null if context does not contain author twitter url and is an AMP post', function () { - var twitterUrl = getCreatorTwitterUrl({ + const twitterUrl = getCreatorTwitterUrl({ context: ['amp', 'post'], post: { primary_author: { @@ -63,7 +63,7 @@ describe('getCreatorTwitterUrl', function () { }); it('should return null if context does not contain author and is an AMP post', function () { - var twitterUrl = getCreatorTwitterUrl({ + const twitterUrl = getCreatorTwitterUrl({ context: ['amp', 'post'], post: {} }); @@ -72,7 +72,7 @@ describe('getCreatorTwitterUrl', function () { it('should return author twitter url if author and has url', function () { - var twitterUrl = getCreatorTwitterUrl({ + const twitterUrl = getCreatorTwitterUrl({ context: ['author'], author: { twitter: 'https://twitter.com/user' @@ -83,7 +83,7 @@ describe('getCreatorTwitterUrl', function () { it('should return null if context does not contain author twitter url and is a author', function () { - var twitterUrl = getCreatorTwitterUrl({ + const twitterUrl = getCreatorTwitterUrl({ context: ['author'], author: { twitter: '' @@ -93,7 +93,7 @@ describe('getCreatorTwitterUrl', function () { }); it('should return null if context is not a post', function () { - var twitterUrl = getCreatorTwitterUrl({ + const twitterUrl = getCreatorTwitterUrl({ context: ['tag'] }); should(twitterUrl).equal(null); diff --git a/test/unit/data/meta/description_spec.js b/test/unit/data/meta/description_spec.js index d45593d8ba..f6b985b082 100644 --- a/test/unit/data/meta/description_spec.js +++ b/test/unit/data/meta/description_spec.js @@ -627,7 +627,7 @@ describe('getMetaDescription', function () { }); it('v3: should return data page meta description if on root context contains page', function () { - var description = getMetaDescription({ + const description = getMetaDescription({ page: { meta_description: 'Best page ever!' } diff --git a/test/unit/data/meta/excerpt_spec.js b/test/unit/data/meta/excerpt_spec.js index 98f673f73a..97c1f7e65f 100644 --- a/test/unit/data/meta/excerpt_spec.js +++ b/test/unit/data/meta/excerpt_spec.js @@ -1,84 +1,89 @@ -var should = require('should'), - getExcerpt = require('../../../../core/frontend/meta/excerpt'); +const should = require('should'); +const getExcerpt = require('../../../../core/frontend/meta/excerpt'); describe('getExcerpt', function () { it('should return html excerpt with no html', function () { - var html = '

    There are
    10
    types
    of people in the world:' + + const html = '

    There are
    10
    types
    of people in the world:' + 'c those who ' + 'understand trinary,

    those who don\'t
    and' + - '< test > those<<< test >>> who mistake it <for> binary.', - expected = 'There are 10 types of people in the world: those who understand trinary, those who ' + - 'don\'t and those>> who mistake it <for> binary.'; + '< test > those<<< test >>> who mistake it <for> binary.'; + + const expected = 'There are 10 types of people in the world: those who understand trinary, those who ' + + 'don\'t and those>> who mistake it <for> binary.'; getExcerpt(html, {}).should.equal(expected); }); it('should return html excerpt strips multiple inline footnotes', function () { - var html = '

    Testing1, ' + + const html = '

    Testing1, ' + 'my footnotes. And stuff. Footnote2with a link ' + - 'right after.', - expected = 'Testing, my footnotes. And stuff. Footnotewith a link right after.'; + 'right after.'; + + const expected = 'Testing, my footnotes. And stuff. Footnotewith a link right after.'; getExcerpt(html, {}).should.equal(expected); }); it('should return html excerpt striping inline and bottom footnotes', function () { - var html = '

    Testing1' + + const html = '

    Testing1' + ' a very short post with a single footnote.

    \n' + '', - expected = 'Testing a very short post with a single footnote.'; + 'title="return to article">↩

'; + + const expected = 'Testing a very short post with a single footnote.'; getExcerpt(html, {}).should.equal(expected); }); it('should return html excerpt truncated by word', function () { - var html = '

Hello World! It\'s me!

', - expected = 'Hello World!'; + const html = '

Hello World! It\'s me!

'; + const expected = 'Hello World!'; getExcerpt(html, {words: '2'}).should.equal(expected); }); it('should return html excerpt truncated by words with non-ascii characters', function () { - var html = '

Едквюэ опортэат праэчынт ючю но, квуй эю

', - expected = 'Едквюэ опортэат'; + const html = '

Едквюэ опортэат праэчынт ючю но, квуй эю

'; + const expected = 'Едквюэ опортэат'; getExcerpt(html, {words: '2'}).should.equal(expected); }); it('should return html excerpt truncated by character', function () { - var html = '

Hello World! It\'s me!

', - expected = 'Hello Wo'; + const html = '

Hello World! It\'s me!

'; + const expected = 'Hello Wo'; getExcerpt(html, {characters: '8'}).should.equal(expected); }); it('should fall back to 50 words if not specified', function () { - var html = '

There are
10
types
of people in the world:' + + const html = '

There are
10
types
of people in the world:' + 'c those who ' + 'understand trinary,

those who don\'t
and' + - '< test > those<<< test >>> who mistake it <for> binary.', - expected = 'There are 10 types of people in the world: those who understand trinary, those who ' + - 'don\'t and those>> who mistake it <for> binary.'; + '< test > those<<< test >>> who mistake it <for> binary.'; + + const expected = 'There are 10 types of people in the world: those who understand trinary, those who ' + + 'don\'t and those>> who mistake it <for> binary.'; getExcerpt(html).should.equal(expected); }); it('should truncate plain text for custom excerpts', function () { - var html = 'This is a custom excerpt. It should always be rendered in full length and not being cut ' + + const html = 'This is a custom excerpt. It should always be rendered in full length and not being cut ' + 'off. The maximum length of a custom excerpt is 300 characters. Enough to tell a bit about ' + 'your story and make a nice summary for your readers. It\s only allowed to truncate anything ' + - 'after 300 characters. This give', - expected = 'This is a custom excerpt. It should always be rendered in full length and not being cut ' + - 'off. The maximum length of a custom excerpt is 300 characters. Enough to tell a bit about ' + - 'your story and make a nice summary for your readers. It\s only allowed to truncate anything ' + - 'after 300 characters. This give'; + 'after 300 characters. This give'; + + const expected = 'This is a custom excerpt. It should always be rendered in full length and not being cut ' + + 'off. The maximum length of a custom excerpt is 300 characters. Enough to tell a bit about ' + + 'your story and make a nice summary for your readers. It\s only allowed to truncate anything ' + + 'after 300 characters. This give'; getExcerpt(html, {characters: '300'}).should.equal(expected); }); diff --git a/test/unit/data/meta/image-dimensions_spec.js b/test/unit/data/meta/image-dimensions_spec.js index b7f3c667f3..5ef72aeead 100644 --- a/test/unit/data/meta/image-dimensions_spec.js +++ b/test/unit/data/meta/image-dimensions_spec.js @@ -1,10 +1,10 @@ -var should = require('should'), - sinon = require('sinon'), - rewire = require('rewire'), - getImageDimensions = rewire('../../../../core/frontend/meta/image-dimensions'); +const should = require('should'); +const sinon = require('sinon'); +const rewire = require('rewire'); +const getImageDimensions = rewire('../../../../core/frontend/meta/image-dimensions'); describe('getImageDimensions', function () { - var sizeOfStub; + let sizeOfStub; beforeEach(function () { sizeOfStub = sinon.stub(); @@ -15,7 +15,7 @@ describe('getImageDimensions', function () { }); it('should return dimension for images', function (done) { - var metaData = { + const metaData = { coverImage: { url: 'http://mysite.com/content/image/mypostcoverimage.jpg' }, @@ -67,7 +67,7 @@ describe('getImageDimensions', function () { }); it('should return metaData if url is undefined or null', function (done) { - var metaData = { + const metaData = { coverImage: { url: undefined }, @@ -110,7 +110,7 @@ describe('getImageDimensions', function () { }); it('should fake image dimension for publisher.logo if file is too big and square', function (done) { - var metaData = { + const metaData = { coverImage: { url: 'http://mysite.com/content/image/mypostcoverimage.jpg' }, @@ -162,7 +162,7 @@ describe('getImageDimensions', function () { }); it('should not fake dimension for publisher.logo if a logo is too big but not square', function (done) { - var metaData = { + const metaData = { coverImage: { url: 'http://mysite.com/content/image/mypostcoverimage.jpg' }, diff --git a/test/unit/data/meta/keywords_spec.js b/test/unit/data/meta/keywords_spec.js index 03fbeb4493..ef0356e515 100644 --- a/test/unit/data/meta/keywords_spec.js +++ b/test/unit/data/meta/keywords_spec.js @@ -1,7 +1,7 @@ -var should = require('should'), - sinon = require('sinon'), - models = require('../../../../core/server/models'), - getKeywords = require('../../../../core/frontend/meta/keywords'); +const should = require('should'); +const sinon = require('sinon'); +const models = require('../../../../core/server/models'); +const getKeywords = require('../../../../core/frontend/meta/keywords'); describe('getKeywords', function () { before(function () { @@ -13,7 +13,7 @@ describe('getKeywords', function () { }); it('should return tags as keywords if post has tags', function () { - var keywords = getKeywords({ + const keywords = getKeywords({ post: { tags: [ {name: 'one'}, @@ -26,7 +26,7 @@ describe('getKeywords', function () { }); it('should only return visible tags', function () { - var keywords = getKeywords({ + const keywords = getKeywords({ post: { tags: [ {name: 'one', visibility: 'public'}, @@ -40,7 +40,7 @@ describe('getKeywords', function () { }); it('should return null if post has tags is empty array', function () { - var keywords = getKeywords({ + const keywords = getKeywords({ post: { tags: [] } @@ -49,14 +49,14 @@ describe('getKeywords', function () { }); it('should return null if post has no tags', function () { - var keywords = getKeywords({ + const keywords = getKeywords({ post: {} }); should.equal(keywords, null); }); it('should return null if not a post', function () { - var keywords = getKeywords({ + const keywords = getKeywords({ author: {} }); should.equal(keywords, null); diff --git a/test/unit/data/meta/modified_date_spec.js b/test/unit/data/meta/modified_date_spec.js index 4e172075b8..84597236c6 100644 --- a/test/unit/data/meta/modified_date_spec.js +++ b/test/unit/data/meta/modified_date_spec.js @@ -1,9 +1,9 @@ -var should = require('should'), - getModifiedDate = require('../../../../core/frontend/meta/modified_date'); +const should = require('should'); +const getModifiedDate = require('../../../../core/frontend/meta/modified_date'); describe('getModifiedDate', function () { it('should return updated at date as ISO 8601 from context if exists', function () { - var modDate = getModifiedDate({ + const modDate = getModifiedDate({ context: ['post'], post: { updated_at: new Date('2016-01-01 12:56:45.232Z') @@ -13,7 +13,7 @@ describe('getModifiedDate', function () { }); it('should return updated at date for an AMP post', function () { - var modDate = getModifiedDate({ + const modDate = getModifiedDate({ context: ['amp', 'post'], post: { updated_at: new Date('2016-01-01 12:56:45.232Z') @@ -23,7 +23,7 @@ describe('getModifiedDate', function () { }); it('should return null if no update_at date on context', function () { - var modDate = getModifiedDate({ + const modDate = getModifiedDate({ context: ['author'], author: {} }); @@ -31,7 +31,7 @@ describe('getModifiedDate', function () { }); it('should return null if context and property do not match in name', function () { - var modDate = getModifiedDate({ + const modDate = getModifiedDate({ context: ['author'], post: { updated_at: new Date('2016-01-01 12:56:45.232Z') diff --git a/test/unit/data/meta/og_type_spec.js b/test/unit/data/meta/og_type_spec.js index 70a066534e..f4ebbfc675 100644 --- a/test/unit/data/meta/og_type_spec.js +++ b/test/unit/data/meta/og_type_spec.js @@ -1,30 +1,30 @@ -var should = require('should'), - getOgType = require('../../../../core/frontend/meta/og_type'); +const should = require('should'); +const getOgType = require('../../../../core/frontend/meta/og_type'); describe('getOgType', function () { it('should return og type profile if context is type author', function () { - var ogType = getOgType({ + const ogType = getOgType({ context: ['author'] }); should.equal(ogType, 'profile'); }); it('should return og type article if context is type post', function () { - var ogType = getOgType({ + const ogType = getOgType({ context: ['post'] }); should.equal(ogType, 'article'); }); it('should return og type article if context is type amp', function () { - var ogType = getOgType({ + const ogType = getOgType({ context: ['amp', 'post'] }); should.equal(ogType, 'article'); }); it('should return og type website if context is not author or post', function () { - var ogType = getOgType({ + const ogType = getOgType({ context: ['tag'] }); should.equal(ogType, 'website'); diff --git a/test/unit/data/meta/paginated_url_spec.js b/test/unit/data/meta/paginated_url_spec.js index 2e8995476b..7b80178473 100644 --- a/test/unit/data/meta/paginated_url_spec.js +++ b/test/unit/data/meta/paginated_url_spec.js @@ -1,10 +1,11 @@ -var should = require('should'), - sinon = require('sinon'), - getPaginatedUrl = require('../../../../core/frontend/meta/paginated_url'), - urlUtils = require('../../../utils/urlUtils'); +const should = require('should'); +const sinon = require('sinon'); +const getPaginatedUrl = require('../../../../core/frontend/meta/paginated_url'); +const urlUtils = require('../../../utils/urlUtils'); describe('getPaginatedUrl', function () { - var data, getTestUrls; + let data; + let getTestUrls; beforeEach(function () { data = {}; @@ -31,7 +32,7 @@ describe('getPaginatedUrl', function () { data.pagination = {prev: null, next: 2}; // Execute test - var urls = getTestUrls(); + const urls = getTestUrls(); // Check results urls.should.have.property('next', 'http://127.0.0.1:2369/page/2/'); @@ -47,7 +48,7 @@ describe('getPaginatedUrl', function () { data.pagination = {prev: 1, next: 3}; // Execute test - var urls = getTestUrls(); + const urls = getTestUrls(); // Check results urls.should.have.property('next', 'http://127.0.0.1:2369/page/3/'); @@ -63,7 +64,7 @@ describe('getPaginatedUrl', function () { data.pagination = {prev: 9, next: null}; // Execute test - var urls = getTestUrls(); + const urls = getTestUrls(); // Check results urls.should.have.property('next', null); @@ -81,7 +82,7 @@ describe('getPaginatedUrl', function () { data.pagination = {prev: null, next: 2}; // Execute test - var urls = getTestUrls(); + const urls = getTestUrls(); // Check results urls.should.have.property('next', 'http://127.0.0.1:2369/featured/page/2/'); @@ -97,7 +98,7 @@ describe('getPaginatedUrl', function () { data.pagination = {prev: 1, next: 3}; // Execute test - var urls = getTestUrls(); + const urls = getTestUrls(); // Check results urls.should.have.property('next', 'http://127.0.0.1:2369/featured/page/3/'); @@ -113,7 +114,7 @@ describe('getPaginatedUrl', function () { data.pagination = {prev: 9, next: null}; // Execute test - var urls = getTestUrls(); + const urls = getTestUrls(); // Check results urls.should.have.property('next', null); @@ -142,7 +143,7 @@ describe('getPaginatedUrl', function () { data.pagination = {prev: 1, next: 3}; // Execute test - var urls = getTestUrls(); + const urls = getTestUrls(); // Check results urls.should.have.property('next', 'http://localhost:65535/blog/page/3/'); @@ -158,7 +159,7 @@ describe('getPaginatedUrl', function () { data.pagination = {prev: 1, next: 3}; // Execute test - var urls = getTestUrls(); + const urls = getTestUrls(); // Check results urls.should.have.property('next', 'http://localhost:65535/blog/featured/page/3/'); diff --git a/test/unit/data/meta/published_date_spec.js b/test/unit/data/meta/published_date_spec.js index 2de9b20f96..d67a2309fd 100644 --- a/test/unit/data/meta/published_date_spec.js +++ b/test/unit/data/meta/published_date_spec.js @@ -1,9 +1,9 @@ -var should = require('should'), - getPublishedDate = require('../../../../core/frontend/meta/published_date'); +const should = require('should'); +const getPublishedDate = require('../../../../core/frontend/meta/published_date'); describe('getPublishedDate', function () { it('should return published at date as ISO 8601 from context if exists', function () { - var pubDate = getPublishedDate({ + const pubDate = getPublishedDate({ context: ['post'], post: { published_at: new Date('2016-01-01 12:56:45.232Z') @@ -13,7 +13,7 @@ describe('getPublishedDate', function () { }); it('should return published at over created at date as ISO 8601 if has both', function () { - var pubDate = getPublishedDate({ + const pubDate = getPublishedDate({ context: ['post'], post: { published_at: new Date('2016-01-01 12:56:45.232Z'), @@ -24,7 +24,7 @@ describe('getPublishedDate', function () { }); it('should return published at date for an amp context', function () { - var pubDate = getPublishedDate({ + const pubDate = getPublishedDate({ context: ['amp', 'post'], post: { published_at: new Date('2016-01-01 12:56:45.232Z') @@ -34,7 +34,7 @@ describe('getPublishedDate', function () { }); it('should return null if no update_at date on context', function () { - var pubDate = getPublishedDate({ + const pubDate = getPublishedDate({ context: ['author'], author: {} }); @@ -42,7 +42,7 @@ describe('getPublishedDate', function () { }); it('should return null if context and property do not match in name', function () { - var pubDate = getPublishedDate({ + const pubDate = getPublishedDate({ context: ['author'], post: { published_at: new Date('2016-01-01 12:56:45.232Z') diff --git a/test/unit/data/meta/rss_url_spec.js b/test/unit/data/meta/rss_url_spec.js index ed4a5248be..190fe9393e 100644 --- a/test/unit/data/meta/rss_url_spec.js +++ b/test/unit/data/meta/rss_url_spec.js @@ -1,7 +1,7 @@ -const should = require('should'), - sinon = require('sinon'), - routing = require('../../../../core/frontend/services/routing'), - getRssUrl = require('../../../../core/frontend/meta/rss_url'); +const should = require('should'); +const sinon = require('sinon'); +const routing = require('../../../../core/frontend/services/routing'); +const getRssUrl = require('../../../../core/frontend/meta/rss_url'); describe('getRssUrl', function () { beforeEach(function () { diff --git a/test/unit/data/meta/schema_spec.js b/test/unit/data/meta/schema_spec.js index 2be518e096..b4452b74f7 100644 --- a/test/unit/data/meta/schema_spec.js +++ b/test/unit/data/meta/schema_spec.js @@ -1,57 +1,61 @@ -var should = require('should'), - getSchema = require('../../../../core/frontend/meta/schema'), - markdownToMobiledoc = require('../../../utils/fixtures/data-generator').markdownToMobiledoc; +const should = require('should'); +const getSchema = require('../../../../core/frontend/meta/schema'); +const markdownToMobiledoc = require('../../../utils/fixtures/data-generator').markdownToMobiledoc; describe('getSchema', function () { it('should return post schema if context starts with post', function (done) { - var metadata = { - site: { - title: 'Site Title', - url: 'http://mysite.com', - logo: { - url: 'http://mysite.com/author/image/url/logo.jpg', - dimensions: { - width: 500, - height: 500 - } - } - }, - authorImage: { - url: 'http://mysite.com/author/image/url/me.jpg', + const metadata = { + site: { + title: 'Site Title', + url: 'http://mysite.com', + logo: { + url: 'http://mysite.com/author/image/url/logo.jpg', dimensions: { width: 500, height: 500 } - }, - authorFacebook: 'testuser', - creatorTwitter: '@testuser', - authorUrl: 'http://mysite.com/author/me/', - metaTitle: 'Post Title', - url: 'http://mysite.com/post/my-post-slug/', - publishedDate: '2015-12-25T05:35:01.234Z', - modifiedDate: '2016-01-21T22:13:05.412Z', - coverImage: { - url: 'http://mysite.com/content/image/mypostcoverimage.jpg', - dimensions: { - width: 500, - height: 500 - } - }, - keywords: ['one', 'two', 'tag'], - metaDescription: 'Post meta description', - excerpt: 'Custom excerpt for description' - }, data = { - context: ['post'], - post: { - primary_author: { - name: 'Post Author', - website: 'http://myblogsite.com/', - bio: 'My author bio.', - facebook: 'testuser', - twitter: '@testuser' - } } - }, schema = getSchema(metadata, data); + }, + authorImage: { + url: 'http://mysite.com/author/image/url/me.jpg', + dimensions: { + width: 500, + height: 500 + } + }, + authorFacebook: 'testuser', + creatorTwitter: '@testuser', + authorUrl: 'http://mysite.com/author/me/', + metaTitle: 'Post Title', + url: 'http://mysite.com/post/my-post-slug/', + publishedDate: '2015-12-25T05:35:01.234Z', + modifiedDate: '2016-01-21T22:13:05.412Z', + coverImage: { + url: 'http://mysite.com/content/image/mypostcoverimage.jpg', + dimensions: { + width: 500, + height: 500 + } + }, + keywords: ['one', 'two', 'tag'], + metaDescription: 'Post meta description', + excerpt: 'Custom excerpt for description' + }; + + const data = { + context: ['post'], + post: { + primary_author: { + name: 'Post Author', + website: 'http://myblogsite.com/', + bio: 'My author bio.', + facebook: 'testuser', + twitter: '@testuser' + } + } + }; + + const schema = getSchema(metadata, data); should.deepEqual(schema, { '@context': 'https://schema.org', @@ -104,55 +108,58 @@ describe('getSchema', function () { }); it('should return page schema if context starts with page', function (done) { - var metadata = { - site: { - title: 'Site Title', - url: 'http://mysite.com', - logo: { - url: 'http://mysite.com/author/image/url/logo.jpg', - dimensions: { - width: 500, - height: 500 - } - } - }, - authorImage: { - url: 'http://mysite.com/author/image/url/me.jpg', + const metadata = { + site: { + title: 'Site Title', + url: 'http://mysite.com', + logo: { + url: 'http://mysite.com/author/image/url/logo.jpg', dimensions: { width: 500, height: 500 } - }, - authorFacebook: 'testuser', - creatorTwitter: '@testuser', - authorUrl: 'http://mysite.com/author/me/', - metaTitle: 'Page Title', - url: 'http://mysite.com/post/my-page-slug/', - publishedDate: '2015-12-25T05:35:01.234Z', - modifiedDate: '2016-01-21T22:13:05.412Z', - coverImage: { - url: 'http://mysite.com/content/image/mypagecoverimage.jpg', - dimensions: { - width: 500, - height: 500 - } - }, - keywords: ['one', 'two'], - metaDescription: 'Post meta description', - excerpt: 'Custom excerpt for description' - }, data = { - context: ['page'], - page: { - primary_author: { - name: 'Page Author', - website: 'http://myblogsite.com/', - bio: 'My author bio.', - facebook: 'testuser', - twitter: '@testuser' - } } }, - schema = getSchema(metadata, data); + authorImage: { + url: 'http://mysite.com/author/image/url/me.jpg', + dimensions: { + width: 500, + height: 500 + } + }, + authorFacebook: 'testuser', + creatorTwitter: '@testuser', + authorUrl: 'http://mysite.com/author/me/', + metaTitle: 'Page Title', + url: 'http://mysite.com/post/my-page-slug/', + publishedDate: '2015-12-25T05:35:01.234Z', + modifiedDate: '2016-01-21T22:13:05.412Z', + coverImage: { + url: 'http://mysite.com/content/image/mypagecoverimage.jpg', + dimensions: { + width: 500, + height: 500 + } + }, + keywords: ['one', 'two'], + metaDescription: 'Post meta description', + excerpt: 'Custom excerpt for description' + }; + + const data = { + context: ['page'], + page: { + primary_author: { + name: 'Page Author', + website: 'http://myblogsite.com/', + bio: 'My author bio.', + facebook: 'testuser', + twitter: '@testuser' + } + } + }; + + const schema = getSchema(metadata, data); should.deepEqual(schema, { '@context': 'https://schema.org', @@ -205,58 +212,62 @@ describe('getSchema', function () { }); it('should return post schema if context starts with amp', function (done) { - var metadata = { - site: { - title: 'Site Title', - url: 'http://mysite.com', - logo: { - url: 'http://mysite.com/author/image/url/logo.jpg', - dimensions: { - width: 500, - height: 500 - } - } - }, - authorImage: { - url: 'http://mysite.com/author/image/url/me.jpg', + const metadata = { + site: { + title: 'Site Title', + url: 'http://mysite.com', + logo: { + url: 'http://mysite.com/author/image/url/logo.jpg', dimensions: { width: 500, height: 500 } - }, - authorFacebook: 'testuser', - creatorTwitter: '@testuser', - authorUrl: 'http://mysite.com/author/me/', - metaTitle: 'Post Title', - url: 'http://mysite.com/post/my-amp-post-slug/', - publishedDate: '2015-12-25T05:35:01.234Z', - modifiedDate: '2016-01-21T22:13:05.412Z', - coverImage: { - url: 'http://mysite.com/content/image/mypostcoverimage.jpg', - dimensions: { - width: 500, - height: 500 - } - }, - keywords: ['one', 'two', 'tag'], - metaDescription: 'Post meta description', - excerpt: 'Post meta description' - }, data = { - context: ['amp', 'post'], - post: { - title: 'Post Title', - slug: 'my-amp-post-slug', - mobiledoc: markdownToMobiledoc('some markdown'), - html: 'some html', - primary_author: { - name: 'Post Author', - website: 'http://myblogsite.com/', - bio: 'My author bio.', - facebook: 'testuser', - twitter: '@testuser' - } } - }, schema = getSchema(metadata, data); + }, + authorImage: { + url: 'http://mysite.com/author/image/url/me.jpg', + dimensions: { + width: 500, + height: 500 + } + }, + authorFacebook: 'testuser', + creatorTwitter: '@testuser', + authorUrl: 'http://mysite.com/author/me/', + metaTitle: 'Post Title', + url: 'http://mysite.com/post/my-amp-post-slug/', + publishedDate: '2015-12-25T05:35:01.234Z', + modifiedDate: '2016-01-21T22:13:05.412Z', + coverImage: { + url: 'http://mysite.com/content/image/mypostcoverimage.jpg', + dimensions: { + width: 500, + height: 500 + } + }, + keywords: ['one', 'two', 'tag'], + metaDescription: 'Post meta description', + excerpt: 'Post meta description' + }; + + const data = { + context: ['amp', 'post'], + post: { + title: 'Post Title', + slug: 'my-amp-post-slug', + mobiledoc: markdownToMobiledoc('some markdown'), + html: 'some html', + primary_author: { + name: 'Post Author', + website: 'http://myblogsite.com/', + bio: 'My author bio.', + facebook: 'testuser', + twitter: '@testuser' + } + } + }; + + const schema = getSchema(metadata, data); should.deepEqual(schema, { '@context': 'https://schema.org', @@ -309,34 +320,38 @@ describe('getSchema', function () { }); it('should return post schema removing null or undefined values', function (done) { - var metadata = { - site: { - title: 'Site Title' - }, - authorImage: null, - authorFacebook: undefined, - creatorTwitter: undefined, - authorUrl: 'http://mysite.com/author/me/', - metaTitle: 'Post Title', - url: 'http://mysite.com/post/my-post-slug/', - publishedDate: '2015-12-25T05:35:01.234Z', - modifiedDate: '2016-01-21T22:13:05.412Z', - coverImage: undefined, - keywords: [], - metaDescription: '', - excerpt: 'Post meta description' - }, data = { - context: ['post'], - post: { - primary_author: { - name: 'Post Author', - website: undefined, - bio: null, - facebook: null, - twitter: null - } + const metadata = { + site: { + title: 'Site Title' + }, + authorImage: null, + authorFacebook: undefined, + creatorTwitter: undefined, + authorUrl: 'http://mysite.com/author/me/', + metaTitle: 'Post Title', + url: 'http://mysite.com/post/my-post-slug/', + publishedDate: '2015-12-25T05:35:01.234Z', + modifiedDate: '2016-01-21T22:13:05.412Z', + coverImage: undefined, + keywords: [], + metaDescription: '', + excerpt: 'Post meta description' + }; + + const data = { + context: ['post'], + post: { + primary_author: { + name: 'Post Author', + website: undefined, + bio: null, + facebook: null, + twitter: null } - }, schema = getSchema(metadata, data); + } + }; + + const schema = getSchema(metadata, data); should.deepEqual(schema, { '@context': 'https://schema.org', @@ -367,43 +382,47 @@ describe('getSchema', function () { }); it('should return image url instead of ImageObjects if no dimensions supplied', function (done) { - var metadata = { - site: { - title: 'Site Title', - url: 'http://mysite.com', - logo: { - url: 'http://mysite.com/author/image/url/logo.jpg' - } - }, - authorImage: { - url: 'http://mysite.com/author/image/url/me.jpg' - }, - authorFacebook: 'testuser', - creatorTwitter: '@testuser', - authorUrl: 'http://mysite.com/author/me/', - metaTitle: 'Post Title', - url: 'http://mysite.com/post/my-post-slug/', - publishedDate: '2015-12-25T05:35:01.234Z', - modifiedDate: '2016-01-21T22:13:05.412Z', - coverImage: { - url: 'http://mysite.com/content/image/mypostcoverimage.jpg' - }, - keywords: ['one', 'two', 'tag'], - metaDescription: 'Post meta description', - excerpt: 'Post meta description' - }, data = { - context: ['post'], - post: { - primary_author: { - name: 'Post Author', - website: 'http://myblogsite.com/', - bio: 'My author bio.', - facebook: 'testuser', - twitter: '@testuser', - metaDescription: 'My author bio.' - } + const metadata = { + site: { + title: 'Site Title', + url: 'http://mysite.com', + logo: { + url: 'http://mysite.com/author/image/url/logo.jpg' } - }, schema = getSchema(metadata, data); + }, + authorImage: { + url: 'http://mysite.com/author/image/url/me.jpg' + }, + authorFacebook: 'testuser', + creatorTwitter: '@testuser', + authorUrl: 'http://mysite.com/author/me/', + metaTitle: 'Post Title', + url: 'http://mysite.com/post/my-post-slug/', + publishedDate: '2015-12-25T05:35:01.234Z', + modifiedDate: '2016-01-21T22:13:05.412Z', + coverImage: { + url: 'http://mysite.com/content/image/mypostcoverimage.jpg' + }, + keywords: ['one', 'two', 'tag'], + metaDescription: 'Post meta description', + excerpt: 'Post meta description' + }; + + const data = { + context: ['post'], + post: { + primary_author: { + name: 'Post Author', + website: 'http://myblogsite.com/', + bio: 'My author bio.', + facebook: 'testuser', + twitter: '@testuser', + metaDescription: 'My author bio.' + } + } + }; + + const schema = getSchema(metadata, data); should.deepEqual(schema, { '@context': 'https://schema.org', @@ -442,22 +461,26 @@ describe('getSchema', function () { }); it('should return home schema if context starts with home', function () { - var metadata = { - site: { - title: 'Site Title' - }, - url: 'http://mysite.com/post/my-post-slug/', - coverImage: { - url: 'http://mysite.com/content/image/mypostcoverimage.jpg', - dimensions: { - width: 500, - height: 500 - } - }, - metaDescription: 'This is the theme description' - }, data = { - context: ['home'] - }, schema = getSchema(metadata, data); + const metadata = { + site: { + title: 'Site Title' + }, + url: 'http://mysite.com/post/my-post-slug/', + coverImage: { + url: 'http://mysite.com/content/image/mypostcoverimage.jpg', + dimensions: { + width: 500, + height: 500 + } + }, + metaDescription: 'This is the theme description' + }; + + const data = { + context: ['home'] + }; + + const schema = getSchema(metadata, data); should.deepEqual(schema, { '@context': 'https://schema.org', @@ -484,25 +507,29 @@ describe('getSchema', function () { }); it('should return tag schema if context starts with tag', function () { - var metadata = { - site: { - title: 'Site Title' - }, - url: 'http://mysite.com/post/my-post-slug/', - coverImage: { - url: 'http://mysite.com/content/image/mypostcoverimage.jpg', - dimensions: { - width: 500, - height: 500 - } - }, - metaDescription: 'This is the tag description!' - }, data = { - context: ['tag'], - tag: { - name: 'Great Tag' + const metadata = { + site: { + title: 'Site Title' + }, + url: 'http://mysite.com/post/my-post-slug/', + coverImage: { + url: 'http://mysite.com/content/image/mypostcoverimage.jpg', + dimensions: { + width: 500, + height: 500 } - }, schema = getSchema(metadata, data); + }, + metaDescription: 'This is the tag description!' + }; + + const data = { + context: ['tag'], + tag: { + name: 'Great Tag' + } + }; + + const schema = getSchema(metadata, data); should.deepEqual(schema, { '@context': 'https://schema.org', @@ -530,28 +557,32 @@ describe('getSchema', function () { }); it('should return author schema if context starts with author', function () { - var metadata = { - site: { - title: 'Site Title', - url: 'http://mysite.com' - }, - authorImage: { - url: 'http://mysite.com/author/image/url/me.jpg', - dimensions: { - width: 500, - height: 500 - } - }, - authorUrl: 'http://mysite.com/author/me/', - metaDescription: 'This is the author description!' - }, data = { - context: ['author'], - author: { - name: 'Author Name', - website: 'http://myblogsite.com/?user=bambedibu&a=', - twitter: '@testuser' + const metadata = { + site: { + title: 'Site Title', + url: 'http://mysite.com' + }, + authorImage: { + url: 'http://mysite.com/author/image/url/me.jpg', + dimensions: { + width: 500, + height: 500 } - }, schema = getSchema(metadata, data); + }, + authorUrl: 'http://mysite.com/author/me/', + metaDescription: 'This is the author description!' + }; + + const data = { + context: ['author'], + author: { + name: 'Author Name', + website: 'http://myblogsite.com/?user=bambedibu&a=', + twitter: '@testuser' + } + }; + + const schema = getSchema(metadata, data); should.deepEqual(schema, { '@context': 'https://schema.org', @@ -571,9 +602,9 @@ describe('getSchema', function () { }); it('should return null if not a supported type', function () { - var metadata = {}, - data = {}, - schema = getSchema(metadata, data); + const metadata = {}; + const data = {}; + const schema = getSchema(metadata, data); should.deepEqual(schema, null); }); diff --git a/test/unit/data/meta/structured_data_spec.js b/test/unit/data/meta/structured_data_spec.js index 0b7142ea59..ed86f5f6f9 100644 --- a/test/unit/data/meta/structured_data_spec.js +++ b/test/unit/data/meta/structured_data_spec.js @@ -1,40 +1,42 @@ -var should = require('should'), - getStructuredData = require('../../../../core/frontend/meta/structured_data'); +const should = require('should'); +const getStructuredData = require('../../../../core/frontend/meta/structured_data'); describe('getStructuredData', function () { it('should return structured data from metadata per post', function (done) { - var metadata = { - site: { - title: 'Site Title', - facebook: 'testuser', - twitter: '@testuser' - }, - authorName: 'Test User', - ogType: 'article', - metaTitle: 'Post Title', - canonicalUrl: 'http://mysite.com/post/my-post-slug/', - publishedDate: '2015-12-25T05:35:01.234Z', - modifiedDate: '2016-01-21T22:13:05.412Z', - coverImage: { - url: 'http://mysite.com/content/image/mypostcoverimage.jpg', - dimensions: { - width: 500, - height: 500 - } - }, - ogImage: { - url: null - }, - twitterImage: null, - ogTitle: 'Post Title', - ogDescription: 'Post meta description', - twitterTitle: 'Post Title', - twitterDescription: 'Post meta description', - authorFacebook: 'testpage', - creatorTwitter: '@twitterpage', - keywords: ['one', 'two', 'tag'], - metaDescription: 'Post meta description' - }, structuredData = getStructuredData(metadata); + const metadata = { + site: { + title: 'Site Title', + facebook: 'testuser', + twitter: '@testuser' + }, + authorName: 'Test User', + ogType: 'article', + metaTitle: 'Post Title', + canonicalUrl: 'http://mysite.com/post/my-post-slug/', + publishedDate: '2015-12-25T05:35:01.234Z', + modifiedDate: '2016-01-21T22:13:05.412Z', + coverImage: { + url: 'http://mysite.com/content/image/mypostcoverimage.jpg', + dimensions: { + width: 500, + height: 500 + } + }, + ogImage: { + url: null + }, + twitterImage: null, + ogTitle: 'Post Title', + ogDescription: 'Post meta description', + twitterTitle: 'Post Title', + twitterDescription: 'Post meta description', + authorFacebook: 'testpage', + creatorTwitter: '@twitterpage', + keywords: ['one', 'two', 'tag'], + metaDescription: 'Post meta description' + }; + + const structuredData = getStructuredData(metadata); should.deepEqual(structuredData, { 'article:modified_time': '2016-01-21T22:13:05.412Z', @@ -66,35 +68,37 @@ describe('getStructuredData', function () { }); it('should return structured data from metadata with provided og and twitter images only per post', function (done) { - var metadata = { - site: { - title: 'Site Title', - facebook: 'testuser', - twitter: '@testuser' - }, - authorName: 'Test User', - ogType: 'article', - metaTitle: 'Post Title', - canonicalUrl: 'http://mysite.com/post/my-post-slug/', - publishedDate: '2015-12-25T05:35:01.234Z', - modifiedDate: '2016-01-21T22:13:05.412Z', - ogImage: { - url: 'http://mysite.com/content/image/mypostogimage.jpg', - dimensions: { - width: 20, - height: 100 - } - }, - twitterImage: 'http://mysite.com/content/image/myposttwitterimage.jpg', - ogTitle: 'Custom Facebook title', - ogDescription: 'Custom Facebook description', - twitterTitle: 'Custom Twitter title', - twitterDescription: 'Custom Twitter description', - authorFacebook: 'testpage', - creatorTwitter: '@twitterpage', - keywords: ['one', 'two', 'tag'], - metaDescription: 'Post meta description' - }, structuredData = getStructuredData(metadata); + const metadata = { + site: { + title: 'Site Title', + facebook: 'testuser', + twitter: '@testuser' + }, + authorName: 'Test User', + ogType: 'article', + metaTitle: 'Post Title', + canonicalUrl: 'http://mysite.com/post/my-post-slug/', + publishedDate: '2015-12-25T05:35:01.234Z', + modifiedDate: '2016-01-21T22:13:05.412Z', + ogImage: { + url: 'http://mysite.com/content/image/mypostogimage.jpg', + dimensions: { + width: 20, + height: 100 + } + }, + twitterImage: 'http://mysite.com/content/image/myposttwitterimage.jpg', + ogTitle: 'Custom Facebook title', + ogDescription: 'Custom Facebook description', + twitterTitle: 'Custom Twitter title', + twitterDescription: 'Custom Twitter description', + authorFacebook: 'testpage', + creatorTwitter: '@twitterpage', + keywords: ['one', 'two', 'tag'], + metaDescription: 'Post meta description' + }; + + const structuredData = getStructuredData(metadata); should.deepEqual(structuredData, { 'article:modified_time': '2016-01-21T22:13:05.412Z', @@ -126,33 +130,35 @@ describe('getStructuredData', function () { }); it('should return structured data from metadata with no nulls', function (done) { - var metadata = { - site: { - title: 'Site Title', - facebook: '', - twitter: '' - }, - authorName: 'Test User', - ogType: 'article', - metaTitle: 'Post Title', - canonicalUrl: 'http://mysite.com/post/my-post-slug/', - modifiedDate: '2016-01-21T22:13:05.412Z', - authorFacebook: null, - creatorTwitter: null, - coverImage: { - url: undefined - }, - ogImage: { - url: null - }, - twitterImage: null, - ogTitle: 'Post Title', - ogDescription: null, - twitterTitle: 'Post Title', - twitterDescription: null, - keywords: null, - metaDescription: null - }, structuredData = getStructuredData(metadata); + const metadata = { + site: { + title: 'Site Title', + facebook: '', + twitter: '' + }, + authorName: 'Test User', + ogType: 'article', + metaTitle: 'Post Title', + canonicalUrl: 'http://mysite.com/post/my-post-slug/', + modifiedDate: '2016-01-21T22:13:05.412Z', + authorFacebook: null, + creatorTwitter: null, + coverImage: { + url: undefined + }, + ogImage: { + url: null + }, + twitterImage: null, + ogTitle: 'Post Title', + ogDescription: null, + twitterTitle: 'Post Title', + twitterDescription: null, + keywords: null, + metaDescription: null + }; + + const structuredData = getStructuredData(metadata); should.deepEqual(structuredData, { 'article:modified_time': '2016-01-21T22:13:05.412Z', diff --git a/test/unit/data/meta/title_spec.js b/test/unit/data/meta/title_spec.js index 8be8a50f83..a756a4b05c 100644 --- a/test/unit/data/meta/title_spec.js +++ b/test/unit/data/meta/title_spec.js @@ -1,10 +1,10 @@ -var should = require('should'), - sinon = require('sinon'), - getTitle = require('../../../../core/frontend/meta/title'), - settingsCache = require('../../../../core/server/services/settings/cache'); +const should = require('should'); +const sinon = require('sinon'); +const getTitle = require('../../../../core/frontend/meta/title'); +const settingsCache = require('../../../../core/server/services/settings/cache'); describe('getTitle', function () { - var localSettingsCache = {}; + let localSettingsCache = {}; beforeEach(function () { sinon.stub(settingsCache, 'get').callsFake(function (key) { @@ -18,7 +18,7 @@ describe('getTitle', function () { }); it('should return meta_title if on data root', function () { - var title = getTitle({ + const title = getTitle({ meta_title: 'My test title' }); diff --git a/test/unit/data/meta/url_spec.js b/test/unit/data/meta/url_spec.js index 5003204b66..d2e8020433 100644 --- a/test/unit/data/meta/url_spec.js +++ b/test/unit/data/meta/url_spec.js @@ -1,9 +1,9 @@ -const should = require('should'), - sinon = require('sinon'), - urlUtils = require('../../../../core/server/lib/url-utils'), - urlService = require('../../../../core/frontend/services/url'), - getUrl = require('../../../../core/frontend/meta/url'), - testUtils = require('../../../utils'); +const should = require('should'); +const sinon = require('sinon'); +const urlUtils = require('../../../../core/server/lib/url-utils'); +const urlService = require('../../../../core/frontend/services/url'); +const getUrl = require('../../../../core/frontend/meta/url'); +const testUtils = require('../../../utils'); describe('getUrl', function () { beforeEach(function () { diff --git a/test/unit/data/schema/fixtures/utils_spec.js b/test/unit/data/schema/fixtures/utils_spec.js index 88dcf167b7..8e59f3b3b1 100644 --- a/test/unit/data/schema/fixtures/utils_spec.js +++ b/test/unit/data/schema/fixtures/utils_spec.js @@ -1,15 +1,14 @@ -var should = require('should'), - sinon = require('sinon'), - Promise = require('bluebird'), - rewire = require('rewire'), - - models = require('../../../../../core/server/models'), - baseUtils = require('../../../../../core/server/models/base/utils'), - fixtureUtils = rewire('../../../../../core/server/data/schema/fixtures/utils'), - fixtures = require('../../../../../core/server/data/schema/fixtures/fixtures'); +const should = require('should'); +const sinon = require('sinon'); +const Promise = require('bluebird'); +const rewire = require('rewire'); +const models = require('../../../../../core/server/models'); +const baseUtils = require('../../../../../core/server/models/base/utils'); +const fixtureUtils = rewire('../../../../../core/server/data/schema/fixtures/utils'); +const fixtures = require('../../../../../core/server/data/schema/fixtures/fixtures'); describe('Migration Fixture Utils', function () { - var loggerStub; + let loggerStub; beforeEach(function () { loggerStub = { @@ -25,8 +24,8 @@ describe('Migration Fixture Utils', function () { }); describe('Match Func', function () { - var matchFunc = fixtureUtils.__get__('matchFunc'), - getStub; + const matchFunc = fixtureUtils.__get__('matchFunc'); + let getStub; beforeEach(function () { getStub = sinon.stub(); @@ -98,8 +97,8 @@ describe('Migration Fixture Utils', function () { describe('Add Fixtures For Model', function () { it('should call add for main post fixture', function (done) { - var postOneStub = sinon.stub(models.Post, 'findOne').returns(Promise.resolve()), - postAddStub = sinon.stub(models.Post, 'add').returns(Promise.resolve({})); + const postOneStub = sinon.stub(models.Post, 'findOne').returns(Promise.resolve()); + const postAddStub = sinon.stub(models.Post, 'add').returns(Promise.resolve({})); fixtureUtils.addFixturesForModel(fixtures.models[4]).then(function (result) { should.exist(result); @@ -115,8 +114,8 @@ describe('Migration Fixture Utils', function () { }); it('should not call add for main post fixture if it is already found', function (done) { - var postOneStub = sinon.stub(models.Post, 'findOne').returns(Promise.resolve({})), - postAddStub = sinon.stub(models.Post, 'add').returns(Promise.resolve({})); + const postOneStub = sinon.stub(models.Post, 'findOne').returns(Promise.resolve({})); + const postAddStub = sinon.stub(models.Post, 'add').returns(Promise.resolve({})); fixtureUtils.addFixturesForModel(fixtures.models[4]).then(function (result) { should.exist(result); @@ -134,18 +133,21 @@ describe('Migration Fixture Utils', function () { describe('Add Fixtures For Relation', function () { it('should call attach for permissions-roles', function (done) { - var fromItem = { - related: sinon.stub().returnsThis(), - findWhere: sinon.stub().returns() - }, - toItem = [{get: sinon.stub()}], - dataMethodStub = { - filter: sinon.stub().returns(toItem), - find: sinon.stub().returns(fromItem) - }, - baseUtilAttachStub = sinon.stub(baseUtils, 'attach').returns(Promise.resolve([{}])), - permsAllStub = sinon.stub(models.Permission, 'findAll').returns(Promise.resolve(dataMethodStub)), - rolesAllStub = sinon.stub(models.Role, 'findAll').returns(Promise.resolve(dataMethodStub)); + const fromItem = { + related: sinon.stub().returnsThis(), + findWhere: sinon.stub().returns() + }; + + const toItem = [{get: sinon.stub()}]; + + const dataMethodStub = { + filter: sinon.stub().returns(toItem), + find: sinon.stub().returns(fromItem) + }; + + const baseUtilAttachStub = sinon.stub(baseUtils, 'attach').returns(Promise.resolve([{}])); + const permsAllStub = sinon.stub(models.Permission, 'findAll').returns(Promise.resolve(dataMethodStub)); + const rolesAllStub = sinon.stub(models.Role, 'findAll').returns(Promise.resolve(dataMethodStub)); fixtureUtils.addFixturesForRelation(fixtures.relations[0]).then(function (result) { should.exist(result); @@ -169,18 +171,21 @@ describe('Migration Fixture Utils', function () { }); it('should call attach for posts-tags', function (done) { - var fromItem = { - related: sinon.stub().returnsThis(), - findWhere: sinon.stub().returns() - }, - toItem = [{get: sinon.stub()}], - dataMethodStub = { - filter: sinon.stub().returns(toItem), - find: sinon.stub().returns(fromItem) - }, - baseUtilAttachStub = sinon.stub(baseUtils, 'attach').returns(Promise.resolve([{}])), - postsAllStub = sinon.stub(models.Post, 'findAll').returns(Promise.resolve(dataMethodStub)), - tagsAllStub = sinon.stub(models.Tag, 'findAll').returns(Promise.resolve(dataMethodStub)); + const fromItem = { + related: sinon.stub().returnsThis(), + findWhere: sinon.stub().returns() + }; + + const toItem = [{get: sinon.stub()}]; + + const dataMethodStub = { + filter: sinon.stub().returns(toItem), + find: sinon.stub().returns(fromItem) + }; + + const baseUtilAttachStub = sinon.stub(baseUtils, 'attach').returns(Promise.resolve([{}])); + const postsAllStub = sinon.stub(models.Post, 'findAll').returns(Promise.resolve(dataMethodStub)); + const tagsAllStub = sinon.stub(models.Tag, 'findAll').returns(Promise.resolve(dataMethodStub)); fixtureUtils.addFixturesForRelation(fixtures.relations[1]).then(function (result) { should.exist(result); @@ -203,20 +208,22 @@ describe('Migration Fixture Utils', function () { }); it('will not call attach for posts-tags if already present', function (done) { - var fromItem = { - related: sinon.stub().returnsThis(), - findWhere: sinon.stub().returns({}), - tags: sinon.stub().returnsThis(), - attach: sinon.stub().returns(Promise.resolve({})) - }, - toItem = [{get: sinon.stub()}], - dataMethodStub = { - filter: sinon.stub().returns(toItem), - find: sinon.stub().returns(fromItem) - }, + const fromItem = { + related: sinon.stub().returnsThis(), + findWhere: sinon.stub().returns({}), + tags: sinon.stub().returnsThis(), + attach: sinon.stub().returns(Promise.resolve({})) + }; - postsAllStub = sinon.stub(models.Post, 'findAll').returns(Promise.resolve(dataMethodStub)), - tagsAllStub = sinon.stub(models.Tag, 'findAll').returns(Promise.resolve(dataMethodStub)); + const toItem = [{get: sinon.stub()}]; + + const dataMethodStub = { + filter: sinon.stub().returns(toItem), + find: sinon.stub().returns(fromItem) + }; + + const postsAllStub = sinon.stub(models.Post, 'findAll').returns(Promise.resolve(dataMethodStub)); + const tagsAllStub = sinon.stub(models.Tag, 'findAll').returns(Promise.resolve(dataMethodStub)); fixtureUtils.addFixturesForRelation(fixtures.relations[1]).then(function (result) { should.exist(result); @@ -244,7 +251,7 @@ describe('Migration Fixture Utils', function () { describe('findModelFixtureEntry', function () { it('should fetch a single fixture entry', function () { - var foundFixture = fixtureUtils.findModelFixtureEntry('Integration', {slug: 'zapier'}); + const foundFixture = fixtureUtils.findModelFixtureEntry('Integration', {slug: 'zapier'}); foundFixture.should.be.an.Object(); foundFixture.should.eql({ slug: 'zapier', @@ -258,7 +265,7 @@ describe('Migration Fixture Utils', function () { describe('findModelFixtures', function () { it('should fetch a fixture with multiple entries', function () { - var foundFixture = fixtureUtils.findModelFixtures('Permission', {object_type: 'db'}); + const foundFixture = fixtureUtils.findModelFixtures('Permission', {object_type: 'db'}); foundFixture.should.be.an.Object(); foundFixture.entries.should.be.an.Array().with.lengthOf(4); foundFixture.entries[0].should.eql({ @@ -276,7 +283,7 @@ describe('Migration Fixture Utils', function () { describe('findPermissionRelationsForObject', function () { it('should fetch a fixture with multiple entries', function () { - var foundFixture = fixtureUtils.findPermissionRelationsForObject('db'); + const foundFixture = fixtureUtils.findPermissionRelationsForObject('db'); foundFixture.should.be.an.Object(); foundFixture.entries.should.be.an.Object(); foundFixture.entries.should.have.property('Administrator', {db: 'all'}); diff --git a/test/unit/data/schema/integrity_spec.js b/test/unit/data/schema/integrity_spec.js index f63440d0ba..61d359a7fd 100644 --- a/test/unit/data/schema/integrity_spec.js +++ b/test/unit/data/schema/integrity_spec.js @@ -1,8 +1,8 @@ -var should = require('should'), - _ = require('lodash'), - crypto = require('crypto'), - schema = require('../../../../core/server/data/schema'), - fixtures = require('../../../../core/server/data/schema/fixtures'); +const should = require('should'); +const _ = require('lodash'); +const crypto = require('crypto'); +const schema = require('../../../../core/server/data/schema'); +const fixtures = require('../../../../core/server/data/schema/fixtures'); /** * @NOTE @@ -25,9 +25,9 @@ describe('DB version integrity', function () { // If this test is failing, then it is likely a change has been made that requires a DB version bump, // and the values above will need updating as confirmation it('should not change without fixing this test', function () { - var tablesNoValidation = _.cloneDeep(schema.tables), - schemaHash, - fixturesHash; + const tablesNoValidation = _.cloneDeep(schema.tables); + let schemaHash; + let fixturesHash; _.each(tablesNoValidation, function (table) { return _.each(table, function (column, name) { diff --git a/test/unit/data/validation/index_spec.js b/test/unit/data/validation/index_spec.js index 43629cd61a..10360776ac 100644 --- a/test/unit/data/validation/index_spec.js +++ b/test/unit/data/validation/index_spec.js @@ -1,9 +1,9 @@ -var should = require('should'), - _ = require('lodash'), - ObjectId = require('bson-objectid'), - testUtils = require('../../../utils'), - models = require('../../../../core/server/models'), - validation = require('../../../../core/server/data/validation'); +const should = require('should'); +const _ = require('lodash'); +const ObjectId = require('bson-objectid'); +const testUtils = require('../../../utils'); +const models = require('../../../../core/server/models'); +const validation = require('../../../../core/server/data/validation'); // Validate our customisations describe('Validation', function () { @@ -163,7 +163,7 @@ describe('Validation', function () { }); describe('Assert the Validator dependency', function () { - var validator = validation.validator; + const validator = validation.validator; it('isEmptyOrUrl filters javascript urls', function () { validator.isEmptyOrURL('javascript:alert(0)').should.be.false(); diff --git a/test/unit/data/xml/sitemap/generator_spec.js b/test/unit/data/xml/sitemap/generator_spec.js index 604abe9d34..ff3fc6175e 100644 --- a/test/unit/data/xml/sitemap/generator_spec.js +++ b/test/unit/data/xml/sitemap/generator_spec.js @@ -1,14 +1,14 @@ -const should = require('should'), - sinon = require('sinon'), - ObjectId = require('bson-objectid'), - _ = require('lodash'), - testUtils = require('../../../../utils'), - urlUtils = require('../../../../../core/server/lib/url-utils'), - IndexGenerator = require('../../../../../core/frontend/services/sitemap/index-generator'), - PostGenerator = require('../../../../../core/frontend/services/sitemap/post-generator'), - PageGenerator = require('../../../../../core/frontend/services/sitemap/page-generator'), - TagGenerator = require('../../../../../core/frontend/services/sitemap/tag-generator'), - UserGenerator = require('../../../../../core/frontend/services/sitemap/user-generator'); +const should = require('should'); +const sinon = require('sinon'); +const ObjectId = require('bson-objectid'); +const _ = require('lodash'); +const testUtils = require('../../../../utils'); +const urlUtils = require('../../../../../core/server/lib/url-utils'); +const IndexGenerator = require('../../../../../core/frontend/services/sitemap/index-generator'); +const PostGenerator = require('../../../../../core/frontend/services/sitemap/post-generator'); +const PageGenerator = require('../../../../../core/frontend/services/sitemap/page-generator'); +const TagGenerator = require('../../../../../core/frontend/services/sitemap/tag-generator'); +const UserGenerator = require('../../../../../core/frontend/services/sitemap/user-generator'); should.Assertion.add('ValidUrlNode', function (options) { // Check urlNode looks correct @@ -107,7 +107,9 @@ describe('Generators', function () { }); it('compare content output', function () { - let idxFirst, idxSecond, idxThird; + let idxFirst; + let idxSecond; + let idxThird; urlUtils.urlFor.withArgs('image', {image: 'post-100.jpg'}, true).returns('http://my-ghost-blog.com/images/post-100.jpg'); urlUtils.urlFor.withArgs('image', {image: 'post-200.jpg'}, true).returns('http://my-ghost-blog.com/images/post-200.jpg'); diff --git a/test/unit/data/xml/sitemap/manager_spec.js b/test/unit/data/xml/sitemap/manager_spec.js index 452df88a7f..943c066781 100644 --- a/test/unit/data/xml/sitemap/manager_spec.js +++ b/test/unit/data/xml/sitemap/manager_spec.js @@ -1,20 +1,25 @@ -const should = require('should'), - sinon = require('sinon'), +const should = require('should'); +const sinon = require('sinon'); - // Stuff we are testing - common = require('../../../../../core/server/lib/common'), - SiteMapManager = require('../../../../../core/frontend/services/sitemap/manager'), - PostGenerator = require('../../../../../core/frontend/services/sitemap/post-generator'), - PageGenerator = require('../../../../../core/frontend/services/sitemap/page-generator'), - TagGenerator = require('../../../../../core/frontend/services/sitemap/tag-generator'), - UserGenerator = require('../../../../../core/frontend/services/sitemap/user-generator'), - IndexGenerator = require('../../../../../core/frontend/services/sitemap/index-generator'); +// Stuff we are testing +const common = require('../../../../../core/server/lib/common'); + +const SiteMapManager = require('../../../../../core/frontend/services/sitemap/manager'); +const PostGenerator = require('../../../../../core/frontend/services/sitemap/post-generator'); +const PageGenerator = require('../../../../../core/frontend/services/sitemap/page-generator'); +const TagGenerator = require('../../../../../core/frontend/services/sitemap/tag-generator'); +const UserGenerator = require('../../../../../core/frontend/services/sitemap/user-generator'); +const IndexGenerator = require('../../../../../core/frontend/services/sitemap/index-generator'); describe('Unit: sitemap/manager', function () { let eventsToRemember; const makeStubManager = function () { - let posts, pages, tags, authors, index; + let posts; + let pages; + let tags; + let authors; + let index; index = new IndexGenerator(); posts = new PostGenerator(); @@ -43,7 +48,8 @@ describe('Unit: sitemap/manager', function () { }); describe('SiteMapManager', function () { - let manager, fake; + let manager; + let fake; beforeEach(function () { manager = makeStubManager(); diff --git a/test/unit/helpers/asset_spec.js b/test/unit/helpers/asset_spec.js index b8d73293c3..0e29ca503f 100644 --- a/test/unit/helpers/asset_spec.js +++ b/test/unit/helpers/asset_spec.js @@ -1,14 +1,16 @@ // NOTE: the sole purpose of this suite is to test is it calls through to getAssetUrlHelper // more complicated use cases are tested directly in asset_url.spec -var should = require('should'), - sinon = require('sinon'), - configUtils = require('../../utils/configUtils'), - helpers = require('../../../core/frontend/helpers'), - settingsCache = require('../../../core/server/services/settings/cache'); +const should = require('should'); + +const sinon = require('sinon'); +const configUtils = require('../../utils/configUtils'); +const helpers = require('../../../core/frontend/helpers'); +const settingsCache = require('../../../core/server/services/settings/cache'); describe('{{asset}} helper', function () { - var rendered, localSettingsCache = {}; + let rendered; + const localSettingsCache = {}; before(function () { configUtils.set({assetHash: 'abc'}); diff --git a/test/unit/helpers/author_spec.js b/test/unit/helpers/author_spec.js index d086f1e62a..7cc70a3bea 100644 --- a/test/unit/helpers/author_spec.js +++ b/test/unit/helpers/author_spec.js @@ -1,8 +1,8 @@ -const should = require('should'), - sinon = require('sinon'), - testUtils = require('../../utils'), - urlService = require('../../../core/frontend/services/url'), - helpers = require('../../../core/frontend/helpers'); +const should = require('should'); +const sinon = require('sinon'); +const testUtils = require('../../utils'); +const urlService = require('../../../core/frontend/services/url'); +const helpers = require('../../../core/frontend/helpers'); describe('{{author}} helper', function () { beforeEach(function () { diff --git a/test/unit/helpers/authors_spec.js b/test/unit/helpers/authors_spec.js index 075c3b5608..c67983f282 100644 --- a/test/unit/helpers/authors_spec.js +++ b/test/unit/helpers/authors_spec.js @@ -1,9 +1,9 @@ -const should = require('should'), - sinon = require('sinon'), - urlService = require('../../../core/frontend/services/url'), - helpers = require('../../../core/frontend/helpers'), - models = require('../../../core/server/models'), - testUtils = require('../../utils'); +const should = require('should'); +const sinon = require('sinon'); +const urlService = require('../../../core/frontend/services/url'); +const helpers = require('../../../core/frontend/helpers'); +const models = require('../../../core/server/models'); +const testUtils = require('../../utils'); describe('{{authors}} helper', function () { before(function () { diff --git a/test/unit/helpers/body_class_spec.js b/test/unit/helpers/body_class_spec.js index d205369e40..cd6be1b806 100644 --- a/test/unit/helpers/body_class_spec.js +++ b/test/unit/helpers/body_class_spec.js @@ -1,11 +1,11 @@ -var should = require('should'), - themeList = require('../../../core/frontend/services/themes/list'), +const should = require('should'); +const themeList = require('../../../core/frontend/services/themes/list'); - // Stuff we are testing - helpers = require('../../../core/frontend/helpers'); +// Stuff we are testing +const helpers = require('../../../core/frontend/helpers'); describe('{{body_class}} helper', function () { - var options = {}; + let options = {}; before(function () { themeList.init({ casper: { @@ -37,7 +37,7 @@ describe('{{body_class}} helper', function () { it('can render class string', function () { options.data.root.context = ['home']; - var rendered = helpers.body_class.call({}, options); + const rendered = helpers.body_class.call({}, options); should.exist(rendered); rendered.string.should.equal('home-template'); @@ -53,7 +53,7 @@ describe('{{body_class}} helper', function () { } it('Standard home page', function () { - var rendered = callBodyClassWithContext( + const rendered = callBodyClassWithContext( ['home', 'index'], {relativeUrl: '/'} ); @@ -62,7 +62,7 @@ describe('{{body_class}} helper', function () { }); it('a post', function () { - var rendered = callBodyClassWithContext( + const rendered = callBodyClassWithContext( ['post'], {relativeUrl: '/a-post-title', post: {}} ); @@ -71,7 +71,7 @@ describe('{{body_class}} helper', function () { }); it('paginated index', function () { - var rendered = callBodyClassWithContext( + const rendered = callBodyClassWithContext( ['index', 'paged'], {relativeUrl: '/page/4'} ); @@ -80,7 +80,7 @@ describe('{{body_class}} helper', function () { }); it('tag page', function () { - var rendered = callBodyClassWithContext( + const rendered = callBodyClassWithContext( ['tag'], {relativeUrl: '/tag/foo', tag: {slug: 'foo'}} ); @@ -89,7 +89,7 @@ describe('{{body_class}} helper', function () { }); it('paginated tag page', function () { - var rendered = callBodyClassWithContext( + const rendered = callBodyClassWithContext( ['tag', 'paged'], {relativeUrl: '/tag/foo/page/2', tag: {slug: 'foo'}} ); @@ -98,7 +98,7 @@ describe('{{body_class}} helper', function () { }); it('author page', function () { - var rendered = callBodyClassWithContext( + const rendered = callBodyClassWithContext( ['author'], {relativeUrl: '/author/bar', author: {slug: 'bar'}} ); @@ -107,7 +107,7 @@ describe('{{body_class}} helper', function () { }); it('paginated author page', function () { - var rendered = callBodyClassWithContext( + const rendered = callBodyClassWithContext( ['author', 'paged'], {relativeUrl: '/author/bar/page/2', author: {slug: 'bar'}} ); @@ -116,7 +116,7 @@ describe('{{body_class}} helper', function () { }); it('private route for password protection', function () { - var rendered = callBodyClassWithContext( + const rendered = callBodyClassWithContext( ['private'], {relativeUrl: '/private/'} ); @@ -125,7 +125,7 @@ describe('{{body_class}} helper', function () { }); it('post with tags', function () { - var rendered = callBodyClassWithContext( + const rendered = callBodyClassWithContext( ['post'], {relativeUrl: '/my-awesome-post/', post: {tags: [{slug: 'foo'}, {slug: 'bar'}]}} ); @@ -134,7 +134,7 @@ describe('{{body_class}} helper', function () { }); it('v2: a static page', function () { - var rendered = callBodyClassWithContext( + const rendered = callBodyClassWithContext( ['page'], {relativeUrl: '/about', page: {page: true, slug: 'about'}} ); @@ -143,7 +143,7 @@ describe('{{body_class}} helper', function () { }); it('canary: a static page', function () { - var rendered = callBodyClassWithContext( + const rendered = callBodyClassWithContext( ['page'], {relativeUrl: '/about', page: {page: true, slug: 'about'}} ); @@ -152,7 +152,7 @@ describe('{{body_class}} helper', function () { }); it('v3: a static page', function () { - var rendered = callBodyClassWithContext( + const rendered = callBodyClassWithContext( ['page'], {relativeUrl: '/about', page: {page: true, slug: 'about'}} ); @@ -161,7 +161,7 @@ describe('{{body_class}} helper', function () { }); it('a static page with custom template (is now the same as one without)', function () { - var rendered = callBodyClassWithContext( + const rendered = callBodyClassWithContext( ['page'], {relativeUrl: '/about', post: {page: true, slug: 'about'}} ); diff --git a/test/unit/helpers/content_spec.js b/test/unit/helpers/content_spec.js index 05a9f98cb5..9b4eaaf7ce 100644 --- a/test/unit/helpers/content_spec.js +++ b/test/unit/helpers/content_spec.js @@ -1,62 +1,65 @@ -var should = require('should'), +const should = require('should'); - // Stuff we are testing - helpers = require('../../../core/frontend/helpers'); +// Stuff we are testing +const helpers = require('../../../core/frontend/helpers'); describe('{{content}} helper', function () { it('renders empty string when null', function () { - var html = null, - rendered = helpers.content.call({html: html}); + const html = null; + const rendered = helpers.content.call({html: html}); should.exist(rendered); rendered.string.should.equal(''); }); it('can render content', function () { - var html = 'Hello World', - rendered = helpers.content.call({html: html}); + const html = 'Hello World'; + const rendered = helpers.content.call({html: html}); should.exist(rendered); rendered.string.should.equal(html); }); it('can truncate html by word', function () { - var html = '

Hello World! It\'s me!

', - rendered = ( - helpers.content - .call( - {html: html}, - {hash: {words: 2}} - ) - ); + const html = '

Hello World! It\'s me!

'; + + const rendered = ( + helpers.content + .call( + {html: html}, + {hash: {words: 2}} + ) + ); should.exist(rendered); rendered.string.should.equal('

Hello World!

'); }); it('can truncate html to 0 words', function () { - var html = '

Hello World! It\'s me!

', - rendered = ( - helpers.content - .call( - {html: html}, - {hash: {words: '0'}} - ) - ); + const html = '

Hello World! It\'s me!

'; + + const rendered = ( + helpers.content + .call( + {html: html}, + {hash: {words: '0'}} + ) + ); should.exist(rendered); rendered.string.should.equal(''); }); it('can truncate html by character', function () { - var html = '

Hello World! It\'s me!

', - rendered = ( - helpers.content - .call( - {html: html}, - {hash: {characters: 8}} - ) - ); + const html = '

Hello World! It\'s me!

'; + + const rendered = ( + helpers.content + .call( + {html: html}, + {hash: {characters: 8}} + ) + ); should.exist(rendered); rendered.string.should.equal('

Hello Wo

'); diff --git a/test/unit/helpers/date_spec.js b/test/unit/helpers/date_spec.js index 0b72518b39..5d63b99e83 100644 --- a/test/unit/helpers/date_spec.js +++ b/test/unit/helpers/date_spec.js @@ -1,32 +1,35 @@ -var should = require('should'), +const should = require('should'); - // Stuff we are testing - helpers = require('../../../core/frontend/helpers'), - moment = require('moment-timezone'); +// Stuff we are testing +const helpers = require('../../../core/frontend/helpers'); + +const moment = require('moment-timezone'); describe('{{date}} helper', function () { it('creates properly formatted date strings', function () { - var testDates = [ - '2013-12-31T11:28:58.593+02:00', - '2014-01-01T01:28:58.593+11:00', - '2014-02-20T01:28:58.593-04:00', - '2014-03-01T01:28:58.593+00:00' - ], - timezones = 'Europe/Dublin', - format = 'MMM Do, YYYY', - context = { - hash: { - format: format - }, - data: { - site: { - timezone: 'Europe/Dublin' - } + const testDates = [ + '2013-12-31T11:28:58.593+02:00', + '2014-01-01T01:28:58.593+11:00', + '2014-02-20T01:28:58.593-04:00', + '2014-03-01T01:28:58.593+00:00' + ]; + + const timezones = 'Europe/Dublin'; + const format = 'MMM Do, YYYY'; + + const context = { + hash: { + format: format + }, + data: { + site: { + timezone: 'Europe/Dublin' } - }; + } + }; testDates.forEach(function (d) { - var rendered = helpers.date.call({published_at: d}, context); + const rendered = helpers.date.call({published_at: d}, context); should.exist(rendered); String(rendered).should.equal(moment(d).tz(timezones).format(format)); @@ -34,27 +37,29 @@ describe('{{date}} helper', function () { }); it('creates properly formatted time ago date strings', function () { - var testDates = [ - '2013-12-31T23:58:58.593+02:00', - '2014-01-01T00:28:58.593+11:00', - '2014-11-20T01:28:58.593-04:00', - '2014-03-01T01:28:58.593+00:00' - ], - timezones = 'Europe/Dublin', - timeNow = moment().tz('Europe/Dublin'), - context = { - hash: { - timeago: true - }, - data: { - site: { - timezone: 'Europe/Dublin' - } + const testDates = [ + '2013-12-31T23:58:58.593+02:00', + '2014-01-01T00:28:58.593+11:00', + '2014-11-20T01:28:58.593-04:00', + '2014-03-01T01:28:58.593+00:00' + ]; + + const timezones = 'Europe/Dublin'; + const timeNow = moment().tz('Europe/Dublin'); + + const context = { + hash: { + timeago: true + }, + data: { + site: { + timezone: 'Europe/Dublin' } - }; + } + }; testDates.forEach(function (d) { - var rendered = helpers.date.call({published_at: d}, context); + const rendered = helpers.date.call({published_at: d}, context); should.exist(rendered); String(rendered).should.equal(moment(d).tz(timezones).from(timeNow)); diff --git a/test/unit/helpers/encode_spec.js b/test/unit/helpers/encode_spec.js index c8b17b1c4c..0d4e8b529b 100644 --- a/test/unit/helpers/encode_spec.js +++ b/test/unit/helpers/encode_spec.js @@ -1,13 +1,13 @@ -var should = require('should'), +const should = require('should'); - // Stuff we are testing - helpers = require('../../../core/frontend/helpers'); +// Stuff we are testing +const helpers = require('../../../core/frontend/helpers'); describe('{{encode}} helper', function () { it('can escape URI', function () { - var uri = '$pecial!Charact3r(De[iver]y)Foo #Bar', - expected = '%24pecial!Charact3r(De%5Biver%5Dy)Foo%20%23Bar', - escaped = helpers.encode(uri); + const uri = '$pecial!Charact3r(De[iver]y)Foo #Bar'; + const expected = '%24pecial!Charact3r(De%5Biver%5Dy)Foo%20%23Bar'; + const escaped = helpers.encode(uri); should.exist(escaped); String(escaped).should.equal(expected); diff --git a/test/unit/helpers/excerpt_spec.js b/test/unit/helpers/excerpt_spec.js index 747b7cde92..3dad98139b 100644 --- a/test/unit/helpers/excerpt_spec.js +++ b/test/unit/helpers/excerpt_spec.js @@ -1,7 +1,7 @@ -const should = require('should'), +const should = require('should'); - // Stuff we are testing - helpers = require('../../../core/frontend/helpers'); +// Stuff we are testing +const helpers = require('../../../core/frontend/helpers'); describe('{{excerpt}} Helper', function () { it('renders empty string when html, excerpt, and custom_excerpt are null', function () { @@ -17,23 +17,23 @@ describe('{{excerpt}} Helper', function () { }); it('can render custom_excerpt', function () { - const html = 'Hello World', - rendered = helpers.excerpt.call({ - html: html, - custom_excerpt: '' - }); + const html = 'Hello World'; + const rendered = helpers.excerpt.call({ + html: html, + custom_excerpt: '' + }); should.exist(rendered); rendered.string.should.equal(html); }); it('can render excerpt when other fields are empty', function () { - const html = '', - rendered = helpers.excerpt.call({ - html: html, - custom_excerpt: '', - excerpt: 'Regular excerpt' - }); + const html = ''; + const rendered = helpers.excerpt.call({ + html: html, + custom_excerpt: '', + excerpt: 'Regular excerpt' + }); should.exist(rendered); rendered.string.should.equal('Regular excerpt'); @@ -43,25 +43,25 @@ describe('{{excerpt}} Helper', function () { const html = '

There are
10
types
of people in the world:' + 'c those who ' + 'understand trinary,

those who don\'t
and' + - '< test > those<<< test >>> who mistake it <for> binary.', - expected = 'There are 10 types of people in the world: those who understand trinary, those who ' + - 'don\'t and those>> who mistake it <for> binary.', - rendered = helpers.excerpt.call({ - html: html, - custom_excerpt: '' - }); + '< test > those<<< test >>> who mistake it <for> binary.'; + const expected = 'There are 10 types of people in the world: those who understand trinary, those who ' + + 'don\'t and those>> who mistake it <for> binary.'; + const rendered = helpers.excerpt.call({ + html: html, + custom_excerpt: '' + }); should.exist(rendered); rendered.string.should.equal(expected); }); it('strips multiple inline footnotes', function () { - const html = '

Testing1, my footnotes. And stuff. Footnote2with a link right after.', - expected = 'Testing, my footnotes. And stuff. Footnotewith a link right after.', - rendered = helpers.excerpt.call({ - html: html, - custom_excerpt: '' - }); + const html = '

Testing1, my footnotes. And stuff. Footnote2with a link right after.'; + const expected = 'Testing, my footnotes. And stuff. Footnotewith a link right after.'; + const rendered = helpers.excerpt.call({ + html: html, + custom_excerpt: '' + }); should.exist(rendered); rendered.string.should.equal(expected); @@ -69,160 +69,160 @@ describe('{{excerpt}} Helper', function () { it('strips inline and bottom footnotes', function () { const html = '

Testing1 a very short post with a single footnote.

\n' + - '', - expected = 'Testing a very short post with a single footnote.', - rendered = helpers.excerpt.call({ - html: html, - custom_excerpt: '' - }); + ''; + const expected = 'Testing a very short post with a single footnote.'; + const rendered = helpers.excerpt.call({ + html: html, + custom_excerpt: '' + }); should.exist(rendered); rendered.string.should.equal(expected); }); it('can truncate html by word', function () { - const html = '

Hello World! It\'s me!

', - expected = 'Hello World!', - rendered = ( - helpers.excerpt.call( - { - html: html, - custom_excerpt: '' - }, - {hash: {words: '2'}} - ) - ); + const html = '

Hello World! It\'s me!

'; + const expected = 'Hello World!'; + const rendered = ( + helpers.excerpt.call( + { + html: html, + custom_excerpt: '' + }, + {hash: {words: '2'}} + ) + ); should.exist(rendered); rendered.string.should.equal(expected); }); it('can truncate html with non-ascii characters by word', function () { - const html = '

Едквюэ опортэат праэчынт ючю но, квуй эю

', - expected = 'Едквюэ опортэат', - rendered = ( - helpers.excerpt.call( - { - html: html, - custom_excerpt: '' - }, - {hash: {words: '2'}} - ) - ); + const html = '

Едквюэ опортэат праэчынт ючю но, квуй эю

'; + const expected = 'Едквюэ опортэат'; + const rendered = ( + helpers.excerpt.call( + { + html: html, + custom_excerpt: '' + }, + {hash: {words: '2'}} + ) + ); should.exist(rendered); rendered.string.should.equal(expected); }); it('can truncate html by character', function () { - const html = '

Hello World! It\'s me!

', - expected = 'Hello Wo', - rendered = ( - helpers.excerpt.call( - { - html: html, - custom_excerpt: '' - }, - {hash: {characters: '8'}} - ) - ); + const html = '

Hello World! It\'s me!

'; + const expected = 'Hello Wo'; + const rendered = ( + helpers.excerpt.call( + { + html: html, + custom_excerpt: '' + }, + {hash: {characters: '8'}} + ) + ); should.exist(rendered); rendered.string.should.equal(expected); }); it('uses custom_excerpt if provided instead of truncating html', function () { - const html = '

Hello World! It\'s me!

', - customExcerpt = 'My Custom Excerpt wins!', - expected = 'My Custom Excerpt wins!', - rendered = ( - helpers.excerpt.call( - { - html: html, - custom_excerpt: customExcerpt - } - ) - ); + const html = '

Hello World! It\'s me!

'; + const customExcerpt = 'My Custom Excerpt wins!'; + const expected = 'My Custom Excerpt wins!'; + const rendered = ( + helpers.excerpt.call( + { + html: html, + custom_excerpt: customExcerpt + } + ) + ); should.exist(rendered); rendered.string.should.equal(expected); }); it('does not truncate custom_excerpt if characters options is provided', function () { - const html = '

Hello World! It\'s me!

', - customExcerpt = 'This is a custom excerpt. It should always be rendered in full length and not being cut ' + - 'off. The maximum length of a custom excerpt is 300 characters. Enough to tell a bit about ' + - 'your story and make a nice summary for your readers. It\s only allowed to truncate anything ' + - 'after 300 characters. This give', - expected = 'This is a custom excerpt. It should always be rendered in full length and not being cut ' + - 'off. The maximum length of a custom excerpt is 300 characters. Enough to tell a bit about ' + - 'your story and make a nice summary for your readers. It\s only allowed to truncate anything ' + - 'after 300 characters. This give', - rendered = ( - helpers.excerpt.call( - { - html: html, - custom_excerpt: customExcerpt - }, - {hash: {characters: '8'}} - ) - ); + const html = '

Hello World! It\'s me!

'; + const customExcerpt = 'This is a custom excerpt. It should always be rendered in full length and not being cut ' + + 'off. The maximum length of a custom excerpt is 300 characters. Enough to tell a bit about ' + + 'your story and make a nice summary for your readers. It\s only allowed to truncate anything ' + + 'after 300 characters. This give'; + const expected = 'This is a custom excerpt. It should always be rendered in full length and not being cut ' + + 'off. The maximum length of a custom excerpt is 300 characters. Enough to tell a bit about ' + + 'your story and make a nice summary for your readers. It\s only allowed to truncate anything ' + + 'after 300 characters. This give'; + const rendered = ( + helpers.excerpt.call( + { + html: html, + custom_excerpt: customExcerpt + }, + {hash: {characters: '8'}} + ) + ); should.exist(rendered); rendered.string.should.equal(expected); }); it('does not truncate custom_excerpt if words options is provided', function () { - const html = '

Hello World! It\'s me!

', - customExcerpt = 'This is a custom excerpt. It should always be rendered in full length and not being cut ' + - 'off. The maximum length of a custom excerpt is 300 characters. Enough to tell a bit about ' + - 'your story and make a nice summary for your readers. It\s only allowed to truncate anything ' + - 'after 300 characters. This give', - expected = 'This is a custom excerpt. It should always be rendered in full length and not being cut ' + - 'off. The maximum length of a custom excerpt is 300 characters. Enough to tell a bit about ' + - 'your story and make a nice summary for your readers. It\s only allowed to truncate anything ' + - 'after 300 characters. This give', - rendered = ( - helpers.excerpt.call( - { - html: html, - custom_excerpt: customExcerpt - }, - {hash: {words: '10'}} - ) - ); + const html = '

Hello World! It\'s me!

'; + const customExcerpt = 'This is a custom excerpt. It should always be rendered in full length and not being cut ' + + 'off. The maximum length of a custom excerpt is 300 characters. Enough to tell a bit about ' + + 'your story and make a nice summary for your readers. It\s only allowed to truncate anything ' + + 'after 300 characters. This give'; + const expected = 'This is a custom excerpt. It should always be rendered in full length and not being cut ' + + 'off. The maximum length of a custom excerpt is 300 characters. Enough to tell a bit about ' + + 'your story and make a nice summary for your readers. It\s only allowed to truncate anything ' + + 'after 300 characters. This give'; + const rendered = ( + helpers.excerpt.call( + { + html: html, + custom_excerpt: customExcerpt + }, + {hash: {words: '10'}} + ) + ); should.exist(rendered); rendered.string.should.equal(expected); }); it('puts additional space after closing paragraph', function () { - const html = '

Testing.

Space before this text.

And this as well!

', - expected = 'Testing. Space before this text. And this as well!', - rendered = ( - helpers.excerpt.call( - { - html: html, - custom_excerpt: '' - } - ) - ); + const html = '

Testing.

Space before this text.

And this as well!

'; + const expected = 'Testing. Space before this text. And this as well!'; + const rendered = ( + helpers.excerpt.call( + { + html: html, + custom_excerpt: '' + } + ) + ); should.exist(rendered); rendered.string.should.equal(expected); }); it('puts additional space instead of
tag', function () { - const html = '

Testing.
Space before this text.
And this as well!

', - expected = 'Testing. Space before this text. And this as well!', - rendered = ( - helpers.excerpt.call( - { - html: html, - custom_excerpt: '' - } - ) - ); + const html = '

Testing.
Space before this text.
And this as well!

'; + const expected = 'Testing. Space before this text. And this as well!'; + const rendered = ( + helpers.excerpt.call( + { + html: html, + custom_excerpt: '' + } + ) + ); should.exist(rendered); rendered.string.should.equal(expected); @@ -231,16 +231,16 @@ describe('{{excerpt}} Helper', function () { it('puts additional space between paragraph in markup generated by Ghost', function () { const html = '

put space in excerpt.

before this paragraph.

' + '
' + - '

and skip the image.

', - expected = 'put space in excerpt. before this paragraph. and skip the image.', - rendered = ( - helpers.excerpt.call( - { - html: html, - custom_excerpt: '' - } - ) - ); + '

and skip the image.

'; + const expected = 'put space in excerpt. before this paragraph. and skip the image.'; + const rendered = ( + helpers.excerpt.call( + { + html: html, + custom_excerpt: '' + } + ) + ); should.exist(rendered); rendered.string.should.equal(expected); diff --git a/test/unit/helpers/facebook_url_spec.js b/test/unit/helpers/facebook_url_spec.js index d50243234f..b90bbf150d 100644 --- a/test/unit/helpers/facebook_url_spec.js +++ b/test/unit/helpers/facebook_url_spec.js @@ -1,10 +1,10 @@ -var should = require('should'), +const should = require('should'); - // Stuff we are testing - helpers = require('../../../core/frontend/helpers'); +// Stuff we are testing +const helpers = require('../../../core/frontend/helpers'); describe('{{facebook_url}} helper', function () { - var options = {data: {site: {}}}; + const options = {data: {site: {}}}; beforeEach(function () { options.data.site = {facebook: ''}; diff --git a/test/unit/helpers/foreach_spec.js b/test/unit/helpers/foreach_spec.js index 2eeecdec64..3238330c7d 100644 --- a/test/unit/helpers/foreach_spec.js +++ b/test/unit/helpers/foreach_spec.js @@ -1,11 +1,14 @@ -var should = require('should'), - sinon = require('sinon'), - _ = require('lodash'), - helpers = require('../../../core/frontend/helpers'), - handlebars = require('../../../core/frontend/services/themes/engine').handlebars; +const should = require('should'); +const sinon = require('sinon'); +const _ = require('lodash'); +const helpers = require('../../../core/frontend/helpers'); +const handlebars = require('../../../core/frontend/services/themes/engine').handlebars; describe('{{#foreach}} helper', function () { - var options, context, _this, resultData; + let options; + let context; + let _this; + let resultData; afterEach(function () { sinon.restore(); @@ -78,7 +81,7 @@ describe('{{#foreach}} helper', function () { }); it('should populate data when private data is supplied (array)', function () { - var expected = [ + const expected = [ {first: true, last: false, even: false, odd: true, rowStart: false, rowEnd: false}, {first: false, last: false, even: true, odd: false, rowStart: false, rowEnd: false}, {first: false, last: false, even: false, odd: true, rowStart: false, rowEnd: false}, @@ -114,7 +117,7 @@ describe('{{#foreach}} helper', function () { }); it('should populate data when private data is supplied (object)', function () { - var expected = [ + const expected = [ {first: true, last: false, even: false, odd: true, rowStart: false, rowEnd: false}, {first: false, last: false, even: true, odd: false, rowStart: false, rowEnd: false}, {first: false, last: false, even: false, odd: true, rowStart: false, rowEnd: false}, @@ -156,7 +159,7 @@ describe('{{#foreach}} helper', function () { }); it('should handle rowStart and rowEnd for multiple columns (array)', function () { - var expected = [ + const expected = [ {first: true, last: false, even: false, odd: true, rowStart: true, rowEnd: false}, {first: false, last: false, even: true, odd: false, rowStart: false, rowEnd: true}, {first: false, last: false, even: false, odd: true, rowStart: true, rowEnd: false}, @@ -191,7 +194,7 @@ describe('{{#foreach}} helper', function () { }); it('should handle rowStart and rowEnd for multiple columns (array)', function () { - var expected = [ + const expected = [ {first: true, last: false, even: false, odd: true, rowStart: true, rowEnd: false}, {first: false, last: false, even: true, odd: false, rowStart: false, rowEnd: true}, {first: false, last: false, even: false, odd: true, rowStart: true, rowEnd: false}, @@ -247,29 +250,32 @@ describe('{{#foreach}} helper', function () { }); describe('(compile)', function () { - var objectHash = { - posts: { - first: {title: 'first'}, - second: {title: 'second'}, - third: {title: 'third'}, - fourth: {title: 'fourth'}, - fifth: {title: 'fifth'} - } - }, - arrayHash = { - posts: [ - {title: 'first'}, {title: 'second'}, {title: 'third'}, {title: 'fourth'}, {title: 'fifth'} - ] - }, - arrayHash2 = {goodbyes: [{text: 'goodbye'}, {text: 'Goodbye'}, {text: 'GOODBYE'}], world: 'world'}, - objectHash2 = { - goodbyes: {foo: {text: 'goodbye'}, bar: {text: 'Goodbye'}, baz: {text: 'GOODBYE'}}, - world: 'world' - }; + const objectHash = { + posts: { + first: {title: 'first'}, + second: {title: 'second'}, + third: {title: 'third'}, + fourth: {title: 'fourth'}, + fifth: {title: 'fifth'} + } + }; + + const arrayHash = { + posts: [ + {title: 'first'}, {title: 'second'}, {title: 'third'}, {title: 'fourth'}, {title: 'fifth'} + ] + }; + + const arrayHash2 = {goodbyes: [{text: 'goodbye'}, {text: 'Goodbye'}, {text: 'GOODBYE'}], world: 'world'}; + + const objectHash2 = { + goodbyes: {foo: {text: 'goodbye'}, bar: {text: 'Goodbye'}, baz: {text: 'GOODBYE'}}, + world: 'world' + }; function shouldCompileToExpected(templateString, hash, expected) { - var template = handlebars.compile(templateString), - result = template(hash); + const template = handlebars.compile(templateString); + const result = template(hash); result.should.eql(expected); } @@ -280,300 +286,303 @@ describe('{{#foreach}} helper', function () { /** Many of these are copied direct from the handlebars spec */ it('object and @key', function () { - var templateString = '
    {{#foreach posts}}
  • {{@key}} {{title}}
  • {{/foreach}}
', - expected = '
  • first first
  • second second
  • third third
  • fourth fourth
  • fifth fifth
'; + const templateString = '
    {{#foreach posts}}
  • {{@key}} {{title}}
  • {{/foreach}}
'; + const expected = '
  • first first
  • second second
  • third third
  • fourth fourth
  • fifth fifth
'; shouldCompileToExpected(templateString, objectHash, expected); }); it('@index', function () { - var templateString = '
    {{#foreach posts}}
  • {{@index}} {{title}}
  • {{/foreach}}
', - expected = '
  • 0 first
  • 1 second
  • 2 third
  • 3 fourth
  • 4 fifth
'; + const templateString = '
    {{#foreach posts}}
  • {{@index}} {{title}}
  • {{/foreach}}
'; + const expected = '
  • 0 first
  • 1 second
  • 2 third
  • 3 fourth
  • 4 fifth
'; shouldCompileToExpected(templateString, arrayHash, expected); shouldCompileToExpected(templateString, objectHash, expected); }); it('@number', function () { - var templateString = '
    {{#foreach posts}}
  • {{@number}} {{title}}
  • {{/foreach}}
', - expected = '
  • 1 first
  • 2 second
  • 3 third
  • 4 fourth
  • 5 fifth
'; + const templateString = '
    {{#foreach posts}}
  • {{@number}} {{title}}
  • {{/foreach}}
'; + const expected = '
  • 1 first
  • 2 second
  • 3 third
  • 4 fourth
  • 5 fifth
'; shouldCompileToExpected(templateString, arrayHash, expected); shouldCompileToExpected(templateString, objectHash, expected); }); it('nested @index', function () { - var templateString = '{{#foreach goodbyes}}{{@index}}. {{text}}! {{#foreach ../goodbyes}}{{@index}} {{/foreach}}After {{@index}} {{/foreach}}{{@index}}cruel {{world}}!', - expected = '0. goodbye! 0 1 2 After 0 1. Goodbye! 0 1 2 After 1 2. GOODBYE! 0 1 2 After 2 cruel world!'; + const templateString = '{{#foreach goodbyes}}{{@index}}. {{text}}! {{#foreach ../goodbyes}}{{@index}} {{/foreach}}After {{@index}} {{/foreach}}{{@index}}cruel {{world}}!'; + const expected = '0. goodbye! 0 1 2 After 0 1. Goodbye! 0 1 2 After 1 2. GOODBYE! 0 1 2 After 2 cruel world!'; shouldCompileToExpected(templateString, arrayHash2, expected); shouldCompileToExpected(templateString, objectHash2, expected); }); it('array block params', function () { - var templateString = '{{#foreach goodbyes as |value index|}}{{index}}. {{value.text}}! {{#foreach ../goodbyes as |childValue childIndex|}} {{index}} {{childIndex}}{{/foreach}} After {{index}} {{/foreach}}{{index}}cruel {{world}}!', - expected = '0. goodbye! 0 0 0 1 0 2 After 0 1. Goodbye! 1 0 1 1 1 2 After 1 2. GOODBYE! 2 0 2 1 2 2 After 2 cruel world!'; + const templateString = '{{#foreach goodbyes as |value index|}}{{index}}. {{value.text}}! {{#foreach ../goodbyes as |childValue childIndex|}} {{index}} {{childIndex}}{{/foreach}} After {{index}} {{/foreach}}{{index}}cruel {{world}}!'; + const expected = '0. goodbye! 0 0 0 1 0 2 After 0 1. Goodbye! 1 0 1 1 1 2 After 1 2. GOODBYE! 2 0 2 1 2 2 After 2 cruel world!'; shouldCompileToExpected(templateString, arrayHash2, expected); }); it('object block params', function () { - var templateString = '{{#foreach goodbyes as |value index|}}{{index}}. {{value.text}}! {{#foreach ../goodbyes as |childValue childIndex|}} {{index}} {{childIndex}}{{/foreach}} After {{index}} {{/foreach}}{{index}}cruel {{world}}!', - expected = 'foo. goodbye! foo foo foo bar foo baz After foo bar. Goodbye! bar foo bar bar bar baz After bar baz. GOODBYE! baz foo baz bar baz baz After baz cruel world!'; + const templateString = '{{#foreach goodbyes as |value index|}}{{index}}. {{value.text}}! {{#foreach ../goodbyes as |childValue childIndex|}} {{index}} {{childIndex}}{{/foreach}} After {{index}} {{/foreach}}{{index}}cruel {{world}}!'; + const expected = 'foo. goodbye! foo foo foo bar foo baz After foo bar. Goodbye! bar foo bar bar bar baz After bar baz. GOODBYE! baz foo baz bar baz baz After baz cruel world!'; shouldCompileToExpected(templateString, objectHash2, expected); }); it('@first', function () { - var templateString = '{{#foreach goodbyes}}{{#if @first}}{{text}}! {{/if}}{{/foreach}}cruel {{world}}!', - expected = 'goodbye! cruel world!'; + const templateString = '{{#foreach goodbyes}}{{#if @first}}{{text}}! {{/if}}{{/foreach}}cruel {{world}}!'; + const expected = 'goodbye! cruel world!'; shouldCompileToExpected(templateString, arrayHash2, expected); shouldCompileToExpected(templateString, objectHash2, expected); }); it('nested @first', function () { - var templateString = '{{#foreach goodbyes}}({{#if @first}}{{text}}! {{/if}}{{#foreach ../goodbyes}}{{#if @first}}{{text}}!{{/if}}{{/foreach}}{{#if @first}} {{text}}!{{/if}}) {{/foreach}}cruel {{world}}!', - expected = '(goodbye! goodbye! goodbye!) (goodbye!) (goodbye!) cruel world!'; + const templateString = '{{#foreach goodbyes}}({{#if @first}}{{text}}! {{/if}}{{#foreach ../goodbyes}}{{#if @first}}{{text}}!{{/if}}{{/foreach}}{{#if @first}} {{text}}!{{/if}}) {{/foreach}}cruel {{world}}!'; + const expected = '(goodbye! goodbye! goodbye!) (goodbye!) (goodbye!) cruel world!'; shouldCompileToExpected(templateString, arrayHash2, expected); shouldCompileToExpected(templateString, objectHash2, expected); }); it('@last', function () { - var templateString = '{{#foreach goodbyes}}{{#if @last}}{{text}}! {{/if}}{{/foreach}}cruel {{world}}!', - expected = 'GOODBYE! cruel world!'; + const templateString = '{{#foreach goodbyes}}{{#if @last}}{{text}}! {{/if}}{{/foreach}}cruel {{world}}!'; + const expected = 'GOODBYE! cruel world!'; shouldCompileToExpected(templateString, arrayHash2, expected); shouldCompileToExpected(templateString, objectHash2, expected); }); it('nested @last', function () { - var templateString = '{{#foreach goodbyes}}({{#if @last}}{{text}}! {{/if}}{{#foreach ../goodbyes}}{{#if @last}}{{text}}!{{/if}}{{/foreach}}{{#if @last}} {{text}}!{{/if}}) {{/foreach}}cruel {{world}}!', - expected = '(GOODBYE!) (GOODBYE!) (GOODBYE! GOODBYE! GOODBYE!) cruel world!'; + const templateString = '{{#foreach goodbyes}}({{#if @last}}{{text}}! {{/if}}{{#foreach ../goodbyes}}{{#if @last}}{{text}}!{{/if}}{{/foreach}}{{#if @last}} {{text}}!{{/if}}) {{/foreach}}cruel {{world}}!'; + const expected = '(GOODBYE!) (GOODBYE!) (GOODBYE! GOODBYE! GOODBYE!) cruel world!'; shouldCompileToExpected(templateString, arrayHash2, expected); shouldCompileToExpected(templateString, objectHash2, expected); }); it('@last in foreach with limit', function () { - var templateString = '{{#foreach goodbyes limit="2"}}{{#if @last}}{{text}}! {{/if}}{{/foreach}}cruel {{world}}!', - expected = 'Goodbye! cruel world!'; + const templateString = '{{#foreach goodbyes limit="2"}}{{#if @last}}{{text}}! {{/if}}{{/foreach}}cruel {{world}}!'; + const expected = 'Goodbye! cruel world!'; shouldCompileToExpected(templateString, arrayHash2, expected); shouldCompileToExpected(templateString, objectHash2, expected); }); it('foreach with limit 1', function () { - var templateString = '
    {{#foreach posts limit="1"}}
  • {{title}}
  • {{else}}not this{{/foreach}}
', - expected = '
  • first
'; + const templateString = '
    {{#foreach posts limit="1"}}
  • {{title}}
  • {{else}}not this{{/foreach}}
'; + const expected = '
  • first
'; shouldCompileToExpected(templateString, arrayHash, expected); shouldCompileToExpected(templateString, objectHash, expected); }); it('foreach with limit 3', function () { - var templateString = '
    {{#foreach posts limit="3"}}
  • {{title}}
  • {{else}}not this{{/foreach}}
', - expected = '
  • first
  • second
  • third
'; + const templateString = '
    {{#foreach posts limit="3"}}
  • {{title}}
  • {{else}}not this{{/foreach}}
'; + const expected = '
  • first
  • second
  • third
'; shouldCompileToExpected(templateString, arrayHash, expected); shouldCompileToExpected(templateString, objectHash, expected); }); it('foreach with from 2', function () { - var templateString = '
    {{#foreach posts from="2"}}
  • {{title}}
  • {{else}}not this{{/foreach}}
', - expected = '
  • second
  • third
  • fourth
  • fifth
'; + const templateString = '
    {{#foreach posts from="2"}}
  • {{title}}
  • {{else}}not this{{/foreach}}
'; + const expected = '
  • second
  • third
  • fourth
  • fifth
'; shouldCompileToExpected(templateString, arrayHash, expected); shouldCompileToExpected(templateString, objectHash, expected); }); it('foreach with to 4', function () { - var templateString = '
    {{#foreach posts to="4"}}
  • {{title}}
  • {{else}}not this{{/foreach}}
', - expected = '
  • first
  • second
  • third
  • fourth
'; + const templateString = '
    {{#foreach posts to="4"}}
  • {{title}}
  • {{else}}not this{{/foreach}}
'; + const expected = '
  • first
  • second
  • third
  • fourth
'; shouldCompileToExpected(templateString, arrayHash, expected); shouldCompileToExpected(templateString, objectHash, expected); }); it('foreach with from 2 and to 3', function () { - var templateString = '
    {{#foreach posts from="2" to="3"}}
  • {{title}}
  • {{else}}not this{{/foreach}}
', - expected = '
  • second
  • third
'; + const templateString = '
    {{#foreach posts from="2" to="3"}}
  • {{title}}
  • {{else}}not this{{/foreach}}
'; + const expected = '
  • second
  • third
'; shouldCompileToExpected(templateString, arrayHash, expected); shouldCompileToExpected(templateString, objectHash, expected); }); it('foreach with from 3 and limit 2', function () { - var templateString = '
    {{#foreach posts from="3" limit="2"}}
  • {{title}}
  • {{else}}not this{{/foreach}}
', - expected = '
  • third
  • fourth
'; + const templateString = '
    {{#foreach posts from="3" limit="2"}}
  • {{title}}
  • {{else}}not this{{/foreach}}
'; + const expected = '
  • third
  • fourth
'; shouldCompileToExpected(templateString, arrayHash, expected); shouldCompileToExpected(templateString, objectHash, expected); }); it('foreach with from 2, to 5 and limit 3', function () { - var templateString = '
    {{#foreach posts from="2" to="5" limit="3"}}
  • {{title}}
  • {{else}}not this{{/foreach}}
', - expected = '
  • second
  • third
  • fourth
'; + const templateString = '
    {{#foreach posts from="2" to="5" limit="3"}}
  • {{title}}
  • {{else}}not this{{/foreach}}
'; + const expected = '
  • second
  • third
  • fourth
'; shouldCompileToExpected(templateString, arrayHash, expected); shouldCompileToExpected(templateString, objectHash, expected); }); it('@first in foreach with from 2 and to 4', function () { - var templateString = '
    {{#foreach posts from="2" to="4"}}{{#if @first}}
  • {{title}}
  • {{/if}}{{/foreach}}
', - expected = '
  • second
'; + const templateString = '
    {{#foreach posts from="2" to="4"}}{{#if @first}}
  • {{title}}
  • {{/if}}{{/foreach}}
'; + const expected = '
  • second
'; shouldCompileToExpected(templateString, arrayHash, expected); shouldCompileToExpected(templateString, objectHash, expected); }); it('@last in foreach with from 2 and to 4', function () { - var templateString = '
    {{#foreach posts from="2" to="4"}}{{#if @last}}
  • {{title}}
  • {{/if}}{{/foreach}}
', - expected = '
  • fourth
'; + const templateString = '
    {{#foreach posts from="2" to="4"}}{{#if @last}}
  • {{title}}
  • {{/if}}{{/foreach}}
'; + const expected = '
  • fourth
'; shouldCompileToExpected(templateString, arrayHash, expected); shouldCompileToExpected(templateString, objectHash, expected); }); it('@last in foreach with from 4', function () { - var templateString = '
    {{#foreach posts from="4"}}{{#if @last}}
  • {{title}}
  • {{/if}}{{/foreach}}
', - expected = '
  • fifth
'; + const templateString = '
    {{#foreach posts from="4"}}{{#if @last}}
  • {{title}}
  • {{/if}}{{/foreach}}
'; + const expected = '
  • fifth
'; shouldCompileToExpected(templateString, arrayHash, expected); shouldCompileToExpected(templateString, objectHash, expected); }); it('@first in foreach with from 4', function () { - var templateString = '
    {{#foreach posts from="4"}}{{#if @first}}
  • {{title}}
  • {{/if}}{{/foreach}}
', - expected = '
  • fourth
'; + const templateString = '
    {{#foreach posts from="4"}}{{#if @first}}
  • {{title}}
  • {{/if}}{{/foreach}}
'; + const expected = '
  • fourth
'; shouldCompileToExpected(templateString, arrayHash, expected); shouldCompileToExpected(templateString, objectHash, expected); }); it('@last in foreach with to 4', function () { - var templateString = '
    {{#foreach posts to="4"}}{{#if @last}}
  • {{title}}
  • {{/if}}{{/foreach}}
', - expected = '
  • fourth
'; + const templateString = '
    {{#foreach posts to="4"}}{{#if @last}}
  • {{title}}
  • {{/if}}{{/foreach}}
'; + const expected = '
  • fourth
'; shouldCompileToExpected(templateString, arrayHash, expected); shouldCompileToExpected(templateString, objectHash, expected); }); it('@first in foreach with to 4', function () { - var templateString = '
    {{#foreach posts to="4"}}{{#if @first}}
  • {{title}}
  • {{/if}}{{/foreach}}
', - expected = '
  • first
'; + const templateString = '
    {{#foreach posts to="4"}}{{#if @first}}
  • {{title}}
  • {{/if}}{{/foreach}}
'; + const expected = '
  • first
'; shouldCompileToExpected(templateString, arrayHash, expected); shouldCompileToExpected(templateString, objectHash, expected); }); it('@last in foreach with from 4 and limit 3', function () { - var templateString = '
    {{#foreach posts from="4" limit="3"}}{{#if @last}}
  • {{title}}
  • {{/if}}{{/foreach}}
', - expected = '
  • fifth
'; + const templateString = '
    {{#foreach posts from="4" limit="3"}}{{#if @last}}
  • {{title}}
  • {{/if}}{{/foreach}}
'; + const expected = '
  • fifth
'; shouldCompileToExpected(templateString, arrayHash, expected); shouldCompileToExpected(templateString, objectHash, expected); }); it('@first in foreach with from 4 and limit 3', function () { - var templateString = '
    {{#foreach posts from="4" limit="3"}}{{#if @first}}
  • {{title}}
  • {{/if}}{{/foreach}}
', - expected = '
  • fourth
'; + const templateString = '
    {{#foreach posts from="4" limit="3"}}{{#if @first}}
  • {{title}}
  • {{/if}}{{/foreach}}
'; + const expected = '
  • fourth
'; shouldCompileToExpected(templateString, arrayHash, expected); shouldCompileToExpected(templateString, objectHash, expected); }); it('@last in foreach with to 4 and limit 3', function () { - var templateString = '
    {{#foreach posts to="4" limit="3"}}{{#if @last}}
  • {{title}}
  • {{/if}}{{/foreach}}
', - expected = '
  • third
'; + const templateString = '
    {{#foreach posts to="4" limit="3"}}{{#if @last}}
  • {{title}}
  • {{/if}}{{/foreach}}
'; + const expected = '
  • third
'; shouldCompileToExpected(templateString, arrayHash, expected); shouldCompileToExpected(templateString, objectHash, expected); }); it('@first in foreach with to 4 and limit 3', function () { - var templateString = '
    {{#foreach posts to="4" limit="3"}}{{#if @first}}
  • {{title}}
  • {{/if}}{{/foreach}}
', - expected = '
  • first
'; + const templateString = '
    {{#foreach posts to="4" limit="3"}}{{#if @first}}
  • {{title}}
  • {{/if}}{{/foreach}}
'; + const expected = '
  • first
'; shouldCompileToExpected(templateString, arrayHash, expected); shouldCompileToExpected(templateString, objectHash, expected); }); describe('Internal Tags', function () { - var tagArrayHash = { - tags: [ - {name: 'first', visibility: 'public'}, - {name: 'second', visibility: 'public'}, - {name: 'third', visibility: 'internal'}, - {name: 'fourth', visibility: 'public'}, - {name: 'fifth', visibility: 'public'} - ] - }, - tagObjectHash = { - tags: { - first: {name: 'first', visibility: 'public'}, - second: {name: 'second', visibility: 'public'}, - third: {name: 'third', visibility: 'internal'}, - fourth: {name: 'fourth', visibility: 'public'}, - fifth: {name: 'fifth', visibility: 'public'} - } - }; + const tagArrayHash = { + tags: [ + {name: 'first', visibility: 'public'}, + {name: 'second', visibility: 'public'}, + {name: 'third', visibility: 'internal'}, + {name: 'fourth', visibility: 'public'}, + {name: 'fifth', visibility: 'public'} + ] + }; + + const tagObjectHash = { + tags: { + first: {name: 'first', visibility: 'public'}, + second: {name: 'second', visibility: 'public'}, + third: {name: 'third', visibility: 'internal'}, + fourth: {name: 'fourth', visibility: 'public'}, + fifth: {name: 'fifth', visibility: 'public'} + } + }; it('will not output internal tags', function () { - var templateString = '
    {{#foreach tags}}
  • {{@index}} {{name}}
  • {{/foreach}}
', - expected = '
  • 0 first
  • 1 second
  • 2 fourth
  • 3 fifth
'; + const templateString = '
    {{#foreach tags}}
  • {{@index}} {{name}}
  • {{/foreach}}
'; + const expected = '
  • 0 first
  • 1 second
  • 2 fourth
  • 3 fifth
'; shouldCompileToExpected(templateString, tagObjectHash, expected); shouldCompileToExpected(templateString, tagArrayHash, expected); }); it('should still correctly apply from & limit tags', function () { - var templateString = '
    {{#foreach tags from="2" limit="2"}}
  • {{@index}} {{name}}
  • {{/foreach}}
', - expected = '
  • 1 second
  • 2 fourth
'; + const templateString = '
    {{#foreach tags from="2" limit="2"}}
  • {{@index}} {{name}}
  • {{/foreach}}
'; + const expected = '
  • 1 second
  • 2 fourth
'; shouldCompileToExpected(templateString, tagObjectHash, expected); shouldCompileToExpected(templateString, tagArrayHash, expected); }); it('should output all tags with visibility="all"', function () { - var templateString = '
    {{#foreach tags visibility="all"}}
  • {{@index}} {{name}}
  • {{/foreach}}
', - expected = '
  • 0 first
  • 1 second
  • 2 third
  • 3 fourth
  • 4 fifth
'; + const templateString = '
    {{#foreach tags visibility="all"}}
  • {{@index}} {{name}}
  • {{/foreach}}
'; + const expected = '
  • 0 first
  • 1 second
  • 2 third
  • 3 fourth
  • 4 fifth
'; shouldCompileToExpected(templateString, tagObjectHash, expected); shouldCompileToExpected(templateString, tagArrayHash, expected); }); it('should output all tags with visibility property set with visibility="public,internal"', function () { - var templateString = '
    {{#foreach tags visibility="public,internal"}}
  • {{@index}} {{name}}
  • {{/foreach}}
', - expected = '
  • 0 first
  • 1 second
  • 2 third
  • 3 fourth
  • 4 fifth
'; + const templateString = '
    {{#foreach tags visibility="public,internal"}}
  • {{@index}} {{name}}
  • {{/foreach}}
'; + const expected = '
  • 0 first
  • 1 second
  • 2 third
  • 3 fourth
  • 4 fifth
'; shouldCompileToExpected(templateString, tagObjectHash, expected); shouldCompileToExpected(templateString, tagArrayHash, expected); }); it('should output all tags with visibility="internal"', function () { - var templateString = '
    {{#foreach tags visibility="internal"}}
  • {{@index}} {{name}}
  • {{/foreach}}
', - expected = '
  • 0 third
'; + const templateString = '
    {{#foreach tags visibility="internal"}}
  • {{@index}} {{name}}
  • {{/foreach}}
'; + const expected = '
  • 0 third
'; shouldCompileToExpected(templateString, tagObjectHash, expected); shouldCompileToExpected(templateString, tagArrayHash, expected); }); it('should output nothing if all tags are internal', function () { - var tagArrayHash = { - tags: [ - {name: 'first', visibility: 'internal'}, - {name: 'second', visibility: 'internal'} - ] - }, - tagObjectHash = { - tags: { - first: {name: 'first', visibility: 'internal'}, - second: {name: 'second', visibility: 'internal'} - } - }, - templateString = '
    {{#foreach tags}}
  • {{@index}} {{name}}
  • {{/foreach}}
', - expected = '
    '; + const tagArrayHash = { + tags: [ + {name: 'first', visibility: 'internal'}, + {name: 'second', visibility: 'internal'} + ] + }; + + const tagObjectHash = { + tags: { + first: {name: 'first', visibility: 'internal'}, + second: {name: 'second', visibility: 'internal'} + } + }; + + const templateString = '
      {{#foreach tags}}
    • {{@index}} {{name}}
    • {{/foreach}}
    '; + const expected = '
      '; shouldCompileToExpected(templateString, tagObjectHash, expected); shouldCompileToExpected(templateString, tagArrayHash, expected); diff --git a/test/unit/helpers/get_spec.js b/test/unit/helpers/get_spec.js index 38da8b51ef..15b2d95718 100644 --- a/test/unit/helpers/get_spec.js +++ b/test/unit/helpers/get_spec.js @@ -1,14 +1,16 @@ -var should = require('should'), - sinon = require('sinon'), - Promise = require('bluebird'), +const should = require('should'); +const sinon = require('sinon'); +const Promise = require('bluebird'); - // Stuff we are testing - helpers = require('../../../core/frontend/helpers'), - models = require('../../../core/server/models'), - api = require('../../../core/server/api'); +// Stuff we are testing +const helpers = require('../../../core/frontend/helpers'); + +const models = require('../../../core/server/models'); +const api = require('../../../core/server/api'); describe('{{#get}} helper', function () { - var fn, inverse; + let fn; + let inverse; let locals = {}; before(function () { @@ -164,11 +166,13 @@ describe('{{#get}} helper', function () { }); describe('path resolution', function () { - var browseStub, readStub, - pubDate = new Date(), - resource = { - post: {id: 3, title: 'Test 3', author: {slug: 'cameron'}, tags: [{slug: 'test'}, {slug: 'magic'}], published_at: pubDate} - }; + let browseStub; + let readStub; + const pubDate = new Date(); + + const resource = { + post: {id: 3, title: 'Test 3', author: {slug: 'cameron'}, tags: [{slug: 'test'}, {slug: 'magic'}], published_at: pubDate} + }; beforeEach(function () { browseStub = sinon.stub().resolves(); diff --git a/test/unit/helpers/ghost_foot_spec.js b/test/unit/helpers/ghost_foot_spec.js index 7f7423d4d1..c1249dd624 100644 --- a/test/unit/helpers/ghost_foot_spec.js +++ b/test/unit/helpers/ghost_foot_spec.js @@ -1,11 +1,11 @@ -var should = require('should'), - sinon = require('sinon'), - helpers = require('../../../core/frontend/helpers'), - proxy = require('../../../core/frontend/services/proxy'), - settingsCache = proxy.settingsCache; +const should = require('should'); +const sinon = require('sinon'); +const helpers = require('../../../core/frontend/helpers'); +const proxy = require('../../../core/frontend/services/proxy'); +const settingsCache = proxy.settingsCache; describe('{{ghost_foot}} helper', function () { - var settingsCacheStub; + let settingsCacheStub; afterEach(function () { sinon.restore(); diff --git a/test/unit/helpers/ghost_head_spec.js b/test/unit/helpers/ghost_head_spec.js index f00d44033a..26a2b3ddfd 100644 --- a/test/unit/helpers/ghost_head_spec.js +++ b/test/unit/helpers/ghost_head_spec.js @@ -1,22 +1,26 @@ /* eslint-disable no-regex-spaces */ -const should = require('should'), - sinon = require('sinon'), - _ = require('lodash'), - moment = require('moment'), - testUtils = require('../../utils'), - testUrlUtils = require('../../utils/urlUtils'), - configUtils = require('../../utils/configUtils'), - themes = require('../../../core/frontend/services/themes'), - models = require('../../../core/server/models'), - imageLib = require('../../../core/server/lib/image'), - routing = require('../../../core/frontend/services/routing'), - urlService = require('../../../core/frontend/services/url'), - helpers = require('../../../core/frontend/helpers'), - proxy = require('../../../core/frontend/services/proxy'), - settingsCache = proxy.settingsCache; +const should = require('should'); + +const sinon = require('sinon'); +const _ = require('lodash'); +const moment = require('moment'); +const testUtils = require('../../utils'); +const testUrlUtils = require('../../utils/urlUtils'); +const configUtils = require('../../utils/configUtils'); +const themes = require('../../../core/frontend/services/themes'); +const models = require('../../../core/server/models'); +const imageLib = require('../../../core/server/lib/image'); +const routing = require('../../../core/frontend/services/routing'); +const urlService = require('../../../core/frontend/services/url'); +const helpers = require('../../../core/frontend/helpers'); +const proxy = require('../../../core/frontend/services/proxy'); +const settingsCache = proxy.settingsCache; describe('{{ghost_head}} helper', function () { - let posts = [], tags = [], authors = [], users = []; + let posts = []; + let tags = []; + let authors = []; + let users = []; const makeFixtures = () => { const {createPost, createUser, createTag} = testUtils.DataGenerator.forKnex; @@ -423,7 +427,7 @@ describe('{{ghost_head}} helper', function () { }); it('returns structured data on static page', function (done) { - var renderObject = { + const renderObject = { post: posts[0] }; @@ -472,7 +476,7 @@ describe('{{ghost_head}} helper', function () { }); it('returns structured data on static page with custom post structured data', function (done) { - var renderObject = { + const renderObject = { post: posts[1] }; @@ -521,9 +525,11 @@ describe('{{ghost_head}} helper', function () { }); it('returns structured data on post page with author image and post cover image', function (done) { - var renderObject = { - post: posts[2] - }, postBk = _.cloneDeep(renderObject.post); + const renderObject = { + post: posts[2] + }; + + const postBk = _.cloneDeep(renderObject.post); helpers.ghost_head(testUtils.createHbsResponse({ renderObject: renderObject, @@ -533,10 +539,10 @@ describe('{{ghost_head}} helper', function () { safeVersion: '0.3' } })).then(function (rendered) { - var re1 = new RegExp('/); @@ -590,9 +596,11 @@ describe('{{ghost_head}} helper', function () { }); it('returns structured data on post page with custom excerpt for description and meta description', function (done) { - var renderObject = { - post: posts[3] - }, postBk = _.cloneDeep(renderObject.post); + const renderObject = { + post: posts[3] + }; + + const postBk = _.cloneDeep(renderObject.post); helpers.ghost_head(testUtils.createHbsResponse({ renderObject: renderObject, @@ -650,9 +658,11 @@ describe('{{ghost_head}} helper', function () { }); it('returns structured data on post page with fall back excerpt if no meta description provided', function (done) { - var renderObject = { - post: posts[4] - }, postBk = _.cloneDeep(renderObject.post); + const renderObject = { + post: posts[4] + }; + + const postBk = _.cloneDeep(renderObject.post); helpers.ghost_head(testUtils.createHbsResponse({ renderObject: renderObject, @@ -699,9 +709,11 @@ describe('{{ghost_head}} helper', function () { }); it('returns structured data on AMP post page with author image and post cover image', function (done) { - var renderObject = { - post: posts[5] - }, postBk = _.cloneDeep(renderObject.post); + const renderObject = { + post: posts[5] + }; + + const postBk = _.cloneDeep(renderObject.post); helpers.ghost_head(testUtils.createHbsResponse({ renderObject: renderObject, @@ -759,7 +771,7 @@ describe('{{ghost_head}} helper', function () { }); it('returns structured data if metaTitle and metaDescription have double quotes', function (done) { - var renderObject = { + const renderObject = { post: posts[6] }; @@ -819,7 +831,7 @@ describe('{{ghost_head}} helper', function () { }); it('returns structured data without tags if there are no tags', function (done) { - var renderObject = { + const renderObject = { post: posts[7] }; @@ -876,7 +888,7 @@ describe('{{ghost_head}} helper', function () { }); it('returns structured data on post page with null author image and post cover image', function (done) { - var renderObject = { + const renderObject = { post: posts[8] }; @@ -933,7 +945,7 @@ describe('{{ghost_head}} helper', function () { }); it('returns twitter and facebook descriptions even if no meta description available', function (done) { - var renderObject = { + const renderObject = { post: posts[9] }; @@ -957,7 +969,7 @@ describe('{{ghost_head}} helper', function () { }); it('returns canonical URL', function (done) { - var renderObject = { + const renderObject = { post: posts[9] }; @@ -1031,7 +1043,7 @@ describe('{{ghost_head}} helper', function () { }); it('returns structured data and schema first tag page with meta description and meta title', function (done) { - var renderObject = { + const renderObject = { tag: tags[0] }; @@ -1074,7 +1086,7 @@ describe('{{ghost_head}} helper', function () { }); it('tag first page without meta data if no meta title and meta description, but model description provided', function (done) { - var renderObject = { + const renderObject = { tag: tags[1] }; @@ -1116,7 +1128,7 @@ describe('{{ghost_head}} helper', function () { }); it('tag first page without meta and model description returns no description fields', function (done) { - var renderObject = { + const renderObject = { tag: tags[2] }; @@ -1140,7 +1152,7 @@ describe('{{ghost_head}} helper', function () { }); it('does not return structured data on paginated tag pages', function (done) { - var renderObject = { + const renderObject = { tag: tags[3] }; @@ -1390,7 +1402,7 @@ describe('{{ghost_head}} helper', function () { }); it('does not return structured data', function (done) { - var renderObject = { + const renderObject = { post: posts[2] }; @@ -1517,7 +1529,7 @@ describe('{{ghost_head}} helper', function () { }); it('returns meta tag without injected code for amp context', function (done) { - var renderObject = { + const renderObject = { post: posts[1] }; @@ -1546,7 +1558,7 @@ describe('{{ghost_head}} helper', function () { }); it('does not contain amphtml link', function (done) { - var renderObject = { + const renderObject = { post: posts[1] }; diff --git a/test/unit/helpers/has_spec.js b/test/unit/helpers/has_spec.js index 8ad1baee89..752f296e4c 100644 --- a/test/unit/helpers/has_spec.js +++ b/test/unit/helpers/has_spec.js @@ -1,11 +1,14 @@ -var should = require('should'), - sinon = require('sinon'), +const should = require('should'); +const sinon = require('sinon'); - // Stuff we are testing - helpers = require('../../../core/frontend/helpers'); +// Stuff we are testing +const helpers = require('../../../core/frontend/helpers'); describe('{{#has}} helper', function () { - var fn, inverse, thisCtx, handlebarsOptions; + let fn; + let inverse; + let thisCtx; + let handlebarsOptions; afterEach(function () { sinon.restore(); @@ -301,7 +304,7 @@ describe('{{#has}} helper', function () { }); it('will match on an exact number (loop)', function () { - for (var number = 1; number < 9; number += 1) { + for (let number = 1; number < 9; number += 1) { handlebarsOptions.data = {number: number}; // Will match 6 callHasHelper(thisCtx, {number: '6'}); @@ -331,7 +334,7 @@ describe('{{#has}} helper', function () { }); it('will match on a number list (loop)', function () { - for (var number = 1; number < 9; number += 1) { + for (let number = 1; number < 9; number += 1) { handlebarsOptions.data = {number: number}; // Will match 1, 3, 6 callHasHelper(thisCtx, {number: '1, 3, 6,12'}); @@ -362,7 +365,7 @@ describe('{{#has}} helper', function () { }); it('will match on a nth pattern (loop)', function () { - for (var number = 1; number < 9; number += 1) { + for (let number = 1; number < 9; number += 1) { handlebarsOptions.data = {number: number}; // Will match 3 & 6 callHasHelper(thisCtx, {number: 'nth:3'}); @@ -413,7 +416,7 @@ describe('{{#has}} helper', function () { }); it('will match on an exact index (loop)', function () { - for (var index = 0; index < 8; index += 1) { + for (let index = 0; index < 8; index += 1) { handlebarsOptions.data = {index: index}; // Will match 6 callHasHelper(thisCtx, {index: '6'}); @@ -443,7 +446,7 @@ describe('{{#has}} helper', function () { }); it('will match on an index list (loop)', function () { - for (var index = 0; index < 8; index += 1) { + for (let index = 0; index < 8; index += 1) { handlebarsOptions.data = {index: index}; // Will match 1, 3, 6 callHasHelper(thisCtx, {index: '1, 3, 6,12'}); @@ -474,7 +477,7 @@ describe('{{#has}} helper', function () { }); it('will match on a nth pattern (loop)', function () { - for (var index = 0; index < 8; index += 1) { + for (let index = 0; index < 8; index += 1) { handlebarsOptions.data = {index: index}; // Will match 0, 3, 6 callHasHelper(thisCtx, {index: 'nth:3'}); diff --git a/test/unit/helpers/img_url_spec.js b/test/unit/helpers/img_url_spec.js index 2debec457e..1d01a2aa66 100644 --- a/test/unit/helpers/img_url_spec.js +++ b/test/unit/helpers/img_url_spec.js @@ -1,13 +1,14 @@ -var should = require('should'), - sinon = require('sinon'), - urlUtils = require('../../utils/urlUtils'), +const should = require('should'); +const sinon = require('sinon'); +const urlUtils = require('../../utils/urlUtils'); - // Stuff we are testing - helpers = require('../../../core/frontend/helpers'), - common = require('../../../core/server/lib/common'); +// Stuff we are testing +const helpers = require('../../../core/frontend/helpers'); + +const common = require('../../../core/server/lib/common'); describe('{{image}} helper', function () { - var logWarnStub; + let logWarnStub; beforeEach(function () { logWarnStub = sinon.stub(common.logging, 'warn'); @@ -30,53 +31,53 @@ describe('{{image}} helper', function () { }); it('should output relative url of image', function () { - var rendered = helpers.img_url('/content/images/image-relative-url.png', {}); + const rendered = helpers.img_url('/content/images/image-relative-url.png', {}); should.exist(rendered); rendered.should.equal('/content/images/image-relative-url.png'); logWarnStub.called.should.be.false(); }); it('should output relative url of image if the input is absolute', function () { - var rendered = helpers.img_url('http://localhost:65535/content/images/image-relative-url.png', {}); + const rendered = helpers.img_url('http://localhost:65535/content/images/image-relative-url.png', {}); should.exist(rendered); rendered.should.equal('/content/images/image-relative-url.png'); logWarnStub.called.should.be.false(); }); it('should output absolute url of image if the option is present ', function () { - var rendered = helpers.img_url('/content/images/image-relative-url.png', {hash: {absolute: 'true'}}); + const rendered = helpers.img_url('/content/images/image-relative-url.png', {hash: {absolute: 'true'}}); should.exist(rendered); rendered.should.equal('http://localhost:65535/content/images/image-relative-url.png'); logWarnStub.called.should.be.false(); }); it('should NOT output absolute url of image if the option is "false" ', function () { - var rendered = helpers.img_url('/content/images/image-relative-url.png', {hash: {absolute: 'false'}}); + const rendered = helpers.img_url('/content/images/image-relative-url.png', {hash: {absolute: 'false'}}); should.exist(rendered); rendered.should.equal('/content/images/image-relative-url.png'); }); it('should output author url', function () { - var rendered = helpers.img_url('/content/images/author-image-relative-url.png', {}); + const rendered = helpers.img_url('/content/images/author-image-relative-url.png', {}); should.exist(rendered); rendered.should.equal('/content/images/author-image-relative-url.png'); logWarnStub.called.should.be.false(); }); it('should have no output if the image attributeis not provided (with warning)', function () { - var rendered = helpers.img_url({hash: {absolute: 'true'}}); + const rendered = helpers.img_url({hash: {absolute: 'true'}}); should.not.exist(rendered); logWarnStub.calledOnce.should.be.true(); }); it('should have no output if the image attribute evaluates to undefined (with warning)', function () { - var rendered = helpers.img_url(undefined, {hash: {absolute: 'true'}}); + const rendered = helpers.img_url(undefined, {hash: {absolute: 'true'}}); should.not.exist(rendered); logWarnStub.calledOnce.should.be.true(); }); it('should have no output if the image attribute evaluates to null (no waring)', function () { - var rendered = helpers.img_url(null, {hash: {absolute: 'true'}}); + const rendered = helpers.img_url(null, {hash: {absolute: 'true'}}); should.not.exist(rendered); logWarnStub.calledOnce.should.be.false(); }); @@ -95,19 +96,19 @@ describe('{{image}} helper', function () { }); it('should output relative url of image', function () { - var rendered = helpers.img_url('/blog/content/images/image-relative-url.png', {}); + const rendered = helpers.img_url('/blog/content/images/image-relative-url.png', {}); should.exist(rendered); rendered.should.equal('/blog/content/images/image-relative-url.png'); }); it('should output absolute url of image if the option is present ', function () { - var rendered = helpers.img_url('/blog/content/images/image-relative-url.png', {hash: {absolute: 'true'}}); + const rendered = helpers.img_url('/blog/content/images/image-relative-url.png', {hash: {absolute: 'true'}}); should.exist(rendered); rendered.should.equal('http://localhost:65535/blog/content/images/image-relative-url.png'); }); it('should not change output for an external url', function () { - var rendered = helpers.img_url('http://example.com/picture.jpg', {}); + const rendered = helpers.img_url('http://example.com/picture.jpg', {}); should.exist(rendered); rendered.should.equal('http://example.com/picture.jpg'); }); @@ -126,7 +127,7 @@ describe('{{image}} helper', function () { }); it('should output correct url for absolute paths which are internal', function () { - var rendered = helpers.img_url('http://localhost:65535/content/images/my-coole-img.jpg', { + const rendered = helpers.img_url('http://localhost:65535/content/images/my-coole-img.jpg', { hash: { size: 'medium' }, @@ -144,7 +145,7 @@ describe('{{image}} helper', function () { rendered.should.equal('/content/images/size/w400/my-coole-img.jpg'); }); it('should output the correct url for protocol relative urls', function () { - var rendered = helpers.img_url('//website.com/whatever/my-coole-img.jpg', { + const rendered = helpers.img_url('//website.com/whatever/my-coole-img.jpg', { hash: { size: 'medium' }, @@ -162,7 +163,7 @@ describe('{{image}} helper', function () { rendered.should.equal('//website.com/whatever/my-coole-img.jpg'); }); it('should output the correct url for relative paths', function () { - var rendered = helpers.img_url('/content/images/my-coole-img.jpg', { + const rendered = helpers.img_url('/content/images/my-coole-img.jpg', { hash: { size: 'medium' }, @@ -181,7 +182,7 @@ describe('{{image}} helper', function () { }); it('should output the correct url for relative paths without leading slash', function () { - var rendered = helpers.img_url('content/images/my-coole-img.jpg', { + const rendered = helpers.img_url('content/images/my-coole-img.jpg', { hash: { size: 'medium' }, diff --git a/test/unit/helpers/is_spec.js b/test/unit/helpers/is_spec.js index 71e9ec33db..243577f8f9 100644 --- a/test/unit/helpers/is_spec.js +++ b/test/unit/helpers/is_spec.js @@ -1,7 +1,7 @@ -var should = require('should'), - sinon = require('sinon'), - helpers = require('../../../core/frontend/helpers'), - common = require('../../../core/server/lib/common'); +const should = require('should'); +const sinon = require('sinon'); +const helpers = require('../../../core/frontend/helpers'); +const common = require('../../../core/server/lib/common'); describe('{{#is}} helper', function () { afterEach(function () { @@ -10,8 +10,8 @@ describe('{{#is}} helper', function () { // All positive tests it('should match single context "index"', function () { - var fn = sinon.spy(), - inverse = sinon.spy(); + const fn = sinon.spy(); + const inverse = sinon.spy(); helpers.is.call( {}, @@ -24,8 +24,8 @@ describe('{{#is}} helper', function () { }); it('should match OR context "index, paged"', function () { - var fn = sinon.spy(), - inverse = sinon.spy(); + const fn = sinon.spy(); + const inverse = sinon.spy(); helpers.is.call( {}, @@ -38,8 +38,8 @@ describe('{{#is}} helper', function () { }); it('should not match "paged"', function () { - var fn = sinon.spy(), - inverse = sinon.spy(); + const fn = sinon.spy(); + const inverse = sinon.spy(); helpers.is.call( {}, @@ -52,9 +52,9 @@ describe('{{#is}} helper', function () { }); it('should log warning with no args', function () { - var fn = sinon.spy(), - inverse = sinon.spy(), - logWarn = sinon.stub(common.logging, 'warn'); + const fn = sinon.spy(); + const inverse = sinon.spy(); + const logWarn = sinon.stub(common.logging, 'warn'); helpers.is.call( {}, diff --git a/test/unit/helpers/lang_spec.js b/test/unit/helpers/lang_spec.js index 49f3d8e5ee..6881d8c22f 100644 --- a/test/unit/helpers/lang_spec.js +++ b/test/unit/helpers/lang_spec.js @@ -13,8 +13,8 @@ describe('{{lang}} helper', function () { }); it('returns correct language tag', function () { - let expected = proxy.themeI18n.locale(), - rendered = helpers.lang.call(); + let expected = proxy.themeI18n.locale(); + let rendered = helpers.lang.call(); should.exist(rendered); rendered.string.should.equal(expected); diff --git a/test/unit/helpers/meta_description_spec.js b/test/unit/helpers/meta_description_spec.js index 3b8bc475c7..916e530312 100644 --- a/test/unit/helpers/meta_description_spec.js +++ b/test/unit/helpers/meta_description_spec.js @@ -22,7 +22,7 @@ describe('{{meta_description}} helper', function () { }); it('returns correct site description', function () { - var rendered = helpers.meta_description.call( + const rendered = helpers.meta_description.call( {}, {data: {root: {context: ['home', 'index']}}} ); @@ -32,7 +32,7 @@ describe('{{meta_description}} helper', function () { }); it('returns empty description on paginated page', function () { - var rendered = helpers.meta_description.call( + const rendered = helpers.meta_description.call( {}, {data: {root: {context: ['index', 'paged']}}} ); @@ -42,7 +42,7 @@ describe('{{meta_description}} helper', function () { }); it('returns empty description for a tag page', function () { - var rendered = helpers.meta_description.call( + const rendered = helpers.meta_description.call( {tag: {name: 'Rasper Red'}}, {data: {root: {context: ['tag']}}} ); @@ -52,7 +52,7 @@ describe('{{meta_description}} helper', function () { }); it('returns empty description for a paginated tag page', function () { - var rendered = helpers.meta_description.call( + const rendered = helpers.meta_description.call( {tag: {name: 'Rasper Red'}}, {data: {root: {context: ['tag', 'paged']}}} ); @@ -62,7 +62,7 @@ describe('{{meta_description}} helper', function () { }); it('returns tag meta_description if present for a tag page', function () { - var rendered = helpers.meta_description.call( + const rendered = helpers.meta_description.call( {tag: {name: 'Rasper Red', meta_description: 'Rasper is the Cool Red Casper'}}, {data: {root: {context: ['tag']}}} ); @@ -72,7 +72,7 @@ describe('{{meta_description}} helper', function () { }); it('returns empty description on paginated tag page that has meta data', function () { - var rendered = helpers.meta_description.call( + const rendered = helpers.meta_description.call( {tag: {name: 'Rasper Red', meta_description: 'Rasper is the Cool Red Casper'}}, {data: {root: {context: ['tag', 'paged']}}} ); @@ -82,7 +82,7 @@ describe('{{meta_description}} helper', function () { }); it('returns author bio for an author page', function () { - var rendered = helpers.meta_description.call( + const rendered = helpers.meta_description.call( {author: {bio: 'I am a Duck.'}}, {data: {root: {context: ['author']}}} ); @@ -92,7 +92,7 @@ describe('{{meta_description}} helper', function () { }); it('returns empty description for a paginated author page', function () { - var rendered = helpers.meta_description.call( + const rendered = helpers.meta_description.call( {author: {name: 'Donald Duck'}}, {data: {root: {context: ['author', 'paged']}}} ); @@ -102,7 +102,7 @@ describe('{{meta_description}} helper', function () { }); it('returns empty description when meta_description is not set', function () { - var rendered = helpers.meta_description.call( + const rendered = helpers.meta_description.call( {post: {title: 'Post Title', html: 'Very nice post indeed.'}}, {data: {root: {context: ['post']}}} ); @@ -112,7 +112,7 @@ describe('{{meta_description}} helper', function () { }); it('returns meta_description on post with meta_description set', function () { - var rendered = helpers.meta_description.call( + const rendered = helpers.meta_description.call( {post: {title: 'Post Title', meta_description: 'Nice post about stuff.'}}, {data: {root: {context: ['post']}}} ); @@ -122,7 +122,7 @@ describe('{{meta_description}} helper', function () { }); it('returns meta_description on post when used within {{#foreach posts}}', function () { - var rendered = helpers.meta_description.call( + const rendered = helpers.meta_description.call( {meta_description: 'Nice post about stuff.'}, {data: {root: {context: ['home']}}} ); @@ -138,7 +138,7 @@ describe('{{meta_description}} helper', function () { }); it('returns correct site description', function () { - var rendered = helpers.meta_description.call( + const rendered = helpers.meta_description.call( {}, {data: {root: {context: ['home', 'index']}}} ); @@ -148,7 +148,7 @@ describe('{{meta_description}} helper', function () { }); it('returns tag meta_description if present for a tag page', function () { - var rendered = helpers.meta_description.call( + const rendered = helpers.meta_description.call( {tag: {name: 'Rasper Red', meta_description: 'Rasper is the Cool Red Casper'}}, {data: {root: {context: ['tag']}}} ); diff --git a/test/unit/helpers/meta_title_spec.js b/test/unit/helpers/meta_title_spec.js index ac34606169..58753b57ab 100644 --- a/test/unit/helpers/meta_title_spec.js +++ b/test/unit/helpers/meta_title_spec.js @@ -1,8 +1,8 @@ -var should = require('should'), - sinon = require('sinon'), - configUtils = require('../../utils/configUtils'), - helpers = require('../../../core/frontend/helpers'), - settingsCache = require('../../../core/server/services/settings/cache'); +const should = require('should'); +const sinon = require('sinon'); +const configUtils = require('../../utils/configUtils'); +const helpers = require('../../../core/frontend/helpers'); +const settingsCache = require('../../../core/server/services/settings/cache'); describe('{{meta_title}} helper', function () { describe('no meta_title', function () { @@ -20,7 +20,7 @@ describe('{{meta_title}} helper', function () { }); it('returns correct title for homepage', function () { - var rendered = helpers.meta_title.call( + const rendered = helpers.meta_title.call( {}, {data: {root: {context: ['home']}}} ); @@ -30,7 +30,7 @@ describe('{{meta_title}} helper', function () { }); it('returns correct title for paginated page', function () { - var rendered = helpers.meta_title.call( + const rendered = helpers.meta_title.call( {}, {data: {root: {context: [], pagination: {total: 2, page: 2}}}} ); @@ -40,7 +40,7 @@ describe('{{meta_title}} helper', function () { }); it('returns correct title for a post', function () { - var rendered = helpers.meta_title.call( + const rendered = helpers.meta_title.call( {post: {title: 'Post Title'}}, {data: {root: {context: ['post']}}} ); @@ -50,7 +50,7 @@ describe('{{meta_title}} helper', function () { }); it('returns correct title for a post with meta_title set', function () { - var rendered = helpers.meta_title.call( + const rendered = helpers.meta_title.call( {post: {title: 'Post Title', meta_title: 'Awesome Post'}}, {data: {root: {context: ['post']}}} ); @@ -60,7 +60,7 @@ describe('{{meta_title}} helper', function () { }); it('returns correct title for a page with meta_title set', function () { - var rendered = helpers.meta_title.call( + const rendered = helpers.meta_title.call( {post: {title: 'About Page', meta_title: 'All about my awesomeness', page: true}}, {data: {root: {context: ['page']}}} ); @@ -70,18 +70,19 @@ describe('{{meta_title}} helper', function () { }); it('returns correct title for a tag page', function () { - var tag = {relativeUrl: '/tag/rasper-red', tag: {name: 'Rasper Red'}}, - rendered = helpers.meta_title.call( - tag, - {data: {root: {context: ['tag']}}} - ); + const tag = {relativeUrl: '/tag/rasper-red', tag: {name: 'Rasper Red'}}; + + const rendered = helpers.meta_title.call( + tag, + {data: {root: {context: ['tag']}}} + ); should.exist(rendered); String(rendered).should.equal('Rasper Red - Ghost'); }); it('returns correct title for a paginated tag page', function () { - var rendered = helpers.meta_title.call( + const rendered = helpers.meta_title.call( {tag: {name: 'Rasper Red'}}, {data: {root: {context: ['tag', 'paged'], pagination: {total: 2, page: 2}}}} ); @@ -91,7 +92,7 @@ describe('{{meta_title}} helper', function () { }); it('uses tag meta_title to override default response on tag page', function () { - var rendered = helpers.meta_title.call( + const rendered = helpers.meta_title.call( {tag: {name: 'Rasper Red', meta_title: 'Sasper Red'}}, {data: {root: {context: ['tag']}}} ); @@ -101,7 +102,7 @@ describe('{{meta_title}} helper', function () { }); it('uses tag meta_title to override default response on paginated tag page', function () { - var rendered = helpers.meta_title.call( + const rendered = helpers.meta_title.call( {tag: {name: 'Rasper Red', meta_title: 'Sasper Red'}}, {data: {root: {context: ['tag']}}} ); @@ -111,7 +112,7 @@ describe('{{meta_title}} helper', function () { }); it('returns correct title for an author page', function () { - var rendered = helpers.meta_title.call( + const rendered = helpers.meta_title.call( {author: {name: 'Donald Duck'}}, {data: {root: {context: ['author']}}} ); @@ -121,7 +122,7 @@ describe('{{meta_title}} helper', function () { }); it('returns correct title for a paginated author page', function () { - var rendered = helpers.meta_title.call( + const rendered = helpers.meta_title.call( {author: {name: 'Donald Duck'}}, {data: {root: {context: ['author', 'paged'], pagination: {total: 2, page: 2}}}} ); @@ -131,7 +132,7 @@ describe('{{meta_title}} helper', function () { }); it('returns correctly escaped title of a post', function () { - var rendered = helpers.meta_title.call( + const rendered = helpers.meta_title.call( {post: {title: 'Post Title "'}}, {data: {root: {context: ['post']}}} ); @@ -141,7 +142,7 @@ describe('{{meta_title}} helper', function () { }); it('returns meta_title on post when used within {{#foreach posts}}', function () { - var rendered = helpers.meta_title.call( + const rendered = helpers.meta_title.call( {meta_title: 'Awesome Post'}, {data: {root: {context: ['home']}}} ); @@ -160,7 +161,7 @@ describe('{{meta_title}} helper', function () { }[key]; }); - var rendered = helpers.meta_title.call( + const rendered = helpers.meta_title.call( {}, {data: {root: {context: ['home']}}} ); @@ -170,7 +171,7 @@ describe('{{meta_title}} helper', function () { }); it('returns correct title for paginated page', function () { - var rendered = helpers.meta_title.call( + const rendered = helpers.meta_title.call( {}, {data: {root: {context: [], pagination: {total: 2, page: 2}}}} ); @@ -180,18 +181,19 @@ describe('{{meta_title}} helper', function () { }); it('returns correct title for a tag page', function () { - var tag = {relativeUrl: '/tag/rasper-red', tag: {name: 'Rasper Red'}}, - rendered = helpers.meta_title.call( - tag, - {data: {root: {context: ['tag']}}} - ); + const tag = {relativeUrl: '/tag/rasper-red', tag: {name: 'Rasper Red'}}; + + const rendered = helpers.meta_title.call( + tag, + {data: {root: {context: ['tag']}}} + ); should.exist(rendered); String(rendered).should.equal('Rasper Red - Ghost'); }); it('returns correct title for an author page', function () { - var rendered = helpers.meta_title.call( + const rendered = helpers.meta_title.call( {author: {name: 'Donald Duck'}}, {data: {root: {context: ['author']}}} ); @@ -201,7 +203,7 @@ describe('{{meta_title}} helper', function () { }); it('returns correct title for a paginated author page', function () { - var rendered = helpers.meta_title.call( + const rendered = helpers.meta_title.call( {author: {name: 'Donald Duck'}}, {data: {root: {context: ['author', 'paged'], pagination: {total: 2, page: 2}}}} ); diff --git a/test/unit/helpers/navigation_spec.js b/test/unit/helpers/navigation_spec.js index e1dd61e008..1d41b5a37c 100644 --- a/test/unit/helpers/navigation_spec.js +++ b/test/unit/helpers/navigation_spec.js @@ -61,15 +61,15 @@ describe('{{navigation}} helper', function () { }); it('can render empty nav', function () { - var rendered = runHelper(optionsData); + const rendered = runHelper(optionsData); should.exist(rendered); rendered.string.should.be.equal(''); }); it('can handle relativeUrl not being set (e.g. for images/assets)', function () { - var singleItem = {label: 'Foo', url: '/foo'}, - rendered; + const singleItem = {label: 'Foo', url: '/foo'}; + let rendered; delete optionsData.data.root.relativeUrl; optionsData.data.site.navigation = [singleItem]; @@ -80,9 +80,9 @@ describe('{{navigation}} helper', function () { }); it('can render one item', function () { - var singleItem = {label: 'Foo', url: '/foo'}, - testUrl = 'href="' + configUtils.config.get('url') + '/foo"', - rendered; + const singleItem = {label: 'Foo', url: '/foo'}; + const testUrl = 'href="' + configUtils.config.get('url') + '/foo"'; + let rendered; optionsData.data.site.navigation = [singleItem]; rendered = runHelper(optionsData); @@ -94,11 +94,11 @@ describe('{{navigation}} helper', function () { }); it('can render multiple items', function () { - var firstItem = {label: 'Foo', url: '/foo'}, - secondItem = {label: 'Bar Baz Qux', url: '/qux'}, - testUrl = 'href="' + configUtils.config.get('url') + '/foo"', - testUrl2 = 'href="' + configUtils.config.get('url') + '/qux"', - rendered; + const firstItem = {label: 'Foo', url: '/foo'}; + const secondItem = {label: 'Bar Baz Qux', url: '/qux'}; + const testUrl = 'href="' + configUtils.config.get('url') + '/foo"'; + const testUrl2 = 'href="' + configUtils.config.get('url') + '/qux"'; + let rendered; optionsData.data.site.navigation = [firstItem, secondItem]; rendered = runHelper(optionsData); @@ -111,9 +111,9 @@ describe('{{navigation}} helper', function () { }); it('can annotate the current url', function () { - var firstItem = {label: 'Foo', url: '/foo'}, - secondItem = {label: 'Bar', url: '/qux'}, - rendered; + const firstItem = {label: 'Foo', url: '/foo'}; + const secondItem = {label: 'Bar', url: '/qux'}; + let rendered; optionsData.data.site.navigation = [firstItem, secondItem]; optionsData.data.root.relativeUrl = '/foo'; @@ -127,9 +127,9 @@ describe('{{navigation}} helper', function () { }); it('can annotate current url with trailing slash', function () { - var firstItem = {label: 'Foo', url: '/foo'}, - secondItem = {label: 'Bar', url: '/qux'}, - rendered; + const firstItem = {label: 'Foo', url: '/foo'}; + const secondItem = {label: 'Bar', url: '/qux'}; + let rendered; optionsData.data.site.navigation = [firstItem, secondItem]; optionsData.data.root.relativeUrl = '/foo/'; @@ -143,8 +143,8 @@ describe('{{navigation}} helper', function () { }); it('doesn\'t html-escape URLs', function () { - var firstItem = {label: 'Foo', url: '/?foo=bar&baz=qux'}, - rendered; + const firstItem = {label: 'Foo', url: '/?foo=bar&baz=qux'}; + let rendered; optionsData.data.site.navigation = [firstItem]; rendered = runHelper(optionsData); @@ -156,8 +156,8 @@ describe('{{navigation}} helper', function () { }); it('encodes URLs', function () { - var firstItem = {label: 'Foo', url: '/?foo=space bar&'}, - rendered; + const firstItem = {label: 'Foo', url: '/?foo=space bar&'}; + let rendered; optionsData.data.site.navigation = [firstItem]; rendered = runHelper(optionsData); @@ -169,8 +169,8 @@ describe('{{navigation}} helper', function () { }); it('doesn\'t double-encode URLs', function () { - var firstItem = {label: 'Foo', url: '/?foo=space%20bar'}, - rendered; + const firstItem = {label: 'Foo', url: '/?foo=space%20bar'}; + let rendered; optionsData.data.site.navigation = [firstItem]; rendered = runHelper(optionsData); @@ -181,9 +181,9 @@ describe('{{navigation}} helper', function () { describe('type="secondary"', function () { it('can render one item', function () { - var singleItem = {label: 'Foo', url: '/foo'}, - testUrl = 'href="' + configUtils.config.get('url') + '/foo"', - rendered; + const singleItem = {label: 'Foo', url: '/foo'}; + const testUrl = 'href="' + configUtils.config.get('url') + '/foo"'; + let rendered; optionsData.data.site.secondary_navigation = [singleItem]; optionsData.hash = {type: 'secondary'}; @@ -196,11 +196,11 @@ describe('{{navigation}} helper', function () { }); it('can render multiple items', function () { - var firstItem = {label: 'Foo', url: '/foo'}, - secondItem = {label: 'Bar Baz Qux', url: '/qux'}, - testUrl = 'href="' + configUtils.config.get('url') + '/foo"', - testUrl2 = 'href="' + configUtils.config.get('url') + '/qux"', - rendered; + const firstItem = {label: 'Foo', url: '/foo'}; + const secondItem = {label: 'Bar Baz Qux', url: '/qux'}; + const testUrl = 'href="' + configUtils.config.get('url') + '/foo"'; + const testUrl2 = 'href="' + configUtils.config.get('url') + '/qux"'; + let rendered; optionsData.data.site.secondary_navigation = [firstItem, secondItem]; optionsData.hash = {type: 'secondary'}; @@ -216,7 +216,7 @@ describe('{{navigation}} helper', function () { }); describe('{{navigation}} helper with custom template', function () { - var optionsData; + let optionsData; before(function (done) { hbs.express4({partialsDir: [path.resolve(__dirname, './test_tpl')]}); @@ -241,8 +241,8 @@ describe('{{navigation}} helper with custom template', function () { }); it('can render one item and @site title', function () { - var testUrl = 'href="' + configUtils.config.get('url') + '/foo"', - rendered; + const testUrl = 'href="' + configUtils.config.get('url') + '/foo"'; + let rendered; // Set @site.title optionsData.data.site.title = 'Chaos is a ladder.'; @@ -258,8 +258,8 @@ describe('{{navigation}} helper with custom template', function () { }); it('can pass attributes through', function () { - var testUrl = 'href="' + configUtils.config.get('url') + '/foo"', - rendered; + const testUrl = 'href="' + configUtils.config.get('url') + '/foo"'; + let rendered; // Simulate {{navigation isHeader=true}} optionsData.hash = {isHeader: true}; @@ -275,8 +275,8 @@ describe('{{navigation}} helper with custom template', function () { }); it('sets isSecondary for type=secondary', function () { - var testUrl = 'href="' + configUtils.config.get('url') + '/foo"', - rendered; + const testUrl = 'href="' + configUtils.config.get('url') + '/foo"'; + let rendered; // Simulate {{navigation type="secondary"}} optionsData.hash = {type: 'secondary'}; diff --git a/test/unit/helpers/next_post_spec.js b/test/unit/helpers/next_post_spec.js index 3beb3f22af..42b1120b36 100644 --- a/test/unit/helpers/next_post_spec.js +++ b/test/unit/helpers/next_post_spec.js @@ -1,18 +1,17 @@ -var should = require('should'), - sinon = require('sinon'), - Promise = require('bluebird'), - markdownToMobiledoc = require('../../utils/fixtures/data-generator').markdownToMobiledoc, - - helpers = require('../../../core/frontend/helpers'), - api = require('../../../core/server/api'), - common = require('../../../core/server/lib/common'); +const should = require('should'); +const sinon = require('sinon'); +const Promise = require('bluebird'); +const markdownToMobiledoc = require('../../utils/fixtures/data-generator').markdownToMobiledoc; +const helpers = require('../../../core/frontend/helpers'); +const api = require('../../../core/server/api'); +const common = require('../../../core/server/lib/common'); // These helpers are the same, their name just changes helpers.next_post = helpers.prev_post; describe('{{next_post}} helper', function () { let locals; - var browsePostsStub; + let browsePostsStub; beforeEach(function () { locals = { @@ -47,9 +46,9 @@ describe('{{next_post}} helper', function () { }); it('shows \'if\' template with next post data', function (done) { - var fn = sinon.spy(), - inverse = sinon.spy(), - optionsData = {name: 'next_post', data: locals, fn: fn, inverse: inverse}; + const fn = sinon.spy(); + const inverse = sinon.spy(); + const optionsData = {name: 'next_post', data: locals, fn: fn, inverse: inverse}; helpers.next_post .call({ @@ -89,9 +88,9 @@ describe('{{next_post}} helper', function () { }); it('shows \'else\' template', function (done) { - var fn = sinon.spy(), - inverse = sinon.spy(), - optionsData = {name: 'next_post', data: locals, fn: fn, inverse: inverse}; + const fn = sinon.spy(); + const inverse = sinon.spy(); + const optionsData = {name: 'next_post', data: locals, fn: fn, inverse: inverse}; helpers.next_post .call({ @@ -127,9 +126,9 @@ describe('{{next_post}} helper', function () { }); it('shows \'else\' template', function (done) { - var fn = sinon.spy(), - inverse = sinon.spy(), - optionsData = {name: 'next_post', data: locals, fn: fn, inverse: inverse}; + const fn = sinon.spy(); + const inverse = sinon.spy(); + const optionsData = {name: 'next_post', data: locals, fn: fn, inverse: inverse}; helpers.next_post .call({}, optionsData) @@ -163,9 +162,9 @@ describe('{{next_post}} helper', function () { }); it('shows \'else\' template', function (done) { - var fn = sinon.spy(), - inverse = sinon.spy(), - optionsData = {name: 'next_post', data: locals, fn: fn, inverse: inverse}; + const fn = sinon.spy(); + const inverse = sinon.spy(); + const optionsData = {name: 'next_post', data: locals, fn: fn, inverse: inverse}; helpers.next_post .call({ @@ -207,9 +206,9 @@ describe('{{next_post}} helper', function () { }); it('shows \'else\' template', function (done) { - var fn = sinon.spy(), - inverse = sinon.spy(), - optionsData = {name: 'next_post', data: locals, fn: fn, inverse: inverse}; + const fn = sinon.spy(); + const inverse = sinon.spy(); + const optionsData = {name: 'next_post', data: locals, fn: fn, inverse: inverse}; helpers.next_post .call({ @@ -243,9 +242,9 @@ describe('{{next_post}} helper', function () { }); it('shows \'if\' template with prev post data with primary_tag set', function (done) { - var fn = sinon.spy(), - inverse = sinon.spy(), - optionsData = {name: 'next_post', data: locals, fn: fn, inverse: inverse, hash: {in: 'primary_tag'}}; + const fn = sinon.spy(); + const inverse = sinon.spy(); + const optionsData = {name: 'next_post', data: locals, fn: fn, inverse: inverse, hash: {in: 'primary_tag'}}; helpers.next_post .call({ @@ -275,9 +274,9 @@ describe('{{next_post}} helper', function () { }); it('shows \'if\' template with prev post data with primary_author set', function (done) { - var fn = sinon.spy(), - inverse = sinon.spy(), - optionsData = {name: 'next_post', data: locals, fn: fn, inverse: inverse, hash: {in: 'primary_author'}}; + const fn = sinon.spy(); + const inverse = sinon.spy(); + const optionsData = {name: 'next_post', data: locals, fn: fn, inverse: inverse, hash: {in: 'primary_author'}}; helpers.next_post .call({ @@ -307,9 +306,9 @@ describe('{{next_post}} helper', function () { }); it('shows \'if\' template with prev post data with author set', function (done) { - var fn = sinon.spy(), - inverse = sinon.spy(), - optionsData = {name: 'next_post', data: locals, fn: fn, inverse: inverse, hash: {in: 'author'}}; + const fn = sinon.spy(); + const inverse = sinon.spy(); + const optionsData = {name: 'next_post', data: locals, fn: fn, inverse: inverse, hash: {in: 'author'}}; helpers.next_post .call({ @@ -339,9 +338,9 @@ describe('{{next_post}} helper', function () { }); it('shows \'if\' template with prev post data & ignores in author if author isnt present', function (done) { - var fn = sinon.spy(), - inverse = sinon.spy(), - optionsData = {name: 'next_post', data: locals, fn: fn, inverse: inverse, hash: {in: 'author'}}; + const fn = sinon.spy(); + const inverse = sinon.spy(); + const optionsData = {name: 'next_post', data: locals, fn: fn, inverse: inverse, hash: {in: 'author'}}; helpers.next_post .call({ @@ -370,9 +369,9 @@ describe('{{next_post}} helper', function () { }); it('shows \'if\' template with prev post data & ignores unknown in value', function (done) { - var fn = sinon.spy(), - inverse = sinon.spy(), - optionsData = {name: 'next_post', data: locals, fn: fn, inverse: inverse, hash: {in: 'magic'}}; + const fn = sinon.spy(); + const inverse = sinon.spy(); + const optionsData = {name: 'next_post', data: locals, fn: fn, inverse: inverse, hash: {in: 'magic'}}; helpers.next_post .call({ @@ -410,9 +409,9 @@ describe('{{next_post}} helper', function () { }); it('should handle error from the API', function (done) { - var fn = sinon.spy(), - inverse = sinon.spy(), - optionsData = {name: 'next_post', data: locals, fn: fn, inverse: inverse}; + const fn = sinon.spy(); + const inverse = sinon.spy(); + const optionsData = {name: 'next_post', data: locals, fn: fn, inverse: inverse}; helpers.next_post .call({ @@ -438,9 +437,9 @@ describe('{{next_post}} helper', function () { }); it('should show warning for call without any options', function (done) { - var fn = sinon.spy(), - inverse = sinon.spy(), - optionsData = {name: 'next_post', data: {root: {}}}; + const fn = sinon.spy(); + const inverse = sinon.spy(); + const optionsData = {name: 'next_post', data: {root: {}}}; helpers.next_post .call( diff --git a/test/unit/helpers/page_url_spec.js b/test/unit/helpers/page_url_spec.js index 29f5749017..f1efe10965 100644 --- a/test/unit/helpers/page_url_spec.js +++ b/test/unit/helpers/page_url_spec.js @@ -1,10 +1,10 @@ -var should = require('should'), +const should = require('should'); - // Stuff we are testing - helpers = require('../../../core/frontend/helpers'); +// Stuff we are testing +const helpers = require('../../../core/frontend/helpers'); describe('{{page_url}} helper', function () { - var options = {data: {root: {pagination: {}}}}; + const options = {data: {root: {pagination: {}}}}; beforeEach(function () { options.data.root = {pagination: {}}; diff --git a/test/unit/helpers/pagination_spec.js b/test/unit/helpers/pagination_spec.js index 08e01eee64..b9452602c0 100644 --- a/test/unit/helpers/pagination_spec.js +++ b/test/unit/helpers/pagination_spec.js @@ -1,9 +1,8 @@ -var should = require('should'), - hbs = require('../../../core/frontend/services/themes/engine'), - configUtils = require('../../utils/configUtils'), - path = require('path'), - - helpers = require('../../../core/frontend/helpers'); +const should = require('should'); +const hbs = require('../../../core/frontend/services/themes/engine'); +const configUtils = require('../../utils/configUtils'); +const path = require('path'); +const helpers = require('../../../core/frontend/helpers'); describe('{{pagination}} helper', function () { before(function (done) { @@ -18,17 +17,19 @@ describe('{{pagination}} helper', function () { hbs.registerHelper('page_url', helpers.page_url); }); - var paginationRegex = /class="pagination"/, - newerRegex = /class="newer-posts"/, - olderRegex = /class="older-posts"/, - pageRegex = /class="page-number"/; + const paginationRegex = /class="pagination"/; + const newerRegex = /class="newer-posts"/; + const olderRegex = /class="older-posts"/; + const pageRegex = /class="page-number"/; it('should throw if pagination data is incorrect', function () { - var runHelper = function (data) { - return function () { - helpers.pagination.call(data); - }; - }, expectedMessage = 'The {{pagination}} helper was used outside of a paginated context. See https://ghost.org/docs/api/handlebars-themes/helpers/pagination/.'; + const runHelper = function (data) { + return function () { + helpers.pagination.call(data); + }; + }; + + const expectedMessage = 'The {{pagination}} helper was used outside of a paginated context. See https://ghost.org/docs/api/handlebars-themes/helpers/pagination/.'; runHelper('not an object').should.throwError(expectedMessage); runHelper(function () { @@ -36,7 +37,7 @@ describe('{{pagination}} helper', function () { }); it('can render single page with no pagination necessary', function () { - var rendered = helpers.pagination.call({ + const rendered = helpers.pagination.call({ pagination: {page: 1, prev: null, next: null, limit: 15, total: 8, pages: 1}, tag: {slug: 'slug'} }); @@ -50,7 +51,7 @@ describe('{{pagination}} helper', function () { }); it('can render first page of many with older posts link', function () { - var rendered = helpers.pagination.call({ + const rendered = helpers.pagination.call({ pagination: {page: 1, prev: null, next: 2, limit: 15, total: 8, pages: 3} }); should.exist(rendered); @@ -63,7 +64,7 @@ describe('{{pagination}} helper', function () { }); it('can render middle pages of many with older and newer posts link', function () { - var rendered = helpers.pagination.call({ + const rendered = helpers.pagination.call({ pagination: {page: 2, prev: 1, next: 3, limit: 15, total: 8, pages: 3} }); should.exist(rendered); @@ -76,7 +77,7 @@ describe('{{pagination}} helper', function () { }); it('can render last page of many with newer posts link', function () { - var rendered = helpers.pagination.call({ + const rendered = helpers.pagination.call({ pagination: {page: 3, prev: 2, next: null, limit: 15, total: 8, pages: 3} }); should.exist(rendered); @@ -89,7 +90,7 @@ describe('{{pagination}} helper', function () { }); it('validates values', function () { - var runErrorTest = function (data) { + const runErrorTest = function (data) { return function () { helpers.pagination.call(data); }; @@ -130,7 +131,7 @@ describe('{{pagination}} helper with custom template', function () { }); it('can render single page with @site.title', function () { - var rendered = helpers.pagination.call({ + const rendered = helpers.pagination.call({ pagination: {page: 1, prev: null, next: null, limit: 15, total: 8, pages: 1}, tag: {slug: 'slug'} }, { @@ -148,7 +149,7 @@ describe('{{pagination}} helper with custom template', function () { }); it('can pass attributes through', function () { - var rendered = helpers.pagination.call({ + const rendered = helpers.pagination.call({ pagination: {page: 1, prev: null, next: null, limit: 15, total: 8, pages: 1}, tag: {slug: 'slug'} }, { diff --git a/test/unit/helpers/plural_spec.js b/test/unit/helpers/plural_spec.js index 71b9d2aa13..881027fca5 100644 --- a/test/unit/helpers/plural_spec.js +++ b/test/unit/helpers/plural_spec.js @@ -1,60 +1,64 @@ -var should = require('should'), +const should = require('should'); - // Stuff we are testing - helpers = require('../../../core/frontend/helpers'); +// Stuff we are testing +const helpers = require('../../../core/frontend/helpers'); describe('{{plural}} helper', function () { it('will show no-value string', function () { - var expected = 'No Posts', - rendered = helpers.plural.call({}, 0, { - hash: { - empty: 'No Posts', - singular: '% Post', - plural: '% Posts' - } - }); + const expected = 'No Posts'; + + const rendered = helpers.plural.call({}, 0, { + hash: { + empty: 'No Posts', + singular: '% Post', + plural: '% Posts' + } + }); should.exist(rendered); rendered.string.should.equal(expected); }); it('will show no-value string with placement', function () { - var expected = '0 Posts', - rendered = helpers.plural.call({}, 0, { - hash: { - empty: '% Posts', - singular: '% Post', - plural: '% Posts' - } - }); + const expected = '0 Posts'; + + const rendered = helpers.plural.call({}, 0, { + hash: { + empty: '% Posts', + singular: '% Post', + plural: '% Posts' + } + }); should.exist(rendered); rendered.string.should.equal(expected); }); it('will show singular string', function () { - var expected = '1 Post', - rendered = helpers.plural.call({}, 1, { - hash: { - empty: 'No Posts', - singular: '% Post', - plural: '% Posts' - } - }); + const expected = '1 Post'; + + const rendered = helpers.plural.call({}, 1, { + hash: { + empty: 'No Posts', + singular: '% Post', + plural: '% Posts' + } + }); should.exist(rendered); rendered.string.should.equal(expected); }); it('will show plural string', function () { - var expected = '2 Posts', - rendered = helpers.plural.call({}, 2, { - hash: { - empty: 'No Posts', - singular: '% Post', - plural: '% Posts' - } - }); + const expected = '2 Posts'; + + const rendered = helpers.plural.call({}, 2, { + hash: { + empty: 'No Posts', + singular: '% Post', + plural: '% Posts' + } + }); should.exist(rendered); rendered.string.should.equal(expected); diff --git a/test/unit/helpers/post_class_spec.js b/test/unit/helpers/post_class_spec.js index d67de430b9..aa56456b7f 100644 --- a/test/unit/helpers/post_class_spec.js +++ b/test/unit/helpers/post_class_spec.js @@ -1,50 +1,50 @@ -var should = require('should'), +const should = require('should'); - // Stuff we are testing - helpers = require('../../../core/frontend/helpers'); +// Stuff we are testing +const helpers = require('../../../core/frontend/helpers'); describe('{{post_class}} helper', function () { it('can render class string', function () { - var rendered = helpers.post_class.call({}); + const rendered = helpers.post_class.call({}); should.exist(rendered); rendered.string.should.equal('post no-image'); }); it('can render class string without no-image class', function () { - var rendered = helpers.post_class.call({feature_image: 'blah'}); + const rendered = helpers.post_class.call({feature_image: 'blah'}); should.exist(rendered); rendered.string.should.equal('post'); }); it('can render featured class', function () { - var post = {featured: true}, - rendered = helpers.post_class.call(post); + const post = {featured: true}; + const rendered = helpers.post_class.call(post); should.exist(rendered); rendered.string.should.equal('post featured no-image'); }); it('can render featured class without no-image class', function () { - var post = {featured: true, feature_image: 'asdass'}, - rendered = helpers.post_class.call(post); + const post = {featured: true, feature_image: 'asdass'}; + const rendered = helpers.post_class.call(post); should.exist(rendered); rendered.string.should.equal('post featured'); }); it('can render page class', function () { - var post = {page: true}, - rendered = helpers.post_class.call(post); + const post = {page: true}; + const rendered = helpers.post_class.call(post); should.exist(rendered); rendered.string.should.equal('post no-image page'); }); it('can render page class without no-image class', function () { - var post = {page: true, feature_image: 'asdasdas'}, - rendered = helpers.post_class.call(post); + const post = {page: true, feature_image: 'asdasdas'}; + const rendered = helpers.post_class.call(post); should.exist(rendered); rendered.string.should.equal('post page'); diff --git a/test/unit/helpers/prev_post_spec.js b/test/unit/helpers/prev_post_spec.js index 57b32ed1a4..082a98be9b 100644 --- a/test/unit/helpers/prev_post_spec.js +++ b/test/unit/helpers/prev_post_spec.js @@ -1,14 +1,13 @@ -var should = require('should'), - sinon = require('sinon'), - Promise = require('bluebird'), - markdownToMobiledoc = require('../../utils/fixtures/data-generator').markdownToMobiledoc, - - helpers = require('../../../core/frontend/helpers'), - api = require('../../../core/server/api'), - common = require('../../../core/server/lib/common'); +const should = require('should'); +const sinon = require('sinon'); +const Promise = require('bluebird'); +const markdownToMobiledoc = require('../../utils/fixtures/data-generator').markdownToMobiledoc; +const helpers = require('../../../core/frontend/helpers'); +const api = require('../../../core/server/api'); +const common = require('../../../core/server/lib/common'); describe('{{prev_post}} helper', function () { - var browsePostsStub; + let browsePostsStub; let locals; beforeEach(function () { @@ -44,9 +43,9 @@ describe('{{prev_post}} helper', function () { }); it('shows \'if\' template with previous post data', function (done) { - var fn = sinon.spy(), - inverse = sinon.spy(), - optionsData = {name: 'prev_post', data: locals, fn: fn, inverse: inverse}; + const fn = sinon.spy(); + const inverse = sinon.spy(); + const optionsData = {name: 'prev_post', data: locals, fn: fn, inverse: inverse}; helpers.prev_post .call({ @@ -84,9 +83,9 @@ describe('{{prev_post}} helper', function () { }); it('shows \'else\' template', function (done) { - var fn = sinon.spy(), - inverse = sinon.spy(), - optionsData = {name: 'prev_post', data: locals, fn: fn, inverse: inverse}; + const fn = sinon.spy(); + const inverse = sinon.spy(); + const optionsData = {name: 'prev_post', data: locals, fn: fn, inverse: inverse}; helpers.prev_post .call({ @@ -122,9 +121,9 @@ describe('{{prev_post}} helper', function () { }); it('shows \'else\' template', function (done) { - var fn = sinon.spy(), - inverse = sinon.spy(), - optionsData = {name: 'prev_post', data: locals, fn: fn, inverse: inverse}; + const fn = sinon.spy(); + const inverse = sinon.spy(); + const optionsData = {name: 'prev_post', data: locals, fn: fn, inverse: inverse}; helpers.prev_post .call({}, optionsData) @@ -158,9 +157,9 @@ describe('{{prev_post}} helper', function () { }); it('shows \'else\' template', function (done) { - var fn = sinon.spy(), - inverse = sinon.spy(), - optionsData = {name: 'prev_post', data: locals, fn: fn, inverse: inverse}; + const fn = sinon.spy(); + const inverse = sinon.spy(); + const optionsData = {name: 'prev_post', data: locals, fn: fn, inverse: inverse}; helpers.prev_post .call({ @@ -202,9 +201,9 @@ describe('{{prev_post}} helper', function () { }); it('shows \'else\' template', function (done) { - var fn = sinon.spy(), - inverse = sinon.spy(), - optionsData = {name: 'prev_post', data: locals, fn: fn, inverse: inverse}; + const fn = sinon.spy(); + const inverse = sinon.spy(); + const optionsData = {name: 'prev_post', data: locals, fn: fn, inverse: inverse}; helpers.prev_post .call({ @@ -238,9 +237,9 @@ describe('{{prev_post}} helper', function () { }); it('shows \'if\' template with prev post data with primary_tag set', function (done) { - var fn = sinon.spy(), - inverse = sinon.spy(), - optionsData = {name: 'prev_post', data: locals, fn: fn, inverse: inverse, hash: {in: 'primary_tag'}}; + const fn = sinon.spy(); + const inverse = sinon.spy(); + const optionsData = {name: 'prev_post', data: locals, fn: fn, inverse: inverse, hash: {in: 'primary_tag'}}; helpers.prev_post .call({ @@ -270,9 +269,9 @@ describe('{{prev_post}} helper', function () { }); it('shows \'if\' template with prev post data with primary_author set', function (done) { - var fn = sinon.spy(), - inverse = sinon.spy(), - optionsData = {name: 'prev_post', data: locals, fn: fn, inverse: inverse, hash: {in: 'primary_author'}}; + const fn = sinon.spy(); + const inverse = sinon.spy(); + const optionsData = {name: 'prev_post', data: locals, fn: fn, inverse: inverse, hash: {in: 'primary_author'}}; helpers.prev_post .call({ @@ -302,9 +301,9 @@ describe('{{prev_post}} helper', function () { }); it('shows \'if\' template with prev post data with author set', function (done) { - var fn = sinon.spy(), - inverse = sinon.spy(), - optionsData = {name: 'prev_post', data: locals, fn: fn, inverse: inverse, hash: {in: 'author'}}; + const fn = sinon.spy(); + const inverse = sinon.spy(); + const optionsData = {name: 'prev_post', data: locals, fn: fn, inverse: inverse, hash: {in: 'author'}}; helpers.prev_post .call({ @@ -334,9 +333,9 @@ describe('{{prev_post}} helper', function () { }); it('shows \'if\' template with prev post data & ignores in author if author isnt present', function (done) { - var fn = sinon.spy(), - inverse = sinon.spy(), - optionsData = {name: 'prev_post', data: locals, fn: fn, inverse: inverse, hash: {in: 'author'}}; + const fn = sinon.spy(); + const inverse = sinon.spy(); + const optionsData = {name: 'prev_post', data: locals, fn: fn, inverse: inverse, hash: {in: 'author'}}; helpers.prev_post .call({ @@ -365,9 +364,9 @@ describe('{{prev_post}} helper', function () { }); it('shows \'if\' template with prev post data & ignores unknown in value', function (done) { - var fn = sinon.spy(), - inverse = sinon.spy(), - optionsData = {name: 'prev_post', data: locals, fn: fn, inverse: inverse, hash: {in: 'magic'}}; + const fn = sinon.spy(); + const inverse = sinon.spy(); + const optionsData = {name: 'prev_post', data: locals, fn: fn, inverse: inverse, hash: {in: 'magic'}}; helpers.prev_post .call({ @@ -405,9 +404,9 @@ describe('{{prev_post}} helper', function () { }); it('should handle error from the API', function (done) { - var fn = sinon.spy(), - inverse = sinon.spy(), - optionsData = {name: 'prev_post', data: locals, fn: fn, inverse: inverse}; + const fn = sinon.spy(); + const inverse = sinon.spy(); + const optionsData = {name: 'prev_post', data: locals, fn: fn, inverse: inverse}; helpers.prev_post .call({ @@ -433,9 +432,9 @@ describe('{{prev_post}} helper', function () { }); it('should show warning for call without any options', function (done) { - var fn = sinon.spy(), - inverse = sinon.spy(), - optionsData = {name: 'prev_post', data: {root: {}}}; + const fn = sinon.spy(); + const inverse = sinon.spy(); + const optionsData = {name: 'prev_post', data: {root: {}}}; helpers.prev_post .call( diff --git a/test/unit/helpers/reading_time_spec.js b/test/unit/helpers/reading_time_spec.js index f36e62f51e..5ce935574e 100644 --- a/test/unit/helpers/reading_time_spec.js +++ b/test/unit/helpers/reading_time_spec.js @@ -1,9 +1,9 @@ -var should = require('should'), +const should = require('should'); - // Stuff we are testing - helpers = require('../../../core/frontend/helpers'); +// Stuff we are testing +const helpers = require('../../../core/frontend/helpers'); -var almostOneMinute = +const almostOneMinute = '

      Ghost has a number of different user roles for your team

      ' + '

      Authors

      The base user level in Ghost is an author. Authors can write posts,' + ' edit their own posts, and publish their own posts. Authors are trusted users. If you ' + @@ -20,7 +20,7 @@ var almostOneMinute = ' users to fill out their user profiles, including bio and social links. These will populate rich structured data ' + 'for posts and generally create more opportunities for themes to fully populate their design.

      '; -var almostOneAndAHalfMinute = almostOneMinute + +const almostOneAndAHalfMinute = almostOneMinute + '
      ' + '

      Ghost has a number of different user roles for your team

      ' + '

      Authors

      The base user level in Ghost is an author. Authors can write posts,' + @@ -35,48 +35,52 @@ var almostOneAndAHalfMinute = almostOneMinute + describe('{{reading_time}} helper', function () { it('[success] renders reading time for less than one minute text as one minute', function () { - var data = { - html: almostOneMinute, - title: 'Test', - slug: 'slug' - }, - result = helpers.reading_time.call(data); + const data = { + html: almostOneMinute, + title: 'Test', + slug: 'slug' + }; + + const result = helpers.reading_time.call(data); String(result).should.equal('1 min read'); }); it('[success] renders reading time for one minute text as one minute', function () { - var data = { - html: almostOneMinute + + const data = { + html: almostOneMinute + 'This needed about twenty-five more words before passing the one minute reading time, ' + 'since the word count was 250, and the average speed is 275.', - title: 'Test', - slug: 'slug' - }, - result = helpers.reading_time.call(data); + title: 'Test', + slug: 'slug' + }; + + const result = helpers.reading_time.call(data); String(result).should.equal('1 min read'); }); it('[success] renders reading time for just under 1.5 minutes text as one minute', function () { - var data = { - html: almostOneAndAHalfMinute, - title: 'Test', - slug: 'slug' - }, - result = helpers.reading_time.call(data); + const data = { + html: almostOneAndAHalfMinute, + title: 'Test', + slug: 'slug' + }; + + const result = helpers.reading_time.call(data); String(result).should.equal('1 min read'); }); it('[success] adds time for feature image', function () { - var data = { - html: almostOneAndAHalfMinute, - title: 'Test', - slug: 'slug', - feature_image: '/content/images/someimage.jpg' - }, - result = helpers.reading_time.call(data); + const data = { + html: almostOneAndAHalfMinute, + title: 'Test', + slug: 'slug', + feature_image: '/content/images/someimage.jpg' + }; + + const result = helpers.reading_time.call(data); // The reading time for this HTML snippet would 89 seconds without the image // Adding the 12 additional seconds for the image results in a readng time of over 1.5 minutes, rounded to 2 @@ -84,13 +88,14 @@ describe('{{reading_time}} helper', function () { }); it('[success] adds time for inline images', function () { - var data = { - html: almostOneAndAHalfMinute + + const data = { + html: almostOneAndAHalfMinute + '', - title: 'Test', - slug: 'slug' - }, - result = helpers.reading_time.call(data); + title: 'Test', + slug: 'slug' + }; + + const result = helpers.reading_time.call(data); // The reading time for this HTML snippet would 89 seconds without the image // Adding the 12 additional seconds for the image results in a readng time of over 1.5 minutes, rounded to 2 @@ -98,13 +103,14 @@ describe('{{reading_time}} helper', function () { }); it('[failure] does not render reading time when not post', function () { - var data = { - author: { - name: 'abc 123', - slug: 'abc123' - } - }, - result = helpers.reading_time.call(data); + const data = { + author: { + name: 'abc 123', + slug: 'abc123' + } + }; + + const result = helpers.reading_time.call(data); should.not.exist(result); }); diff --git a/test/unit/helpers/tags_spec.js b/test/unit/helpers/tags_spec.js index 8e94c17e21..8df45741ac 100644 --- a/test/unit/helpers/tags_spec.js +++ b/test/unit/helpers/tags_spec.js @@ -1,9 +1,9 @@ -const should = require('should'), - sinon = require('sinon'), - testUtils = require('../../utils'), - urlService = require('../../../core/frontend/services/url'), - models = require('../../../core/server/models'), - helpers = require('../../../core/frontend/helpers'); +const should = require('should'); +const sinon = require('sinon'); +const testUtils = require('../../utils'); +const urlService = require('../../../core/frontend/services/url'); +const models = require('../../../core/server/models'); +const helpers = require('../../../core/frontend/helpers'); describe('{{tags}} helper', function () { before(function () { diff --git a/test/unit/helpers/title_spec.js b/test/unit/helpers/title_spec.js index 1fe1e2652f..cae1a0a593 100644 --- a/test/unit/helpers/title_spec.js +++ b/test/unit/helpers/title_spec.js @@ -1,31 +1,31 @@ -var should = require('should'), +const should = require('should'); - // Stuff we are testing - helpers = require('../../../core/frontend/helpers'); +// Stuff we are testing +const helpers = require('../../../core/frontend/helpers'); describe('{{title}} Helper', function () { it('can render title', function () { - var title = 'Hello World', - rendered = helpers.title.call({title: title}); + const title = 'Hello World'; + const rendered = helpers.title.call({title: title}); should.exist(rendered); rendered.string.should.equal(title); }); it('escapes correctly', function () { - var rendered = helpers.title.call({title: '

      I am a title

      '}); + const rendered = helpers.title.call({title: '

      I am a title

      '}); rendered.string.should.equal('<h1>I am a title</h1>'); }); it('returns a blank string where title is missing', function () { - var rendered = helpers.title.call({title: null}); + const rendered = helpers.title.call({title: null}); rendered.string.should.equal(''); }); it('returns a blank string where data missing', function () { - var rendered = helpers.title.call({}); + const rendered = helpers.title.call({}); rendered.string.should.equal(''); }); diff --git a/test/unit/helpers/twitter_url_spec.js b/test/unit/helpers/twitter_url_spec.js index abc9fb1cf9..aa89138a83 100644 --- a/test/unit/helpers/twitter_url_spec.js +++ b/test/unit/helpers/twitter_url_spec.js @@ -1,10 +1,10 @@ -var should = require('should'), +const should = require('should'); - // Stuff we are testing - helpers = require('../../../core/frontend/helpers'); +// Stuff we are testing +const helpers = require('../../../core/frontend/helpers'); describe('{{twitter_url}} helper', function () { - var options = {data: {site: {}}}; + const options = {data: {site: {}}}; beforeEach(function () { options.data.site = {twitter: ''}; diff --git a/test/unit/helpers/url_spec.js b/test/unit/helpers/url_spec.js index 6f9c3b2219..436e36204c 100644 --- a/test/unit/helpers/url_spec.js +++ b/test/unit/helpers/url_spec.js @@ -1,12 +1,12 @@ -var should = require('should'), - sinon = require('sinon'), - Promise = require('bluebird'), - testUtils = require('../../utils'), - urlUtils = require('../../utils/urlUtils'), - markdownToMobiledoc = require('../../utils/fixtures/data-generator').markdownToMobiledoc, - helpers = require('../../../core/frontend/helpers'), - urlService = require('../../../core/frontend/services/url'), - api = require('../../../core/server/api'); +const should = require('should'); +const sinon = require('sinon'); +const Promise = require('bluebird'); +const testUtils = require('../../utils'); +const urlUtils = require('../../utils/urlUtils'); +const markdownToMobiledoc = require('../../utils/fixtures/data-generator').markdownToMobiledoc; +const helpers = require('../../../core/frontend/helpers'); +const urlService = require('../../../core/frontend/services/url'); +const api = require('../../../core/server/api'); describe('{{url}} helper', function () { let rendered; diff --git a/test/unit/lib/common/errors_spec.js b/test/unit/lib/common/errors_spec.js index 4e4c1c2155..c262a5f1fd 100644 --- a/test/unit/lib/common/errors_spec.js +++ b/test/unit/lib/common/errors_spec.js @@ -1,15 +1,16 @@ -var should = require('should'), - common = require('../../../../core/server/lib/common'); +const should = require('should'); +const common = require('../../../../core/server/lib/common'); describe('Errors', function () { it('Ensure we inherit from Error', function () { - var ghostError = new common.errors.GhostError(); + const ghostError = new common.errors.GhostError(); (ghostError instanceof Error).should.eql(true); }); describe('Inherite from other error', function () { it('default', function () { - var someError = new Error(), ghostError; + const someError = new Error(); + let ghostError; someError.message = 'test'; someError.context = 'test'; @@ -22,7 +23,8 @@ describe('Errors', function () { }); it('has nested object', function () { - var someError = new Error(), ghostError; + const someError = new Error(); + let ghostError; someError.obj = { a: 'b' @@ -36,7 +38,8 @@ describe('Errors', function () { }); it('with custom attribute', function () { - var someError = new Error(), ghostError; + const someError = new Error(); + let ghostError; someError.context = 'test'; @@ -49,7 +52,8 @@ describe('Errors', function () { }); it('with custom attribute', function () { - var someError = new Error(), ghostError; + const someError = new Error(); + let ghostError; ghostError = new common.errors.GhostError({ err: someError, @@ -60,7 +64,7 @@ describe('Errors', function () { }); it('error is string', function () { - var ghostError = new common.errors.GhostError({ + const ghostError = new common.errors.GhostError({ err: 'string' }); diff --git a/test/unit/lib/fs/package-json/filter_spec.js b/test/unit/lib/fs/package-json/filter_spec.js index 3c7f3358d2..d3b1709a56 100644 --- a/test/unit/lib/fs/package-json/filter_spec.js +++ b/test/unit/lib/fs/package-json/filter_spec.js @@ -1,44 +1,46 @@ -var should = require('should'), - packageJSON = require('../../../../../core/server/lib/fs/package-json'); +const should = require('should'); +const packageJSON = require('../../../../../core/server/lib/fs/package-json'); describe('lib/fs/package-json', function () { // @TODO: introduce some non-theme package examples - var casper = { + const casper = { + name: 'casper', + path: '~/content/themes/casper', + 'package.json': { name: 'casper', - path: '~/content/themes/casper', - 'package.json': { - name: 'casper', - description: 'The default personal blogging theme for Ghost. Beautiful, minimal and responsive.', - demo: 'https://demo.ghost.io', - version: '1.3.5', - engines: {}, - license: 'MIT', - screenshots: {}, - author: {}, - gpm: {}, - keywords: {}, - repository: {}, - bugs: 'https://github.com/TryGhost/Casper/issues', - contributors: 'https://github.com/TryGhost/Casper/graphs/contributors' - } - }, - simplePackage = { + description: 'The default personal blogging theme for Ghost. Beautiful, minimal and responsive.', + demo: 'https://demo.ghost.io', + version: '1.3.5', + engines: {}, + license: 'MIT', + screenshots: {}, + author: {}, + gpm: {}, + keywords: {}, + repository: {}, + bugs: 'https://github.com/TryGhost/Casper/issues', + contributors: 'https://github.com/TryGhost/Casper/graphs/contributors' + } + }; + + const simplePackage = { + name: 'simple', + path: '~/content/themes/simple', + 'package.json': { name: 'simple', - path: '~/content/themes/simple', - 'package.json': { - name: 'simple', - version: '0.1.0' - } - }, - missingPackageJson = { - name: 'missing', - path: '~/content/themes/missing', - 'package.json': null - }; + version: '0.1.0' + } + }; + + const missingPackageJson = { + name: 'missing', + path: '~/content/themes/missing', + 'package.json': null + }; it('should filter packages correctly', function () { - var result = packageJSON.filter({casper: casper}), - package1; + const result = packageJSON.filter({casper: casper}); + let package1; result.should.be.an.Array().with.lengthOf(1); package1 = result[0]; @@ -51,8 +53,9 @@ describe('lib/fs/package-json', function () { }); it('should filter packages and handle a single active package string', function () { - var result = packageJSON.filter({casper: casper, simple: simplePackage}, 'casper'), - package1, package2; + const result = packageJSON.filter({casper: casper, simple: simplePackage}, 'casper'); + let package1; + let package2; result.should.be.an.Array().with.lengthOf(2); package1 = result[0]; @@ -72,8 +75,9 @@ describe('lib/fs/package-json', function () { }); it('should filter packages and handle an array of active packages', function () { - var result = packageJSON.filter({casper: casper, simple: simplePackage}, ['casper', 'simple']), - package1, package2; + const result = packageJSON.filter({casper: casper, simple: simplePackage}, ['casper', 'simple']); + let package1; + let package2; result.should.be.an.Array().with.lengthOf(2); package1 = result[0]; @@ -93,8 +97,9 @@ describe('lib/fs/package-json', function () { }); it('handles packages with no package.json even though this makes us sad', function () { - var result = packageJSON.filter({casper: casper, missing: missingPackageJson}, ['casper']), - package1, package2; + const result = packageJSON.filter({casper: casper, missing: missingPackageJson}, ['casper']); + let package1; + let package2; result.should.be.an.Array().with.lengthOf(2); package1 = result[0]; @@ -114,7 +119,7 @@ describe('lib/fs/package-json', function () { }); it('filters out things which are not packages', function () { - var result = packageJSON.filter({ + const result = packageJSON.filter({ '.git': {}, '.anything': {}, 'README.md': {}, _messages: {} }); result.should.be.an.Array().with.lengthOf(0); diff --git a/test/unit/lib/fs/package-json/parse_spec.js b/test/unit/lib/fs/package-json/parse_spec.js index 40212eef03..0de6ff8478 100644 --- a/test/unit/lib/fs/package-json/parse_spec.js +++ b/test/unit/lib/fs/package-json/parse_spec.js @@ -1,11 +1,12 @@ -var should = require('should'), - tmp = require('tmp'), - fs = require('fs-extra'), - packageJSON = require('../../../../../core/server/lib/fs/package-json'); +const should = require('should'); +const tmp = require('tmp'); +const fs = require('fs-extra'); +const packageJSON = require('../../../../../core/server/lib/fs/package-json'); describe('lib/fs/package-json: parse', function () { it('should parse valid package.json', function (done) { - var pkgJson, tmpFile; + let pkgJson; + let tmpFile; tmpFile = tmp.fileSync(); pkgJson = JSON.stringify({ @@ -29,7 +30,8 @@ describe('lib/fs/package-json: parse', function () { }); it('should fail when name is missing', function (done) { - var pkgJson, tmpFile; + let pkgJson; + let tmpFile; tmpFile = tmp.fileSync(); pkgJson = JSON.stringify({ @@ -54,7 +56,8 @@ describe('lib/fs/package-json: parse', function () { }); it('should fail when version is missing', function (done) { - var pkgJson, tmpFile; + let pkgJson; + let tmpFile; tmpFile = tmp.fileSync(); pkgJson = JSON.stringify({ @@ -79,7 +82,8 @@ describe('lib/fs/package-json: parse', function () { }); it('should fail when JSON is invalid', function (done) { - var pkgJson, tmpFile; + let pkgJson; + let tmpFile; tmpFile = tmp.fileSync(); pkgJson = '{name:"test"}'; @@ -102,7 +106,7 @@ describe('lib/fs/package-json: parse', function () { }); it('should fail when file is missing', function (done) { - var tmpFile = tmp.fileSync(); + const tmpFile = tmp.fileSync(); tmpFile.removeCallback(); packageJSON.parse(tmpFile.name) diff --git a/test/unit/lib/fs/package-json/read_spec.js b/test/unit/lib/fs/package-json/read_spec.js index 8dd25296d1..bebd09626b 100644 --- a/test/unit/lib/fs/package-json/read_spec.js +++ b/test/unit/lib/fs/package-json/read_spec.js @@ -1,13 +1,13 @@ -var should = require('should'), - tmp = require('tmp'), - join = require('path').join, - fs = require('fs-extra'), - packageJSON = require('../../../../../core/server/lib/fs/package-json'); +const should = require('should'); +const tmp = require('tmp'); +const join = require('path').join; +const fs = require('fs-extra'); +const packageJSON = require('../../../../../core/server/lib/fs/package-json'); describe('lib/fs/package-json: read', function () { describe('all', function () { it('should read directory and ignore unneeded items', function (done) { - var packagePath = tmp.dirSync({unsafeCleanup: true}); + const packagePath = tmp.dirSync({unsafeCleanup: true}); // create example theme fs.mkdirSync(join(packagePath.name, 'casper')); @@ -36,7 +36,8 @@ describe('lib/fs/package-json: read', function () { }); it('should read directory and parse package.json files', function (done) { - var packagePath, pkgJson; + let packagePath; + let pkgJson; packagePath = tmp.dirSync({unsafeCleanup: true}); pkgJson = JSON.stringify({ @@ -69,7 +70,8 @@ describe('lib/fs/package-json: read', function () { }); it('should read directory and ignore invalid package.json files', function (done) { - var packagePath, pkgJson; + let packagePath; + let pkgJson; packagePath = tmp.dirSync({unsafeCleanup: true}); pkgJson = JSON.stringify({ @@ -100,7 +102,7 @@ describe('lib/fs/package-json: read', function () { describe('one', function () { it('should read directory and ignore unneeded items', function (done) { - var packagePath = tmp.dirSync({unsafeCleanup: true}); + const packagePath = tmp.dirSync({unsafeCleanup: true}); // create example theme fs.mkdirSync(join(packagePath.name, 'casper')); @@ -129,7 +131,8 @@ describe('lib/fs/package-json: read', function () { }); it('should read directory and parse package.json files', function (done) { - var packagePath, pkgJson; + let packagePath; + let pkgJson; packagePath = tmp.dirSync({unsafeCleanup: true}); pkgJson = JSON.stringify({ @@ -162,7 +165,8 @@ describe('lib/fs/package-json: read', function () { }); it('should read directory and ignore invalid package.json files', function (done) { - var packagePath, pkgJson; + let packagePath; + let pkgJson; packagePath = tmp.dirSync({unsafeCleanup: true}); pkgJson = JSON.stringify({ @@ -191,7 +195,7 @@ describe('lib/fs/package-json: read', function () { }); it('should read directory and include only single requested package', function (done) { - var packagePath = tmp.dirSync({unsafeCleanup: true}); + const packagePath = tmp.dirSync({unsafeCleanup: true}); // create trash fs.writeFileSync(join(packagePath.name, 'casper.zip')); @@ -222,7 +226,7 @@ describe('lib/fs/package-json: read', function () { }); it('should return an error if package cannot be found', function (done) { - var packagePath = tmp.dirSync({unsafeCleanup: true}); + const packagePath = tmp.dirSync({unsafeCleanup: true}); // create trash fs.writeFileSync(join(packagePath.name, 'casper.zip')); @@ -240,7 +244,7 @@ describe('lib/fs/package-json: read', function () { }); it('should return empty object if package is not a directory', function (done) { - var packagePath = tmp.dirSync({unsafeCleanup: true}); + const packagePath = tmp.dirSync({unsafeCleanup: true}); // create trash fs.writeFileSync(join(packagePath.name, 'casper.zip')); diff --git a/test/unit/lib/fs/read-csv_spec.js b/test/unit/lib/fs/read-csv_spec.js index a692c73ce5..a7c69e5669 100644 --- a/test/unit/lib/fs/read-csv_spec.js +++ b/test/unit/lib/fs/read-csv_spec.js @@ -1,7 +1,7 @@ -var should = require('should'), - path = require('path'), - fsLib = require('../../../../core/server/lib/fs'), - csvPath = path.join(__dirname, '../../../utils/fixtures/csv/'); +const should = require('should'); +const path = require('path'); +const fsLib = require('../../../../core/server/lib/fs'); +const csvPath = path.join(__dirname, '../../../utils/fixtures/csv/'); describe('lib/fs: read csv', function () { it('read csv: one column', function (done) { diff --git a/test/unit/lib/ghost-version_spec.js b/test/unit/lib/ghost-version_spec.js index 5441f6020b..92509a8332 100644 --- a/test/unit/lib/ghost-version_spec.js +++ b/test/unit/lib/ghost-version_spec.js @@ -2,7 +2,8 @@ const should = require('should'); const rewire = require('rewire'); const mockUtils = require('../../utils/mocks'); -let ghostVersionUtils, version; +let ghostVersionUtils; +let version; describe('Utils: Ghost Version', function () { const beforeEachIt = function be() { diff --git a/test/unit/lib/image/blog-icon_spec.js b/test/unit/lib/image/blog-icon_spec.js index 470b6ca4b1..7bd577435e 100644 --- a/test/unit/lib/image/blog-icon_spec.js +++ b/test/unit/lib/image/blog-icon_spec.js @@ -1,14 +1,14 @@ -var should = require('should'), - sinon = require('sinon'), - _ = require('lodash'), - path = require('path'), - rewire = require('rewire'), - settingsCache = require('../../../../core/server/services/settings/cache'), - storageUtils = require('../../../../core/server/adapters/storage/utils'), - urlUtils = require('../../../utils/urlUtils'), +const should = require('should'); +const sinon = require('sinon'); +const _ = require('lodash'); +const path = require('path'); +const rewire = require('rewire'); +const settingsCache = require('../../../../core/server/services/settings/cache'); +const storageUtils = require('../../../../core/server/adapters/storage/utils'); +const urlUtils = require('../../../utils/urlUtils'); - // stuff we are testing - blogIcon = rewire('../../../../core/server/lib/image/blog-icon'); +// stuff we are testing +const blogIcon = rewire('../../../../core/server/lib/image/blog-icon'); describe('lib/image: blog icon', function () { afterEach(function () { @@ -152,7 +152,7 @@ describe('lib/image: blog icon', function () { }); it('[failure] return error message', function (done) { - var sizeOfStub = sinon.stub(); + const sizeOfStub = sinon.stub(); sizeOfStub.throws({error: 'image-size could not find dimensions'}); diff --git a/test/unit/lib/image/cached-image-size-from-url_spec.js b/test/unit/lib/image/cached-image-size-from-url_spec.js index 6fe8635c0d..9d6dba3c8e 100644 --- a/test/unit/lib/image/cached-image-size-from-url_spec.js +++ b/test/unit/lib/image/cached-image-size-from-url_spec.js @@ -1,14 +1,14 @@ -var should = require('should'), - sinon = require('sinon'), - Promise = require('bluebird'), - rewire = require('rewire'), +const should = require('should'); +const sinon = require('sinon'); +const Promise = require('bluebird'); +const rewire = require('rewire'); - // Stuff we are testing - getCachedImageSizeFromUrl = rewire('../../../../core/server/lib/image/cached-image-size-from-url'); +// Stuff we are testing +const getCachedImageSizeFromUrl = rewire('../../../../core/server/lib/image/cached-image-size-from-url'); describe('lib/image: image size cache', function () { - var sizeOfStub, - cachedImagedSize; + let sizeOfStub; + let cachedImagedSize; beforeEach(function () { sizeOfStub = sinon.stub(); @@ -20,9 +20,9 @@ describe('lib/image: image size cache', function () { }); it('should read from cache, if dimensions for image are fetched already', function (done) { - var url = 'http://mysite.com/content/image/mypostcoverimage.jpg', - cachedImagedSizeResult, - imageSizeSpy; + const url = 'http://mysite.com/content/image/mypostcoverimage.jpg'; + let cachedImagedSizeResult; + let imageSizeSpy; sizeOfStub.returns(new Promise.resolve({ width: 50, @@ -64,8 +64,8 @@ describe('lib/image: image size cache', function () { }); it('can handle image-size errors', function (done) { - var url = 'http://mysite.com/content/image/mypostcoverimage.jpg', - cachedImagedSizeResult; + const url = 'http://mysite.com/content/image/mypostcoverimage.jpg'; + let cachedImagedSizeResult; sizeOfStub.returns(new Promise.reject('error')); @@ -83,8 +83,8 @@ describe('lib/image: image size cache', function () { }); it('should return null if url is undefined', function (done) { - var url = null, - result; + const url = null; + let result; result = getCachedImageSizeFromUrl(url); diff --git a/test/unit/lib/image/gravatar_spec.js b/test/unit/lib/image/gravatar_spec.js index 755df638f9..0258787140 100644 --- a/test/unit/lib/image/gravatar_spec.js +++ b/test/unit/lib/image/gravatar_spec.js @@ -1,7 +1,7 @@ -var should = require('should'), - nock = require('nock'), - configUtils = require('../../../utils/configUtils'), - gravatar = require('../../../../core/server/lib/image/gravatar'); +const should = require('should'); +const nock = require('nock'); +const configUtils = require('../../../utils/configUtils'); +const gravatar = require('../../../../core/server/lib/image/gravatar'); describe('lib/image: gravatar', function () { beforeEach(function () { diff --git a/test/unit/lib/image/image-size_spec.js b/test/unit/lib/image/image-size_spec.js index 9e57c7ef1c..1464dd300b 100644 --- a/test/unit/lib/image/image-size_spec.js +++ b/test/unit/lib/image/image-size_spec.js @@ -1,12 +1,12 @@ -const should = require('should'), - sinon = require('sinon'), - rewire = require('rewire'), - nock = require('nock'), - path = require('path'), - configUtils = require('../../../utils/configUtils'), - urlUtils = require('../../../../core/server/lib/url-utils'), - errors = require('@tryghost/errors'), - storage = require('../../../../core/server/adapters/storage'); +const should = require('should'); +const sinon = require('sinon'); +const rewire = require('rewire'); +const nock = require('nock'); +const path = require('path'); +const configUtils = require('../../../utils/configUtils'); +const urlUtils = require('../../../../core/server/lib/url-utils'); +const errors = require('@tryghost/errors'); +const storage = require('../../../../core/server/adapters/storage'); describe('lib/image: image size', function () { let imageSize; diff --git a/test/unit/lib/promise/pipeline_spec.js b/test/unit/lib/promise/pipeline_spec.js index ada7531fea..11a72456e1 100644 --- a/test/unit/lib/promise/pipeline_spec.js +++ b/test/unit/lib/promise/pipeline_spec.js @@ -1,9 +1,9 @@ -var should = require('should'), - sinon = require('sinon'), - Promise = require('bluebird'), +const should = require('should'); +const sinon = require('sinon'); +const Promise = require('bluebird'); - // Stuff we are testing - pipeline = require('../../../../core/server/lib/promise/pipeline'); +// Stuff we are testing +const pipeline = require('../../../../core/server/lib/promise/pipeline'); // These tests are based on the tests in https://github.com/cujojs/when/blob/3.7.4/test/pipeline-test.js function createTask(y) { @@ -36,8 +36,8 @@ describe('Pipeline', function () { }); it('should pass args to initial task', function () { - var expected = [1, 2, 3], - tasks = [sinon.spy()]; + const expected = [1, 2, 3]; + const tasks = [sinon.spy()]; return pipeline(tasks, 1, 2, 3).then(function () { tasks[0].calledOnce.should.be.true(); @@ -46,9 +46,9 @@ describe('Pipeline', function () { }); it('should allow initial args to be promises', function () { - var expected = [1, 2, 3], - tasks = [sinon.spy()], - Resolver = Promise.resolve; + const expected = [1, 2, 3]; + const tasks = [sinon.spy()]; + const Resolver = Promise.resolve; return pipeline(tasks, new Resolver(1), new Resolver(2), new Resolver(3)).then(function () { tasks[0].calledOnce.should.be.true(); @@ -57,12 +57,13 @@ describe('Pipeline', function () { }); it('should allow tasks to be promises', function () { - var expected = [1, 2, 3], - tasks = [ - sinon.stub().returns(new Promise.resolve(4)), - sinon.stub().returns(new Promise.resolve(5)), - sinon.stub().returns(new Promise.resolve(6)) - ]; + const expected = [1, 2, 3]; + + const tasks = [ + sinon.stub().returns(new Promise.resolve(4)), + sinon.stub().returns(new Promise.resolve(5)), + sinon.stub().returns(new Promise.resolve(6)) + ]; return pipeline(tasks, 1, 2, 3).then(function (result) { result.should.eql(6); @@ -76,13 +77,15 @@ describe('Pipeline', function () { }); it('should allow tasks and args to be promises', function () { - var expected = [1, 2, 3], - tasks = [ - sinon.stub().returns(new Promise.resolve(4)), - sinon.stub().returns(new Promise.resolve(5)), - sinon.stub().returns(new Promise.resolve(6)) - ], - Resolver = Promise.resolve; + const expected = [1, 2, 3]; + + const tasks = [ + sinon.stub().returns(new Promise.resolve(4)), + sinon.stub().returns(new Promise.resolve(5)), + sinon.stub().returns(new Promise.resolve(6)) + ]; + + const Resolver = Promise.resolve; return pipeline(tasks, new Resolver(1), new Resolver(2), new Resolver(3)).then(function (result) { result.should.eql(6); diff --git a/test/unit/lib/security/password_spec.js b/test/unit/lib/security/password_spec.js index e728034bcf..9b66e8d275 100644 --- a/test/unit/lib/security/password_spec.js +++ b/test/unit/lib/security/password_spec.js @@ -1,5 +1,5 @@ -const should = require('should'), - security = require('../../../../core/server/lib/security'); +const should = require('should'); +const security = require('../../../../core/server/lib/security'); describe('Lib: Security - Password', function () { it('hash plain password', function () { diff --git a/test/unit/lib/security/string_spec.js b/test/unit/lib/security/string_spec.js index c95ef90cd5..2d50e115b1 100644 --- a/test/unit/lib/security/string_spec.js +++ b/test/unit/lib/security/string_spec.js @@ -1,92 +1,92 @@ -var should = require('should'), - security = require('../../../../core/server/lib/security'); +const should = require('should'); +const security = require('../../../../core/server/lib/security'); describe('Lib: Security - String', function () { describe('Safe String', function () { - var options = {}; + const options = {}; it('should remove beginning and ending whitespace', function () { - var result = security.string.safe(' stringwithspace ', options); + const result = security.string.safe(' stringwithspace ', options); result.should.equal('stringwithspace'); }); it('can handle null strings', function () { - var result = security.string.safe(null); + const result = security.string.safe(null); result.should.equal(''); }); it('should remove non ascii characters', function () { - var result = security.string.safe('howtowin✓', options); + const result = security.string.safe('howtowin✓', options); result.should.equal('howtowin'); }); it('should replace spaces with dashes', function () { - var result = security.string.safe('how to win', options); + const result = security.string.safe('how to win', options); result.should.equal('how-to-win'); }); it('should replace most special characters with dashes', function () { - var result = security.string.safe('a:b/c?d#e[f]g!h$i&j(k)l*m+n,o;{p}=q\\r%su|v^w~x£y"z@1.2`3', options); + const result = security.string.safe('a:b/c?d#e[f]g!h$i&j(k)l*m+n,o;{p}=q\\r%su|v^w~x£y"z@1.2`3', options); result.should.equal('a-b-c-d-e-f-g-h-i-j-k-l-m-n-o-p-q-r-s-t-u-v-w-x-y-z-1-2-3'); }); it('should replace all of the html4 compat symbols in ascii except hyphen and underscore', function () { // note: This is missing the soft-hyphen char that isn't much-liked by linters/browsers/etc, // it passed the test before it was removed - var result = security.string.safe('!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿'); + const result = security.string.safe('!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿'); result.should.equal('_-c-y-ss-c-a-r-deg-23up-1o-1-41-23-4'); }); it('should replace all of the foreign chars in ascii', function () { - var result = security.string.safe('ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ'); + const result = security.string.safe('ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ'); result.should.equal('aaaaaaaeceeeeiiiidnoooooxouuuuuthssaaaaaaaeceeeeiiiidnooooo-ouuuuythy'); }); it('should remove special characters at the beginning of a string', function () { - var result = security.string.safe('.Not special', options); + const result = security.string.safe('.Not special', options); result.should.equal('not-special'); }); it('should remove apostrophes ', function () { - var result = security.string.safe('how we shouldn\'t be', options); + const result = security.string.safe('how we shouldn\'t be', options); result.should.equal('how-we-shouldnt-be'); }); it('should convert to lowercase', function () { - var result = security.string.safe('This has Upper Case', options); + const result = security.string.safe('This has Upper Case', options); result.should.equal('this-has-upper-case'); }); it('should convert multiple dashes into a single dash', function () { - var result = security.string.safe('This :) means everything', options); + const result = security.string.safe('This :) means everything', options); result.should.equal('this-means-everything'); }); it('should remove trailing dashes from the result', function () { - var result = security.string.safe('This.', options); + const result = security.string.safe('This.', options); result.should.equal('this'); }); it('should handle pound signs', function () { - var result = security.string.safe('WHOOPS! I spent all my £ again!', options); + const result = security.string.safe('WHOOPS! I spent all my £ again!', options); result.should.equal('whoops-i-spent-all-my-again'); }); it('should properly handle unicode punctuation conversion', function () { - var result = security.string.safe('に間違いがないか、再度確認してください。再読み込みしてください。', options); + const result = security.string.safe('に間違いがないか、再度確認してください。再読み込みしてください。', options); result.should.equal('nijian-wei-iganaika-zai-du-que-ren-sitekudasai-zai-du-miip-misitekudasai'); }); it('should not lose or convert dashes if options are passed with truthy importing flag', function () { - var result, - options = {importing: true}; + let result; + const options = {importing: true}; result = security.string.safe('-slug-with-starting-ending-and---multiple-dashes-', options); result.should.equal('-slug-with-starting-ending-and---multiple-dashes-'); }); it('should still remove/convert invalid characters when passed options with truthy importing flag', function () { - var result, - options = {importing: true}; + let result; + const options = {importing: true}; result = security.string.safe('-slug-&with-✓-invalid-characters-に\'', options); result.should.equal('-slug--with--invalid-characters-ni'); }); diff --git a/test/unit/lib/security/tokens_spec.js b/test/unit/lib/security/tokens_spec.js index 319f4aa7e2..e075c93eb5 100644 --- a/test/unit/lib/security/tokens_spec.js +++ b/test/unit/lib/security/tokens_spec.js @@ -1,11 +1,12 @@ -var should = require('should'), - uuid = require('uuid'), - security = require('../../../../core/server/lib/security'); +const should = require('should'); +const uuid = require('uuid'); +const security = require('../../../../core/server/lib/security'); describe('Utils: tokens', function () { it('generate', function () { - var expires = Date.now() + 60 * 1000, - dbHash = uuid.v4(), token; + const expires = Date.now() + 60 * 1000; + const dbHash = uuid.v4(); + let token; token = security.tokens.resetToken.generateHash({ email: 'test1@ghost.org', @@ -19,8 +20,10 @@ describe('Utils: tokens', function () { }); it('compare: success', function () { - var expires = Date.now() + 60 * 1000, - dbHash = uuid.v4(), token, tokenIsCorrect; + const expires = Date.now() + 60 * 1000; + const dbHash = uuid.v4(); + let token; + let tokenIsCorrect; token = security.tokens.resetToken.generateHash({ email: 'test1@ghost.org', @@ -39,8 +42,10 @@ describe('Utils: tokens', function () { }); it('compare: error', function () { - var expires = Date.now() + 60 * 1000, - dbHash = uuid.v4(), token, tokenIsCorrect; + const expires = Date.now() + 60 * 1000; + const dbHash = uuid.v4(); + let token; + let tokenIsCorrect; token = security.tokens.resetToken.generateHash({ email: 'test1@ghost.org', @@ -59,8 +64,11 @@ describe('Utils: tokens', function () { }); it('extract', function () { - var expires = Date.now() + 60 * 1000, - dbHash = uuid.v4(), token, parts, email = 'test1@ghost.org'; + const expires = Date.now() + 60 * 1000; + const dbHash = uuid.v4(); + let token; + let parts; + const email = 'test1@ghost.org'; token = security.tokens.resetToken.generateHash({ email: email, @@ -80,8 +88,11 @@ describe('Utils: tokens', function () { }); it('extract', function () { - var expires = Date.now() + 60 * 1000, - dbHash = uuid.v4(), token, parts, email = 'test3@ghost.org'; + const expires = Date.now() + 60 * 1000; + const dbHash = uuid.v4(); + let token; + let parts; + const email = 'test3@ghost.org'; token = security.tokens.resetToken.generateHash({ email: email, @@ -101,9 +112,12 @@ describe('Utils: tokens', function () { }); it('can validate an URI encoded reset token', function () { - var expires = Date.now() + 60 * 1000, - email = 'test1@ghost.org', - dbHash = uuid.v4(), token, tokenIsCorrect, parts; + const expires = Date.now() + 60 * 1000; + const email = 'test1@ghost.org'; + const dbHash = uuid.v4(); + let token; + let tokenIsCorrect; + let parts; token = security.tokens.resetToken.generateHash({ email: email, diff --git a/test/unit/models/base/index_spec.js b/test/unit/models/base/index_spec.js index fa5e814782..cab68c4943 100644 --- a/test/unit/models/base/index_spec.js +++ b/test/unit/models/base/index_spec.js @@ -1,12 +1,12 @@ -var should = require('should'), - sinon = require('sinon'), - _ = require('lodash'), - Promise = require('bluebird'), - security = require('../../../../core/server/lib/security'), - models = require('../../../../core/server/models'), - common = require('../../../../core/server/lib/common'), - urlUtils = require('../../../../core/server/lib/url-utils'), - testUtils = require('../../../utils'); +const should = require('should'); +const sinon = require('sinon'); +const _ = require('lodash'); +const Promise = require('bluebird'); +const security = require('../../../../core/server/lib/security'); +const models = require('../../../../core/server/models'); +const common = require('../../../../core/server/lib/common'); +const urlUtils = require('../../../../core/server/lib/url-utils'); +const testUtils = require('../../../utils'); describe('Models: base', function () { before(function () { diff --git a/test/unit/models/invite_spec.js b/test/unit/models/invite_spec.js index c18ca785a0..ff00343218 100644 --- a/test/unit/models/invite_spec.js +++ b/test/unit/models/invite_spec.js @@ -1,10 +1,10 @@ -const should = require('should'), - sinon = require('sinon'), - Promise = require('bluebird'), - common = require('../../../core/server/lib/common'), - models = require('../../../core/server/models'), - settingsCache = require('../../../core/server/services/settings/cache'), - testUtils = require('../../utils'); +const should = require('should'); +const sinon = require('sinon'); +const Promise = require('bluebird'); +const common = require('../../../core/server/lib/common'); +const models = require('../../../core/server/models'); +const settingsCache = require('../../../core/server/services/settings/cache'); +const testUtils = require('../../utils'); describe('Unit: models/invite', function () { before(function () { diff --git a/test/unit/models/permission_spec.js b/test/unit/models/permission_spec.js index 34dd305d48..9d8b394a97 100644 --- a/test/unit/models/permission_spec.js +++ b/test/unit/models/permission_spec.js @@ -1,8 +1,8 @@ -const should = require('should'), - sinon = require('sinon'), - models = require('../../../core/server/models'), - testUtils = require('../../utils'), - configUtils = require('../../utils/configUtils'); +const should = require('should'); +const sinon = require('sinon'); +const models = require('../../../core/server/models'); +const testUtils = require('../../utils'); +const configUtils = require('../../utils/configUtils'); describe('Unit: models/permission', function () { before(function () { diff --git a/test/unit/models/plugins/pagination_spec.js b/test/unit/models/plugins/pagination_spec.js index d25847b326..54247a2865 100644 --- a/test/unit/models/plugins/pagination_spec.js +++ b/test/unit/models/plugins/pagination_spec.js @@ -1,11 +1,11 @@ -var should = require('should'), - sinon = require('sinon'), - Promise = require('bluebird'), - rewire = require('rewire'), - pagination = rewire('../../../../core/server/models/plugins/pagination'); +const should = require('should'); +const sinon = require('sinon'); +const Promise = require('bluebird'); +const rewire = require('rewire'); +const pagination = rewire('../../../../core/server/models/plugins/pagination'); describe('pagination', function () { - var paginationUtils; + let paginationUtils; afterEach(function () { sinon.restore(); @@ -17,7 +17,7 @@ describe('pagination', function () { }); describe('formatResponse', function () { - var formatResponse; + let formatResponse; before(function () { formatResponse = paginationUtils.formatResponse; @@ -91,7 +91,7 @@ describe('pagination', function () { }); describe('parseOptions', function () { - var parseOptions; + let parseOptions; before(function () { parseOptions = paginationUtils.parseOptions; @@ -135,8 +135,8 @@ describe('pagination', function () { }); describe('addLimitAndOffset', function () { - var addLimitAndOffset, - collection = {}; + let addLimitAndOffset; + const collection = {}; before(function () { addLimitAndOffset = paginationUtils.addLimitAndOffset; @@ -163,7 +163,10 @@ describe('pagination', function () { }); describe('fetchPage', function () { - var model, bookshelf, knex, mockQuery; + let model; + let bookshelf; + let knex; + let mockQuery; before(function () { paginationUtils = pagination.__get__('paginationUtils'); @@ -240,7 +243,7 @@ describe('pagination', function () { }); it('calls all paginationUtils and methods when order set', function (done) { - var orderOptions = {order: {id: 'DESC'}}; + const orderOptions = {order: {id: 'DESC'}}; paginationUtils.parseOptions.returns(orderOptions); bookshelf.Model.prototype.fetchPage(orderOptions).then(function () { @@ -279,7 +282,7 @@ describe('pagination', function () { }); it('calls all paginationUtils and methods when group by set', function (done) { - var groupOptions = {groups: ['posts.id']}; + const groupOptions = {groups: ['posts.id']}; paginationUtils.parseOptions.returns(groupOptions); bookshelf.Model.prototype.fetchPage(groupOptions).then(function () { diff --git a/test/unit/models/post_spec.js b/test/unit/models/post_spec.js index 3abdf36ff2..be3c577455 100644 --- a/test/unit/models/post_spec.js +++ b/test/unit/models/post_spec.js @@ -368,12 +368,12 @@ describe('Unit: models/post: uses database (@TODO: fix me)', function () { describe('As Contributor', function () { describe('Editing', function () { it('rejects if changing status', function (done) { - var mockPostObj = { - get: sinon.stub(), - related: sinon.stub() - }, - context = {user: 1}, - unsafeAttrs = {status: 'published'}; + const mockPostObj = { + get: sinon.stub(), + related: sinon.stub() + }; + const context = {user: 1}; + const unsafeAttrs = {status: 'published'}; mockPostObj.get.withArgs('status').returns('draft'); mockPostObj.related.withArgs('authors').returns({models: [{id: 1}]}); @@ -398,12 +398,12 @@ describe('Unit: models/post: uses database (@TODO: fix me)', function () { }); it('rejects if changing visibility', function (done) { - var mockPostObj = { - get: sinon.stub(), - related: sinon.stub() - }, - context = {user: 1}, - unsafeAttrs = {visibility: 'public'}; + const mockPostObj = { + get: sinon.stub(), + related: sinon.stub() + }; + const context = {user: 1}; + const unsafeAttrs = {visibility: 'public'}; mockPostObj.get.withArgs('visibility').returns('paid'); mockPostObj.related.withArgs('authors').returns({models: [{id: 1}]}); @@ -428,12 +428,12 @@ describe('Unit: models/post: uses database (@TODO: fix me)', function () { }); it('rejects if changing author id', function (done) { - var mockPostObj = { - get: sinon.stub(), - related: sinon.stub() - }, - context = {user: 1}, - unsafeAttrs = {status: 'draft', author_id: 2}; + const mockPostObj = { + get: sinon.stub(), + related: sinon.stub() + }; + const context = {user: 1}; + const unsafeAttrs = {status: 'draft', author_id: 2}; mockPostObj.get.withArgs('author_id').returns(1); @@ -457,12 +457,12 @@ describe('Unit: models/post: uses database (@TODO: fix me)', function () { }); it('rejects if changing authors.0', function (done) { - var mockPostObj = { - get: sinon.stub(), - related: sinon.stub() - }, - context = {user: 1}, - unsafeAttrs = {status: 'draft', authors: [{id: 2}]}; + const mockPostObj = { + get: sinon.stub(), + related: sinon.stub() + }; + const context = {user: 1}; + const unsafeAttrs = {status: 'draft', authors: [{id: 2}]}; mockPostObj.related.withArgs('authors').returns({models: [{id: 1}]}); @@ -486,12 +486,12 @@ describe('Unit: models/post: uses database (@TODO: fix me)', function () { }); it('ignores if changes authors.1', function (done) { - var mockPostObj = { - get: sinon.stub(), - related: sinon.stub() - }, - context = {user: 1}, - unsafeAttrs = {status: 'draft', authors: [{id: 1}, {id: 2}]}; + const mockPostObj = { + get: sinon.stub(), + related: sinon.stub() + }; + const context = {user: 1}; + const unsafeAttrs = {status: 'draft', authors: [{id: 1}, {id: 2}]}; mockPostObj.related.withArgs('authors').returns({models: [{id: 1}]}); mockPostObj.get.withArgs('status').returns('draft'); @@ -515,12 +515,12 @@ describe('Unit: models/post: uses database (@TODO: fix me)', function () { }); it('rejects if post is not draft', function (done) { - var mockPostObj = { - get: sinon.stub(), - related: sinon.stub() - }, - context = {user: 1}, - unsafeAttrs = {status: 'published', author_id: 1}; + const mockPostObj = { + get: sinon.stub(), + related: sinon.stub() + }; + const context = {user: 1}; + const unsafeAttrs = {status: 'published', author_id: 1}; mockPostObj.get.withArgs('status').returns('published'); mockPostObj.get.withArgs('author_id').returns(1); @@ -546,12 +546,12 @@ describe('Unit: models/post: uses database (@TODO: fix me)', function () { }); it('rejects if contributor is not author of post', function (done) { - var mockPostObj = { - get: sinon.stub(), - related: sinon.stub() - }, - context = {user: 1}, - unsafeAttrs = {status: 'draft', author_id: 2}; + const mockPostObj = { + get: sinon.stub(), + related: sinon.stub() + }; + const context = {user: 1}; + const unsafeAttrs = {status: 'draft', author_id: 2}; mockPostObj.get.withArgs('status').returns('draft'); mockPostObj.get.withArgs('author_id').returns(1); @@ -577,12 +577,12 @@ describe('Unit: models/post: uses database (@TODO: fix me)', function () { }); it('resolves if none of the above cases are true', function () { - var mockPostObj = { - get: sinon.stub(), - related: sinon.stub() - }, - context = {user: 1}, - unsafeAttrs = {status: 'draft', author_id: 1}; + const mockPostObj = { + get: sinon.stub(), + related: sinon.stub() + }; + const context = {user: 1}; + const unsafeAttrs = {status: 'draft', author_id: 1}; mockPostObj.get.withArgs('status').returns('draft'); mockPostObj.get.withArgs('author_id').returns(1); @@ -608,11 +608,11 @@ describe('Unit: models/post: uses database (@TODO: fix me)', function () { describe('Adding', function () { it('rejects if "published" status', function (done) { - var mockPostObj = { - get: sinon.stub() - }, - context = {user: 1}, - unsafeAttrs = {status: 'published', author_id: 1}; + const mockPostObj = { + get: sinon.stub() + }; + const context = {user: 1}; + const unsafeAttrs = {status: 'published', author_id: 1}; models.Post.permissible( mockPostObj, @@ -633,11 +633,11 @@ describe('Unit: models/post: uses database (@TODO: fix me)', function () { }); it('rejects if different author id', function (done) { - var mockPostObj = { - get: sinon.stub() - }, - context = {user: 1}, - unsafeAttrs = {status: 'draft', author_id: 2}; + const mockPostObj = { + get: sinon.stub() + }; + const context = {user: 1}; + const unsafeAttrs = {status: 'draft', author_id: 2}; models.Post.permissible( mockPostObj, @@ -658,11 +658,11 @@ describe('Unit: models/post: uses database (@TODO: fix me)', function () { }); it('rejects if different logged in user and `authors.0`', function (done) { - var mockPostObj = { - get: sinon.stub() - }, - context = {user: 1}, - unsafeAttrs = {status: 'draft', authors: [{id: 2}]}; + const mockPostObj = { + get: sinon.stub() + }; + const context = {user: 1}; + const unsafeAttrs = {status: 'draft', authors: [{id: 2}]}; models.Post.permissible( mockPostObj, @@ -683,11 +683,11 @@ describe('Unit: models/post: uses database (@TODO: fix me)', function () { }); it('rejects if same logged in user and `authors.0`, but different author_id', function (done) { - var mockPostObj = { - get: sinon.stub() - }, - context = {user: 1}, - unsafeAttrs = {status: 'draft', author_id: 3, authors: [{id: 1}]}; + const mockPostObj = { + get: sinon.stub() + }; + const context = {user: 1}; + const unsafeAttrs = {status: 'draft', author_id: 3, authors: [{id: 1}]}; models.Post.permissible( mockPostObj, @@ -708,11 +708,11 @@ describe('Unit: models/post: uses database (@TODO: fix me)', function () { }); it('rejects if different logged in user and `authors.0`, but correct author_id', function (done) { - var mockPostObj = { - get: sinon.stub() - }, - context = {user: 1}, - unsafeAttrs = {status: 'draft', author_id: 1, authors: [{id: 2}]}; + const mockPostObj = { + get: sinon.stub() + }; + const context = {user: 1}; + const unsafeAttrs = {status: 'draft', author_id: 1, authors: [{id: 2}]}; models.Post.permissible( mockPostObj, @@ -733,11 +733,11 @@ describe('Unit: models/post: uses database (@TODO: fix me)', function () { }); it('resolves if same logged in user and `authors.0`', function (done) { - var mockPostObj = { - get: sinon.stub() - }, - context = {user: 1}, - unsafeAttrs = {status: 'draft', authors: [{id: 1}]}; + const mockPostObj = { + get: sinon.stub() + }; + const context = {user: 1}; + const unsafeAttrs = {status: 'draft', authors: [{id: 1}]}; models.Post.permissible( mockPostObj, @@ -757,11 +757,11 @@ describe('Unit: models/post: uses database (@TODO: fix me)', function () { }); it('resolves if none of the above cases are true', function () { - var mockPostObj = { - get: sinon.stub() - }, - context = {user: 1}, - unsafeAttrs = {status: 'draft', author_id: 1}; + const mockPostObj = { + get: sinon.stub() + }; + const context = {user: 1}; + const unsafeAttrs = {status: 'draft', author_id: 1}; return models.Post.permissible( mockPostObj, @@ -782,11 +782,11 @@ describe('Unit: models/post: uses database (@TODO: fix me)', function () { describe('Destroying', function () { it('rejects if destroying another author\'s post', function (done) { - var mockPostObj = { - get: sinon.stub(), - related: sinon.stub() - }, - context = {user: 1}; + const mockPostObj = { + get: sinon.stub(), + related: sinon.stub() + }; + const context = {user: 1}; mockPostObj.related.withArgs('authors').returns({models: [{id: 1}]}); @@ -810,11 +810,11 @@ describe('Unit: models/post: uses database (@TODO: fix me)', function () { }); it('rejects if destroying a published post', function (done) { - var mockPostObj = { - get: sinon.stub(), - related: sinon.stub() - }, - context = {user: 1}; + const mockPostObj = { + get: sinon.stub(), + related: sinon.stub() + }; + const context = {user: 1}; mockPostObj.related.withArgs('authors').returns({models: [{id: 1}]}); mockPostObj.get.withArgs('status').returns('published'); @@ -839,11 +839,11 @@ describe('Unit: models/post: uses database (@TODO: fix me)', function () { }); it('resolves if none of the above cases are true', function () { - var mockPostObj = { - get: sinon.stub(), - related: sinon.stub() - }, - context = {user: 1}; + const mockPostObj = { + get: sinon.stub(), + related: sinon.stub() + }; + const context = {user: 1}; mockPostObj.get.withArgs('status').returns('draft'); mockPostObj.related.withArgs('authors').returns({models: [{id: 1}]}); @@ -870,12 +870,12 @@ describe('Unit: models/post: uses database (@TODO: fix me)', function () { describe('As Author', function () { describe('Editing', function () { it('rejects if editing another\'s post', function (done) { - var mockPostObj = { - get: sinon.stub(), - related: sinon.stub() - }, - context = {user: 1}, - unsafeAttrs = {author_id: 2}; + const mockPostObj = { + get: sinon.stub(), + related: sinon.stub() + }; + const context = {user: 1}; + const unsafeAttrs = {author_id: 2}; mockPostObj.related.withArgs('authors').returns({models: [{id: 2}]}); mockPostObj.get.withArgs('author_id').returns(2); @@ -900,12 +900,12 @@ describe('Unit: models/post: uses database (@TODO: fix me)', function () { }); it('rejects if changing visibility', function (done) { - var mockPostObj = { - get: sinon.stub(), - related: sinon.stub() - }, - context = {user: 1}, - unsafeAttrs = {visibility: 'public'}; + const mockPostObj = { + get: sinon.stub(), + related: sinon.stub() + }; + const context = {user: 1}; + const unsafeAttrs = {visibility: 'public'}; mockPostObj.get.withArgs('visibility').returns('paid'); mockPostObj.related.withArgs('authors').returns({models: [{id: 1}]}); @@ -930,12 +930,12 @@ describe('Unit: models/post: uses database (@TODO: fix me)', function () { }); it('rejects if editing another\'s post (using `authors`)', function (done) { - var mockPostObj = { - get: sinon.stub(), - related: sinon.stub() - }, - context = {user: 1}, - unsafeAttrs = {authors: [{id: 2}]}; + const mockPostObj = { + get: sinon.stub(), + related: sinon.stub() + }; + const context = {user: 1}; + const unsafeAttrs = {authors: [{id: 2}]}; mockPostObj.related.withArgs('authors').returns({models: [{id: 1}]}); @@ -959,12 +959,12 @@ describe('Unit: models/post: uses database (@TODO: fix me)', function () { }); it('rejects if changing author', function (done) { - var mockPostObj = { - get: sinon.stub(), - related: sinon.stub() - }, - context = {user: 1}, - unsafeAttrs = {author_id: 2}; + const mockPostObj = { + get: sinon.stub(), + related: sinon.stub() + }; + const context = {user: 1}; + const unsafeAttrs = {author_id: 2}; mockPostObj.get.withArgs('author_id').returns(1); mockPostObj.related.withArgs('authors').returns({models: [{id: 1}]}); @@ -989,12 +989,12 @@ describe('Unit: models/post: uses database (@TODO: fix me)', function () { }); it('rejects if changing authors', function (done) { - var mockPostObj = { - get: sinon.stub(), - related: sinon.stub() - }, - context = {user: 1}, - unsafeAttrs = {authors: [{id: 2}]}; + const mockPostObj = { + get: sinon.stub(), + related: sinon.stub() + }; + const context = {user: 1}; + const unsafeAttrs = {authors: [{id: 2}]}; mockPostObj.related.withArgs('authors').returns({models: [{id: 1}]}); @@ -1018,12 +1018,12 @@ describe('Unit: models/post: uses database (@TODO: fix me)', function () { }); it('rejects if changing authors and author_id', function (done) { - var mockPostObj = { - get: sinon.stub(), - related: sinon.stub() - }, - context = {user: 1}, - unsafeAttrs = {authors: [{id: 1}], author_id: 2}; + const mockPostObj = { + get: sinon.stub(), + related: sinon.stub() + }; + const context = {user: 1}; + const unsafeAttrs = {authors: [{id: 1}], author_id: 2}; mockPostObj.get.withArgs('author_id').returns(1); mockPostObj.related.withArgs('authors').returns({models: [{id: 1}]}); @@ -1048,12 +1048,12 @@ describe('Unit: models/post: uses database (@TODO: fix me)', function () { }); it('rejects if changing authors and author_id', function (done) { - var mockPostObj = { - get: sinon.stub(), - related: sinon.stub() - }, - context = {user: 1}, - unsafeAttrs = {authors: [{id: 2}], author_id: 1}; + const mockPostObj = { + get: sinon.stub(), + related: sinon.stub() + }; + const context = {user: 1}; + const unsafeAttrs = {authors: [{id: 2}], author_id: 1}; mockPostObj.get.withArgs('author_id').returns(1); mockPostObj.related.withArgs('authors').returns({models: [{id: 1}]}); @@ -1078,12 +1078,12 @@ describe('Unit: models/post: uses database (@TODO: fix me)', function () { }); it('resolves if none of the above cases are true', function () { - var mockPostObj = { - get: sinon.stub(), - related: sinon.stub() - }, - context = {user: 1}, - unsafeAttrs = {author_id: 1}; + const mockPostObj = { + get: sinon.stub(), + related: sinon.stub() + }; + const context = {user: 1}; + const unsafeAttrs = {author_id: 1}; mockPostObj.get.withArgs('author_id').returns(1); mockPostObj.related.withArgs('authors').returns({models: [{id: 1}]}); @@ -1106,11 +1106,11 @@ describe('Unit: models/post: uses database (@TODO: fix me)', function () { describe('Adding', function () { it('rejects if different author id', function (done) { - var mockPostObj = { - get: sinon.stub() - }, - context = {user: 1}, - unsafeAttrs = {author_id: 2}; + const mockPostObj = { + get: sinon.stub() + }; + const context = {user: 1}; + const unsafeAttrs = {author_id: 2}; models.Post.permissible( mockPostObj, @@ -1131,12 +1131,12 @@ describe('Unit: models/post: uses database (@TODO: fix me)', function () { }); it('rejects if different authors', function (done) { - var mockPostObj = { - get: sinon.stub(), - related: sinon.stub() - }, - context = {user: 1}, - unsafeAttrs = {authors: [{id: 2}]}; + const mockPostObj = { + get: sinon.stub(), + related: sinon.stub() + }; + const context = {user: 1}; + const unsafeAttrs = {authors: [{id: 2}]}; mockPostObj.related.withArgs('authors').returns({models: [{id: 1}]}); @@ -1159,11 +1159,11 @@ describe('Unit: models/post: uses database (@TODO: fix me)', function () { }); it('resolves if none of the above cases are true', function () { - var mockPostObj = { - get: sinon.stub() - }, - context = {user: 1}, - unsafeAttrs = {author_id: 1}; + const mockPostObj = { + get: sinon.stub() + }; + const context = {user: 1}; + const unsafeAttrs = {author_id: 1}; return models.Post.permissible( mockPostObj, @@ -1183,12 +1183,12 @@ describe('Unit: models/post: uses database (@TODO: fix me)', function () { describe('Everyone Else', function () { it('rejects if hasUserPermissions is false and not current owner', function (done) { - var mockPostObj = { - get: sinon.stub(), - related: sinon.stub() - }, - context = {user: 1}, - unsafeAttrs = {author_id: 2}; + const mockPostObj = { + get: sinon.stub(), + related: sinon.stub() + }; + const context = {user: 1}; + const unsafeAttrs = {author_id: 2}; mockPostObj.related.withArgs('authors').returns({models: [{id: 2}]}); mockPostObj.get.withArgs('author_id').returns(2); @@ -1213,11 +1213,11 @@ describe('Unit: models/post: uses database (@TODO: fix me)', function () { }); it('resolves if hasUserPermission is true', function () { - var mockPostObj = { - get: sinon.stub() - }, - context = {user: 1}, - unsafeAttrs = {author_id: 2}; + const mockPostObj = { + get: sinon.stub() + }; + const context = {user: 1}; + const unsafeAttrs = {author_id: 2}; mockPostObj.get.withArgs('author_id').returns(2); @@ -1236,12 +1236,12 @@ describe('Unit: models/post: uses database (@TODO: fix me)', function () { }); it('resolves if changing visibility', function () { - var mockPostObj = { - get: sinon.stub(), - related: sinon.stub() - }, - context = {user: 1}, - unsafeAttrs = {visibility: 'public'}; + const mockPostObj = { + get: sinon.stub(), + related: sinon.stub() + }; + const context = {user: 1}; + const unsafeAttrs = {visibility: 'public'}; mockPostObj.get.withArgs('visibility').returns('paid'); mockPostObj.related.withArgs('authors').returns({models: [{id: 1}]}); diff --git a/test/unit/models/user_spec.js b/test/unit/models/user_spec.js index 445231d9d8..361912480c 100644 --- a/test/unit/models/user_spec.js +++ b/test/unit/models/user_spec.js @@ -1,15 +1,15 @@ -const should = require('should'), - url = require('url'), - sinon = require('sinon'), - Promise = require('bluebird'), - _ = require('lodash'), - schema = require('../../../core/server/data/schema'), - models = require('../../../core/server/models'), - permissions = require('../../../core/server/services/permissions'), - validation = require('../../../core/server/data/validation'), - common = require('../../../core/server/lib/common'), - security = require('../../../core/server/lib/security'), - testUtils = require('../../utils'); +const should = require('should'); +const url = require('url'); +const sinon = require('sinon'); +const Promise = require('bluebird'); +const _ = require('lodash'); +const schema = require('../../../core/server/data/schema'); +const models = require('../../../core/server/models'); +const permissions = require('../../../core/server/services/permissions'); +const validation = require('../../../core/server/data/validation'); +const common = require('../../../core/server/lib/common'); +const security = require('../../../core/server/lib/security'); +const testUtils = require('../../utils'); describe('Unit: models/user', function () { before(function () { @@ -139,7 +139,7 @@ describe('Unit: models/user', function () { describe('permissible', function () { function getUserModel(id, role, roleId) { - var hasRole = sinon.stub(); + const hasRole = sinon.stub(); hasRole.withArgs(role).returns(true); @@ -152,8 +152,8 @@ describe('Unit: models/user', function () { } it('cannot delete owner', function (done) { - var mockUser = getUserModel(1, 'Owner'), - context = {user: 1}; + const mockUser = getUserModel(1, 'Owner'); + const context = {user: 1}; models.User.permissible(mockUser, 'destroy', context, {}, testUtils.permissions.owner, true, true, true).then(() => { done(new Error('Permissible function should have errored')); @@ -165,8 +165,8 @@ describe('Unit: models/user', function () { }); it('can always edit self', function () { - var mockUser = getUserModel(3, 'Contributor'), - context = {user: 3}; + const mockUser = getUserModel(3, 'Contributor'); + const context = {user: 3}; return models.User.permissible(mockUser, 'edit', context, {}, testUtils.permissions.contributor, false, true, true).then(() => { should(mockUser.get.calledOnce).be.true(); @@ -174,8 +174,8 @@ describe('Unit: models/user', function () { }); it('cannot edit my status to inactive', function () { - var mockUser = getUserModel(3, 'Editor'), - context = {user: 3}; + const mockUser = getUserModel(3, 'Editor'); + const context = {user: 3}; return models.User.permissible(mockUser, 'edit', context, {status: 'inactive'}, testUtils.permissions.editor, false, true, true) .then(Promise.reject) @@ -201,7 +201,7 @@ describe('Unit: models/user', function () { describe('change role', function () { function getUserToEdit(id, role) { - var hasRole = sinon.stub(); + const hasRole = sinon.stub(); hasRole.withArgs(role).returns(true); @@ -303,8 +303,8 @@ describe('Unit: models/user', function () { describe('as editor', function () { it('can\'t edit another editor', function (done) { - var mockUser = getUserModel(3, 'Editor'), - context = {user: 2}; + const mockUser = getUserModel(3, 'Editor'); + const context = {user: 2}; models.User.permissible(mockUser, 'edit', context, {}, testUtils.permissions.editor, true, true, true).then(() => { done(new Error('Permissible function should have errored')); @@ -317,8 +317,8 @@ describe('Unit: models/user', function () { }); it('can\'t edit owner', function (done) { - var mockUser = getUserModel(3, 'Owner'), - context = {user: 2}; + const mockUser = getUserModel(3, 'Owner'); + const context = {user: 2}; models.User.permissible(mockUser, 'edit', context, {}, testUtils.permissions.editor, true, true, true).then(() => { done(new Error('Permissible function should have errored')); @@ -331,8 +331,8 @@ describe('Unit: models/user', function () { }); it('can\'t edit an admin', function (done) { - var mockUser = getUserModel(3, 'Administrator'), - context = {user: 2}; + const mockUser = getUserModel(3, 'Administrator'); + const context = {user: 2}; models.User.permissible(mockUser, 'edit', context, {}, testUtils.permissions.editor, true, true, true).then(() => { done(new Error('Permissible function should have errored')); @@ -345,8 +345,8 @@ describe('Unit: models/user', function () { }); it('can edit author', function () { - var mockUser = getUserModel(3, 'Author'), - context = {user: 2}; + const mockUser = getUserModel(3, 'Author'); + const context = {user: 2}; return models.User.permissible(mockUser, 'edit', context, {}, testUtils.permissions.editor, true, true, true).then(() => { should(mockUser.hasRole.called).be.true(); @@ -355,8 +355,8 @@ describe('Unit: models/user', function () { }); it('can edit contributor', function () { - var mockUser = getUserModel(3, 'Contributor'), - context = {user: 2}; + const mockUser = getUserModel(3, 'Contributor'); + const context = {user: 2}; return models.User.permissible(mockUser, 'edit', context, {}, testUtils.permissions.editor, true, true, true).then(() => { should(mockUser.hasRole.called).be.true(); @@ -365,8 +365,8 @@ describe('Unit: models/user', function () { }); it('can destroy self', function () { - var mockUser = getUserModel(3, 'Editor'), - context = {user: 3}; + const mockUser = getUserModel(3, 'Editor'); + const context = {user: 3}; return models.User.permissible(mockUser, 'destroy', context, {}, testUtils.permissions.editor, true, true, true).then(() => { should(mockUser.hasRole.called).be.true(); @@ -375,8 +375,8 @@ describe('Unit: models/user', function () { }); it('can\'t destroy another editor', function (done) { - var mockUser = getUserModel(3, 'Editor'), - context = {user: 2}; + const mockUser = getUserModel(3, 'Editor'); + const context = {user: 2}; models.User.permissible(mockUser, 'destroy', context, {}, testUtils.permissions.editor, true, true, true).then(() => { done(new Error('Permissible function should have errored')); @@ -389,8 +389,8 @@ describe('Unit: models/user', function () { }); it('can\'t destroy an admin', function (done) { - var mockUser = getUserModel(3, 'Administrator'), - context = {user: 2}; + const mockUser = getUserModel(3, 'Administrator'); + const context = {user: 2}; models.User.permissible(mockUser, 'destroy', context, {}, testUtils.permissions.editor, true, true, true).then(() => { done(new Error('Permissible function should have errored')); @@ -403,8 +403,8 @@ describe('Unit: models/user', function () { }); it('can destroy an author', function () { - var mockUser = getUserModel(3, 'Author'), - context = {user: 2}; + const mockUser = getUserModel(3, 'Author'); + const context = {user: 2}; return models.User.permissible(mockUser, 'destroy', context, {}, testUtils.permissions.editor, true, true, true).then(() => { should(mockUser.hasRole.called).be.true(); @@ -413,8 +413,8 @@ describe('Unit: models/user', function () { }); it('can destroy a contributor', function () { - var mockUser = getUserModel(3, 'Contributor'), - context = {user: 2}; + const mockUser = getUserModel(3, 'Contributor'); + const context = {user: 2}; return models.User.permissible(mockUser, 'destroy', context, {}, testUtils.permissions.editor, true, true, true).then(() => { should(mockUser.hasRole.called).be.true(); diff --git a/test/unit/services/apps/proxy_spec.js b/test/unit/services/apps/proxy_spec.js index ff95c3aaac..c4aed1f891 100644 --- a/test/unit/services/apps/proxy_spec.js +++ b/test/unit/services/apps/proxy_spec.js @@ -1,8 +1,8 @@ -const should = require('should'), - sinon = require('sinon'), - helpers = require('../../../../core/frontend/services/themes/handlebars/register'), - AppProxy = require('../../../../core/frontend/services/apps/proxy'), - routing = require('../../../../core/frontend/services/routing'); +const should = require('should'); +const sinon = require('sinon'); +const helpers = require('../../../../core/frontend/services/themes/handlebars/register'); +const AppProxy = require('../../../../core/frontend/services/apps/proxy'); +const routing = require('../../../../core/frontend/services/routing'); describe('Apps', function () { beforeEach(function () { @@ -17,7 +17,7 @@ describe('Apps', function () { describe('Proxy', function () { it('creates a ghost proxy', function () { - var appProxy = AppProxy.getInstance('TestApp'); + const appProxy = AppProxy.getInstance('TestApp'); should.exist(appProxy.helpers); should.exist(appProxy.helpers.register); @@ -25,8 +25,8 @@ describe('Apps', function () { }); it('allows helper registration', function () { - var registerSpy = sinon.stub(helpers, 'registerThemeHelper'), - appProxy = AppProxy.getInstance('TestApp'); + const registerSpy = sinon.stub(helpers, 'registerThemeHelper'); + const appProxy = AppProxy.getInstance('TestApp'); appProxy.helpers.register('myTestHelper', sinon.stub().returns('test result')); diff --git a/test/unit/services/mail/GhostMailer_spec.js b/test/unit/services/mail/GhostMailer_spec.js index 721a42328c..64061e84af 100644 --- a/test/unit/services/mail/GhostMailer_spec.js +++ b/test/unit/services/mail/GhostMailer_spec.js @@ -1,40 +1,42 @@ -var should = require('should'), - sinon = require('sinon'), - Promise = require('bluebird'), - mail = require('../../../../core/server/services/mail'), - settingsCache = require('../../../../core/server/services/settings/cache'), - configUtils = require('../../../utils/configUtils'), - urlUtils = require('../../../../core/server/lib/url-utils'), - common = require('../../../../core/server/lib/common'), - mailer, +const should = require('should'); +const sinon = require('sinon'); +const Promise = require('bluebird'); +const mail = require('../../../../core/server/services/mail'); +const settingsCache = require('../../../../core/server/services/settings/cache'); +const configUtils = require('../../../utils/configUtils'); +const urlUtils = require('../../../../core/server/lib/url-utils'); +const common = require('../../../../core/server/lib/common'); +let mailer; - // Mock SMTP config - SMTP = { - transport: 'SMTP', - options: { - service: 'Gmail', - auth: { - user: 'nil', - pass: '123' - } +// Mock SMTP config +const SMTP = { + transport: 'SMTP', + options: { + service: 'Gmail', + auth: { + user: 'nil', + pass: '123' } - }, + } +}; - // test data - mailDataNoDomain = { - to: 'joe@doesntexistexample091283zalgo.com', - subject: 'testemail', - html: '

      This

      ' - }, - mailDataNoServer = { - to: 'joe@example.com', - subject: 'testemail', - html: '

      This

      ' - }, - mailDataIncomplete = { - subject: 'testemail', - html: '

      This

      ' - }; +// test data +const mailDataNoDomain = { + to: 'joe@doesntexistexample091283zalgo.com', + subject: 'testemail', + html: '

      This

      ' +}; + +const mailDataNoServer = { + to: 'joe@example.com', + subject: 'testemail', + html: '

      This

      ' +}; + +const mailDataIncomplete = { + subject: 'testemail', + html: '

      This

      ' +}; const sandbox = sinon.createSandbox(); diff --git a/test/unit/services/mail/utils_spec.js b/test/unit/services/mail/utils_spec.js index 3a35ee13e8..f50e5538c6 100644 --- a/test/unit/services/mail/utils_spec.js +++ b/test/unit/services/mail/utils_spec.js @@ -1,9 +1,9 @@ -var should = require('should'), - sinon = require('sinon'), - mail = require('../../../../core/server/services/mail'); +const should = require('should'); +const sinon = require('sinon'); +const mail = require('../../../../core/server/services/mail'); describe('Mail: Utils', function () { - var scope = {ghostMailer: null}; + const scope = {ghostMailer: null}; beforeEach(function () { scope.ghostMailer = new mail.GhostMailer(); diff --git a/test/unit/services/permissions/can-this_spec.js b/test/unit/services/permissions/can-this_spec.js index 77dddc84ce..07c922d60f 100644 --- a/test/unit/services/permissions/can-this_spec.js +++ b/test/unit/services/permissions/can-this_spec.js @@ -1,16 +1,16 @@ -const should = require('should'), - sinon = require('sinon'), - testUtils = require('../../../utils'), - Promise = require('bluebird'), - _ = require('lodash'), - models = require('../../../../core/server/models'), - permissions = require('../../../../core/server/services/permissions'), - providers = require('../../../../core/server/services/permissions/providers'); +const should = require('should'); +const sinon = require('sinon'); +const testUtils = require('../../../utils'); +const Promise = require('bluebird'); +const _ = require('lodash'); +const models = require('../../../../core/server/models'); +const permissions = require('../../../../core/server/services/permissions'); +const providers = require('../../../../core/server/services/permissions/providers'); describe('Permissions', function () { - var fakePermissions = [], - findPostSpy, - findTagSpy; + let fakePermissions = []; + let findPostSpy; + let findTagSpy; before(function () { models.init(); @@ -23,8 +23,9 @@ describe('Permissions', function () { findPostSpy = sinon.stub(models.Post, 'findOne').callsFake(function () { // @TODO: the test env has no concept of including relations - let post = models.Post.forge(testUtils.DataGenerator.Content.posts[0]), - authors = [testUtils.DataGenerator.Content.users[0]]; + let post = models.Post.forge(testUtils.DataGenerator.Content.posts[0]); + + let authors = [testUtils.DataGenerator.Content.users[0]]; post.related('authors').set(authors); return Promise.resolve(post); @@ -54,12 +55,12 @@ describe('Permissions', function () { function loadFakePermissions(options) { options = options || {}; - var fixturePermissions = _.cloneDeep(testUtils.DataGenerator.Content.permissions), - extraPerm = { - name: 'test', - action_type: 'edit', - object_type: 'post' - }; + const fixturePermissions = _.cloneDeep(testUtils.DataGenerator.Content.permissions); + const extraPerm = { + name: 'test', + action_type: 'edit', + object_type: 'post' + }; if (options.extra) { fixturePermissions.push(extraPerm); @@ -78,7 +79,7 @@ describe('Permissions', function () { }); it('canThisResult gets build properly', function () { - var canThisResult = permissions.canThis(); + const canThisResult = permissions.canThis(); canThisResult.browse.should.be.an.Object(); canThisResult.browse.post.should.be.a.Function(); @@ -244,7 +245,7 @@ describe('Permissions', function () { // It can depend on bookshelf, but should NOT use hard coded model knowledge. // We use the tag model here because it doesn't have permissible, once that changes, these tests must also change it('No permissions: cannot edit tag (no permissible function on model)', function (done) { - var userProviderStub = sinon.stub(providers, 'user').callsFake(function () { + const userProviderStub = sinon.stub(providers, 'user').callsFake(function () { // Fake the response from providers.user, which contains permissions and roles return Promise.resolve({ permissions: [], @@ -267,7 +268,7 @@ describe('Permissions', function () { }); it('With permissions: can edit specific tag (no permissible function on model)', function (done) { - var userProviderStub = sinon.stub(providers, 'user').callsFake(function () { + const userProviderStub = sinon.stub(providers, 'user').callsFake(function () { // Fake the response from providers.user, which contains permissions and roles return Promise.resolve({ permissions: models.Permissions.forge(testUtils.DataGenerator.Content.permissions).models, @@ -288,7 +289,7 @@ describe('Permissions', function () { }); it('With permissions: can edit non-specific tag (no permissible function on model)', function (done) { - var userProviderStub = sinon.stub(providers, 'user').callsFake(function () { + const userProviderStub = sinon.stub(providers, 'user').callsFake(function () { // Fake the response from providers.user, which contains permissions and roles return Promise.resolve({ permissions: models.Permissions.forge(testUtils.DataGenerator.Content.permissions).models, @@ -309,7 +310,7 @@ describe('Permissions', function () { }); it('Specific permissions: can edit correct specific tag (no permissible function on model)', function (done) { - var userProviderStub = sinon.stub(providers, 'user').callsFake(function () { + const userProviderStub = sinon.stub(providers, 'user').callsFake(function () { // Fake the response from providers.user, which contains permissions and roles return Promise.resolve({ permissions: models.Permissions.forge([ @@ -338,7 +339,7 @@ describe('Permissions', function () { }); it('Specific permissions: cannot edit incorrect specific tag (no permissible function on model)', function (done) { - var userProviderStub = sinon.stub(providers, 'user').callsFake(function () { + const userProviderStub = sinon.stub(providers, 'user').callsFake(function () { // Fake the response from providers.user, which contains permissions and roles return Promise.resolve({ permissions: models.Permissions.forge([ @@ -370,7 +371,7 @@ describe('Permissions', function () { // @TODO fix this case - it makes no sense?! it('Specific permissions: CAN edit non-specific tag (no permissible function on model) @TODO fix this', function (done) { - var userProviderStub = sinon.stub(providers, 'user').callsFake(function () { + const userProviderStub = sinon.stub(providers, 'user').callsFake(function () { // Fake the response from providers.user, which contains permissions and roles return Promise.resolve({ permissions: models.Permissions.forge([ @@ -399,7 +400,7 @@ describe('Permissions', function () { }); it('With owner role: can edit tag (no permissible function on model)', function (done) { - var userProviderStub = sinon.stub(providers, 'user').callsFake(function () { + const userProviderStub = sinon.stub(providers, 'user').callsFake(function () { // Fake the response from providers.user, which contains permissions and roles return Promise.resolve({ permissions: [], @@ -452,16 +453,17 @@ describe('Permissions', function () { describe('permissible (overridden)', function () { it('can use permissible function on model to forbid something (post model)', function (done) { - var userProviderStub = sinon.stub(providers, 'user').callsFake(function () { - // Fake the response from providers.user, which contains permissions and roles - return Promise.resolve({ - permissions: models.Permissions.forge(testUtils.DataGenerator.Content.permissions).models, - roles: undefined - }); - }), - permissibleStub = sinon.stub(models.Post, 'permissible').callsFake(function () { - return Promise.reject({message: 'Hello World!'}); + const userProviderStub = sinon.stub(providers, 'user').callsFake(function () { + // Fake the response from providers.user, which contains permissions and roles + return Promise.resolve({ + permissions: models.Permissions.forge(testUtils.DataGenerator.Content.permissions).models, + roles: undefined }); + }); + + const permissibleStub = sinon.stub(models.Post, 'permissible').callsFake(function () { + return Promise.reject({message: 'Hello World!'}); + }); permissions .canThis({user: {}}) // user context @@ -489,16 +491,17 @@ describe('Permissions', function () { }); it('can use permissible function on model to allow something (post model)', function (done) { - var userProviderStub = sinon.stub(providers, 'user').callsFake(function () { - // Fake the response from providers.user, which contains permissions and roles - return Promise.resolve({ - permissions: models.Permissions.forge(testUtils.DataGenerator.Content.permissions).models, - roles: undefined - }); - }), - permissibleStub = sinon.stub(models.Post, 'permissible').callsFake(function () { - return Promise.resolve(); + const userProviderStub = sinon.stub(providers, 'user').callsFake(function () { + // Fake the response from providers.user, which contains permissions and roles + return Promise.resolve({ + permissions: models.Permissions.forge(testUtils.DataGenerator.Content.permissions).models, + roles: undefined }); + }); + + const permissibleStub = sinon.stub(models.Post, 'permissible').callsFake(function () { + return Promise.resolve(); + }); permissions .canThis({user: {}}) // user context diff --git a/test/unit/services/permissions/index_spec.js b/test/unit/services/permissions/index_spec.js index d0595ce611..0c003565b9 100644 --- a/test/unit/services/permissions/index_spec.js +++ b/test/unit/services/permissions/index_spec.js @@ -1,16 +1,16 @@ -var should = require('should'), - sinon = require('sinon'), - testUtils = require('../../../utils'), - Promise = require('bluebird'), - _ = require('lodash'), - models = require('../../../../core/server/models'), - actionsMap = require('../../../../core/server/services/permissions/actions-map-cache'), - permissions = require('../../../../core/server/services/permissions'); +const should = require('should'); +const sinon = require('sinon'); +const testUtils = require('../../../utils'); +const Promise = require('bluebird'); +const _ = require('lodash'); +const models = require('../../../../core/server/models'); +const actionsMap = require('../../../../core/server/services/permissions/actions-map-cache'); +const permissions = require('../../../../core/server/services/permissions'); describe('Permissions', function () { - var fakePermissions = [], - findPostSpy, - findTagSpy; + let fakePermissions = []; + let findPostSpy; + let findTagSpy; before(function () { models.init(); @@ -49,12 +49,13 @@ describe('Permissions', function () { function loadFakePermissions(options) { options = options || {}; - var fixturePermissions = _.cloneDeep(testUtils.DataGenerator.Content.permissions), - extraPerm = { - name: 'test', - action_type: 'edit', - object_type: 'post' - }; + const fixturePermissions = _.cloneDeep(testUtils.DataGenerator.Content.permissions); + + const extraPerm = { + name: 'test', + action_type: 'edit', + object_type: 'post' + }; if (options.extra) { fixturePermissions.push(extraPerm); diff --git a/test/unit/services/permissions/parse-context_spec.js b/test/unit/services/permissions/parse-context_spec.js index d8f339f0ce..d4976a192b 100644 --- a/test/unit/services/permissions/parse-context_spec.js +++ b/test/unit/services/permissions/parse-context_spec.js @@ -1,5 +1,5 @@ -var should = require('should'), - parseContext = require('../../../../core/server/services/permissions/parse-context'); +const should = require('should'); +const parseContext = require('../../../../core/server/services/permissions/parse-context'); describe('Permissions', function () { describe('parseContext', function () { diff --git a/test/unit/services/permissions/providers_spec.js b/test/unit/services/permissions/providers_spec.js index 840db53704..1d2dd4c79a 100644 --- a/test/unit/services/permissions/providers_spec.js +++ b/test/unit/services/permissions/providers_spec.js @@ -1,9 +1,9 @@ -var should = require('should'), - sinon = require('sinon'), - testUtils = require('../../../utils'), - Promise = require('bluebird'), - models = require('../../../../core/server/models'), - providers = require('../../../../core/server/services/permissions/providers'); +const should = require('should'); +const sinon = require('sinon'); +const testUtils = require('../../../utils'); +const Promise = require('bluebird'); +const models = require('../../../../core/server/models'); +const providers = require('../../../../core/server/services/permissions/providers'); describe('Permission Providers', function () { before(function () { @@ -16,7 +16,7 @@ describe('Permission Providers', function () { describe('User', function () { it('errors if user cannot be found', function (done) { - var findUserSpy = sinon.stub(models.User, 'findOne').callsFake(function () { + const findUserSpy = sinon.stub(models.User, 'findOne').callsFake(function () { return Promise.resolve(); }); @@ -33,12 +33,14 @@ describe('Permission Providers', function () { it('can load user with role, and permissions', function (done) { // This test requires quite a lot of unique setup work - var findUserSpy = sinon.stub(models.User, 'findOne').callsFake(function () { + const findUserSpy = sinon.stub(models.User, 'findOne').callsFake(function () { // Create a fake model - var fakeUser = models.User.forge(testUtils.DataGenerator.Content.users[0]), - // Roles & Permissions need to be collections - fakeAdminRole = models.Roles.forge(testUtils.DataGenerator.Content.roles[0]), - fakeAdminRolePermissions = models.Permissions.forge(testUtils.DataGenerator.Content.permissions); + const fakeUser = models.User.forge(testUtils.DataGenerator.Content.users[0]); + + // Roles & Permissions need to be collections + const fakeAdminRole = models.Roles.forge(testUtils.DataGenerator.Content.roles[0]); + + const fakeAdminRolePermissions = models.Permissions.forge(testUtils.DataGenerator.Content.permissions); // ## Fake the relations // User is related to roles & permissions @@ -78,12 +80,14 @@ describe('Permission Providers', function () { it('can load user with role, and role.permissions', function (done) { // This test requires quite a lot of unique setup work - var findUserSpy = sinon.stub(models.User, 'findOne').callsFake(function () { + const findUserSpy = sinon.stub(models.User, 'findOne').callsFake(function () { // Create a fake model - var fakeUser = models.User.forge(testUtils.DataGenerator.Content.users[0]), - // Roles & Permissions need to be collections - fakeAdminRole = models.Roles.forge(testUtils.DataGenerator.Content.roles[0]), - fakeAdminRolePermissions = models.Permissions.forge(testUtils.DataGenerator.Content.permissions); + const fakeUser = models.User.forge(testUtils.DataGenerator.Content.users[0]); + + // Roles & Permissions need to be collections + const fakeAdminRole = models.Roles.forge(testUtils.DataGenerator.Content.roles[0]); + + const fakeAdminRolePermissions = models.Permissions.forge(testUtils.DataGenerator.Content.permissions); // ## Fake the relations // Roles are related to permissions @@ -125,12 +129,14 @@ describe('Permission Providers', function () { it('can load user with role, permissions and role.permissions and deduplicate them', function (done) { // This test requires quite a lot of unique setup work - var findUserSpy = sinon.stub(models.User, 'findOne').callsFake(function () { + const findUserSpy = sinon.stub(models.User, 'findOne').callsFake(function () { // Create a fake model - var fakeUser = models.User.forge(testUtils.DataGenerator.Content.users[0]), - // Roles & Permissions need to be collections - fakeAdminRole = models.Roles.forge(testUtils.DataGenerator.Content.roles[0]), - fakeAdminRolePermissions = models.Permissions.forge(testUtils.DataGenerator.Content.permissions); + const fakeUser = models.User.forge(testUtils.DataGenerator.Content.users[0]); + + // Roles & Permissions need to be collections + const fakeAdminRole = models.Roles.forge(testUtils.DataGenerator.Content.roles[0]); + + const fakeAdminRolePermissions = models.Permissions.forge(testUtils.DataGenerator.Content.permissions); // ## Fake the relations // Roles are related to permissions diff --git a/test/unit/services/permissions/public_spec.js b/test/unit/services/permissions/public_spec.js index c2ed6cac54..bd70a39b4b 100644 --- a/test/unit/services/permissions/public_spec.js +++ b/test/unit/services/permissions/public_spec.js @@ -1,7 +1,7 @@ -var should = require('should'), - _ = require('lodash'), - common = require('../../../../core/server/lib/common'), - applyPublicRules = require('../../../../core/server/services/permissions/public'); +const should = require('should'); +const _ = require('lodash'); +const common = require('../../../../core/server/lib/common'); +const applyPublicRules = require('../../../../core/server/services/permissions/public'); describe('Permissions', function () { describe('applyPublicRules', function () { @@ -28,7 +28,7 @@ describe('Permissions', function () { }); it('should return unchanged object for post with public context', function (done) { - var publicContext = {context: {}}; + const publicContext = {context: {}}; applyPublicRules('posts', 'browse', _.cloneDeep(publicContext)).then(function (result) { result.should.not.eql(publicContext); @@ -49,7 +49,7 @@ describe('Permissions', function () { }); it('should throw an error for draft post without uuid (read)', function (done) { - var draft = {context: {}, data: {status: 'draft'}}; + const draft = {context: {}, data: {status: 'draft'}}; applyPublicRules('posts', 'read', _.cloneDeep(draft)).then(function () { done('Did not throw an error for draft'); @@ -60,7 +60,7 @@ describe('Permissions', function () { }); it('should throw an error for draft post (browse)', function (done) { - var draft = {context: {}, status: 'draft'}; + const draft = {context: {}, status: 'draft'}; applyPublicRules('posts', 'browse', _.cloneDeep(draft)).then(function () { done('Did not throw an error for draft'); @@ -71,7 +71,7 @@ describe('Permissions', function () { }); it('should permit post draft status with uuid (read)', function (done) { - var draft = {context: {}, data: {status: 'draft', uuid: '1234-abcd'}}; + const draft = {context: {}, data: {status: 'draft', uuid: '1234-abcd'}}; applyPublicRules('posts', 'read', _.cloneDeep(draft)).then(function (result) { result.should.eql(draft); @@ -80,7 +80,7 @@ describe('Permissions', function () { }); it('should permit post all status with uuid (read)', function (done) { - var draft = {context: {}, data: {status: 'all', uuid: '1234-abcd'}}; + const draft = {context: {}, data: {status: 'all', uuid: '1234-abcd'}}; applyPublicRules('posts', 'read', _.cloneDeep(draft)).then(function (result) { result.should.eql(draft); @@ -89,7 +89,7 @@ describe('Permissions', function () { }); it('should NOT permit post draft status with uuid (browse)', function (done) { - var draft = {context: {}, status: 'draft', uuid: '1234-abcd'}; + const draft = {context: {}, status: 'draft', uuid: '1234-abcd'}; applyPublicRules('posts', 'browse', _.cloneDeep(draft)).then(function () { done('Did not throw an error for draft'); @@ -100,7 +100,7 @@ describe('Permissions', function () { }); it('should NOT permit post all status with uuid (browse)', function (done) { - var draft = {context: {}, status: 'all', uuid: '1234-abcd'}; + const draft = {context: {}, status: 'all', uuid: '1234-abcd'}; applyPublicRules('posts', 'browse', _.cloneDeep(draft)).then(function () { done('Did not throw an error for draft'); @@ -111,7 +111,7 @@ describe('Permissions', function () { }); it('should throw an error for draft post with uuid and id or slug (read)', function (done) { - var draft = {context: {}, data: {status: 'draft', uuid: '1234-abcd', id: 1}}; + let draft = {context: {}, data: {status: 'draft', uuid: '1234-abcd', id: 1}}; applyPublicRules('posts', 'read', _.cloneDeep(draft)).then(function () { done('Did not throw an error for draft'); @@ -130,7 +130,7 @@ describe('Permissions', function () { }); it('should return unchanged object for user with public context', function (done) { - var publicContext = {context: {}}; + const publicContext = {context: {}}; applyPublicRules('users', 'browse', _.cloneDeep(publicContext)).then(function (result) { result.should.not.eql(publicContext); diff --git a/test/unit/services/routing/CollectionRouter_spec.js b/test/unit/services/routing/CollectionRouter_spec.js index a87e1cf06e..702e659794 100644 --- a/test/unit/services/routing/CollectionRouter_spec.js +++ b/test/unit/services/routing/CollectionRouter_spec.js @@ -1,14 +1,16 @@ -const should = require('should'), - sinon = require('sinon'), - express = require('express'), - settingsCache = require('../../../../core/server/services/settings/cache'), - common = require('../../../../core/server/lib/common'), - controllers = require('../../../../core/frontend/services/routing/controllers'), - CollectionRouter = require('../../../../core/frontend/services/routing/CollectionRouter'), - RESOURCE_CONFIG = {QUERY: {post: {controller: 'posts', resource: 'posts'}}}; +const should = require('should'); +const sinon = require('sinon'); +const express = require('express'); +const settingsCache = require('../../../../core/server/services/settings/cache'); +const common = require('../../../../core/server/lib/common'); +const controllers = require('../../../../core/frontend/services/routing/controllers'); +const CollectionRouter = require('../../../../core/frontend/services/routing/CollectionRouter'); +const RESOURCE_CONFIG = {QUERY: {post: {controller: 'posts', resource: 'posts'}}}; describe('UNIT - services/routing/CollectionRouter', function () { - let req, res, next; + let req; + let res; + let next; beforeEach(function () { sinon.stub(common.events, 'emit'); diff --git a/test/unit/services/routing/ParentRouter_spec.js b/test/unit/services/routing/ParentRouter_spec.js index b0a2274605..46ed535dd9 100644 --- a/test/unit/services/routing/ParentRouter_spec.js +++ b/test/unit/services/routing/ParentRouter_spec.js @@ -1,12 +1,14 @@ -const should = require('should'), - sinon = require('sinon'), - configUtils = require('../../../utils/configUtils'), - common = require('../../../../core/server/lib/common'), - urlUtils = require('../../../../core/server/lib/url-utils'), - ParentRouter = require('../../../../core/frontend/services/routing/ParentRouter'); +const should = require('should'); +const sinon = require('sinon'); +const configUtils = require('../../../utils/configUtils'); +const common = require('../../../../core/server/lib/common'); +const urlUtils = require('../../../../core/server/lib/url-utils'); +const ParentRouter = require('../../../../core/frontend/services/routing/ParentRouter'); describe('UNIT - services/routing/ParentRouter', function () { - let req, res, next; + let req; + let res; + let next; beforeEach(function () { sinon.stub(common.events, 'emit'); diff --git a/test/unit/services/routing/RSSRouter_spec.js b/test/unit/services/routing/RSSRouter_spec.js index c588940f40..5c9cf2997f 100644 --- a/test/unit/services/routing/RSSRouter_spec.js +++ b/test/unit/services/routing/RSSRouter_spec.js @@ -1,10 +1,10 @@ -const should = require('should'), - sinon = require('sinon'), - configUtils = require('../../../utils/configUtils'), - common = require('../../../../core/server/lib/common'), - controllers = require('../../../../core/frontend/services/routing/controllers'), - RSSRouter = require('../../../../core/frontend/services/routing/RSSRouter'), - urlUtils = require('../../../../core/server/lib/url-utils'); +const should = require('should'); +const sinon = require('sinon'); +const configUtils = require('../../../utils/configUtils'); +const common = require('../../../../core/server/lib/common'); +const controllers = require('../../../../core/frontend/services/routing/controllers'); +const RSSRouter = require('../../../../core/frontend/services/routing/RSSRouter'); +const urlUtils = require('../../../../core/server/lib/url-utils'); describe('UNIT - services/routing/RSSRouter', function () { describe('instantiate', function () { diff --git a/test/unit/services/routing/StaticRoutesRouter_spec.js b/test/unit/services/routing/StaticRoutesRouter_spec.js index 3ec03f068e..3481b75d93 100644 --- a/test/unit/services/routing/StaticRoutesRouter_spec.js +++ b/test/unit/services/routing/StaticRoutesRouter_spec.js @@ -1,12 +1,14 @@ -const should = require('should'), - sinon = require('sinon'), - common = require('../../../../core/server/lib/common'), - controllers = require('../../../../core/frontend/services/routing/controllers'), - StaticRoutesRouter = require('../../../../core/frontend/services/routing/StaticRoutesRouter'), - configUtils = require('../../../utils/configUtils'); +const should = require('should'); +const sinon = require('sinon'); +const common = require('../../../../core/server/lib/common'); +const controllers = require('../../../../core/frontend/services/routing/controllers'); +const StaticRoutesRouter = require('../../../../core/frontend/services/routing/StaticRoutesRouter'); +const configUtils = require('../../../utils/configUtils'); describe('UNIT - services/routing/StaticRoutesRouter', function () { - let req, res, next; + let req; + let res; + let next; afterEach(function () { configUtils.restore(); diff --git a/test/unit/services/routing/TaxonomyRouter_spec.js b/test/unit/services/routing/TaxonomyRouter_spec.js index 5c0a8267fe..fb67790b43 100644 --- a/test/unit/services/routing/TaxonomyRouter_spec.js +++ b/test/unit/services/routing/TaxonomyRouter_spec.js @@ -1,16 +1,18 @@ -const should = require('should'), - sinon = require('sinon'), - _ = require('lodash'), - settingsCache = require('../../../../core/server/services/settings/cache'), - common = require('../../../../core/server/lib/common'), - controllers = require('../../../../core/frontend/services/routing/controllers'), - TaxonomyRouter = require('../../../../core/frontend/services/routing/TaxonomyRouter'), - RESOURCE_CONFIG_V2 = require('../../../../core/frontend/services/routing/config/v2'), - RESOURCE_CONFIG_CANARY = require('../../../../core/frontend/services/routing/config/canary'), - RESOURCE_CONFIG_V3 = require('../../../../core/frontend/services/routing/config/v3'); +const should = require('should'); +const sinon = require('sinon'); +const _ = require('lodash'); +const settingsCache = require('../../../../core/server/services/settings/cache'); +const common = require('../../../../core/server/lib/common'); +const controllers = require('../../../../core/frontend/services/routing/controllers'); +const TaxonomyRouter = require('../../../../core/frontend/services/routing/TaxonomyRouter'); +const RESOURCE_CONFIG_V2 = require('../../../../core/frontend/services/routing/config/v2'); +const RESOURCE_CONFIG_CANARY = require('../../../../core/frontend/services/routing/config/canary'); +const RESOURCE_CONFIG_V3 = require('../../../../core/frontend/services/routing/config/v3'); describe('UNIT - services/routing/TaxonomyRouter', function () { - let req, res, next; + let req; + let res; + let next; beforeEach(function () { sinon.stub(settingsCache, 'get').withArgs('permalinks').returns('/:slug/'); diff --git a/test/unit/services/routing/controllers/channel_spec.js b/test/unit/services/routing/controllers/channel_spec.js index fcf17e17ad..b8683c017e 100644 --- a/test/unit/services/routing/controllers/channel_spec.js +++ b/test/unit/services/routing/controllers/channel_spec.js @@ -1,11 +1,11 @@ -const should = require('should'), - sinon = require('sinon'), - testUtils = require('../../../../utils'), - common = require('../../../../../core/server/lib/common'), - security = require('../../../../../core/server/lib/security'), - themeService = require('../../../../../core/frontend/services/themes'), - controllers = require('../../../../../core/frontend/services/routing/controllers'), - helpers = require('../../../../../core/frontend/services/routing/helpers'); +const should = require('should'); +const sinon = require('sinon'); +const testUtils = require('../../../../utils'); +const common = require('../../../../../core/server/lib/common'); +const security = require('../../../../../core/server/lib/security'); +const themeService = require('../../../../../core/frontend/services/themes'); +const controllers = require('../../../../../core/frontend/services/routing/controllers'); +const helpers = require('../../../../../core/frontend/services/routing/helpers'); function failTest(done) { return function (err) { @@ -15,7 +15,13 @@ function failTest(done) { } describe('Unit - services/routing/controllers/channel', function () { - let req, res, fetchDataStub, secureStub, renderStub, posts, postsPerPage; + let req; + let res; + let fetchDataStub; + let secureStub; + let renderStub; + let posts; + let postsPerPage; beforeEach(function () { postsPerPage = 5; diff --git a/test/unit/services/routing/controllers/collection_spec.js b/test/unit/services/routing/controllers/collection_spec.js index 56be84cd40..c4e5194529 100644 --- a/test/unit/services/routing/controllers/collection_spec.js +++ b/test/unit/services/routing/controllers/collection_spec.js @@ -1,12 +1,12 @@ -const should = require('should'), - sinon = require('sinon'), - testUtils = require('../../../../utils'), - common = require('../../../../../core/server/lib/common'), - security = require('../../../../../core/server/lib/security'), - themeService = require('../../../../../core/frontend/services/themes'), - urlService = require('../../../../../core/frontend/services/url'), - controllers = require('../../../../../core/frontend/services/routing/controllers'), - helpers = require('../../../../../core/frontend/services/routing/helpers'); +const should = require('should'); +const sinon = require('sinon'); +const testUtils = require('../../../../utils'); +const common = require('../../../../../core/server/lib/common'); +const security = require('../../../../../core/server/lib/security'); +const themeService = require('../../../../../core/frontend/services/themes'); +const urlService = require('../../../../../core/frontend/services/url'); +const controllers = require('../../../../../core/frontend/services/routing/controllers'); +const helpers = require('../../../../../core/frontend/services/routing/helpers'); function failTest(done) { return function (err) { @@ -16,7 +16,13 @@ function failTest(done) { } describe('Unit - services/routing/controllers/collection', function () { - let req, res, fetchDataStub, secureStub, renderStub, posts, postsPerPage; + let req; + let res; + let fetchDataStub; + let secureStub; + let renderStub; + let posts; + let postsPerPage; beforeEach(function () { postsPerPage = 5; diff --git a/test/unit/services/routing/controllers/entry_spec.js b/test/unit/services/routing/controllers/entry_spec.js index 841ee6e88a..d00c32b265 100644 --- a/test/unit/services/routing/controllers/entry_spec.js +++ b/test/unit/services/routing/controllers/entry_spec.js @@ -9,7 +9,13 @@ const helpers = require('../../../../../core/frontend/services/routing/helpers') const EDITOR_URL = `/editor/post/`; describe('Unit - services/routing/controllers/entry', function () { - let req, res, entryLookUpStub, secureStub, renderStub, post, page; + let req; + let res; + let entryLookUpStub; + let secureStub; + let renderStub; + let post; + let page; beforeEach(function () { post = testUtils.DataGenerator.forKnex.createPost(); diff --git a/test/unit/services/routing/controllers/preview_spec.js b/test/unit/services/routing/controllers/preview_spec.js index ab0f15c7d5..2bb68ca49a 100644 --- a/test/unit/services/routing/controllers/preview_spec.js +++ b/test/unit/services/routing/controllers/preview_spec.js @@ -1,19 +1,22 @@ -const should = require('should'), - sinon = require('sinon'), - Promise = require('bluebird'), - testUtils = require('../../../../utils'), - configUtils = require('../../../../utils/configUtils'), - api = require('../../../../../core/server/api'), - controllers = require('../../../../../core/frontend/services/routing/controllers'), - helpers = require('../../../../../core/frontend/services/routing/helpers'), - urlService = require('../../../../../core/frontend/services/url'), - urlUtils = require('../../../../../core/server/lib/url-utils'), - - EDITOR_URL = '/editor/post/'; +const should = require('should'); +const sinon = require('sinon'); +const Promise = require('bluebird'); +const testUtils = require('../../../../utils'); +const configUtils = require('../../../../utils/configUtils'); +const api = require('../../../../../core/server/api'); +const controllers = require('../../../../../core/frontend/services/routing/controllers'); +const helpers = require('../../../../../core/frontend/services/routing/helpers'); +const urlService = require('../../../../../core/frontend/services/url'); +const urlUtils = require('../../../../../core/server/lib/url-utils'); +const EDITOR_URL = '/editor/post/'; describe('Unit - services/routing/controllers/preview', function () { - let secureStub, renderStub; - let req, res, post, apiResponse; + let secureStub; + let renderStub; + let req; + let res; + let post; + let apiResponse; function failTest(done) { return function (err) { diff --git a/test/unit/services/routing/controllers/rss_spec.js b/test/unit/services/routing/controllers/rss_spec.js index b26fec1f0f..a27659f121 100644 --- a/test/unit/services/routing/controllers/rss_spec.js +++ b/test/unit/services/routing/controllers/rss_spec.js @@ -1,13 +1,13 @@ -const should = require('should'), - sinon = require('sinon'), - _ = require('lodash'), - testUtils = require('../../../../utils'), - common = require('../../../../../core/server/lib/common'), - security = require('../../../../../core/server/lib/security'), - settingsCache = require('../../../../../core/server/services/settings/cache'), - controllers = require('../../../../../core/frontend/services/routing/controllers'), - helpers = require('../../../../../core/frontend/services/routing/helpers'), - rssService = require('../../../../../core/frontend/services/rss'); +const should = require('should'); +const sinon = require('sinon'); +const _ = require('lodash'); +const testUtils = require('../../../../utils'); +const common = require('../../../../../core/server/lib/common'); +const security = require('../../../../../core/server/lib/security'); +const settingsCache = require('../../../../../core/server/services/settings/cache'); +const controllers = require('../../../../../core/frontend/services/routing/controllers'); +const helpers = require('../../../../../core/frontend/services/routing/helpers'); +const rssService = require('../../../../../core/frontend/services/rss'); // Helper function to prevent unit tests // from failing via timeout when they @@ -19,7 +19,11 @@ function failTest(done) { } describe('Unit - services/routing/controllers/rss', function () { - let req, res, next, fetchDataStub, posts; + let req; + let res; + let next; + let fetchDataStub; + let posts; beforeEach(function () { posts = [ diff --git a/test/unit/services/routing/controllers/static_spec.js b/test/unit/services/routing/controllers/static_spec.js index c092785799..daf9f9e62b 100644 --- a/test/unit/services/routing/controllers/static_spec.js +++ b/test/unit/services/routing/controllers/static_spec.js @@ -1,10 +1,10 @@ -const should = require('should'), - sinon = require('sinon'), - testUtils = require('../../../../utils'), - api = require('../../../../../core/server/api'), - themeService = require('../../../../../core/frontend/services/themes'), - helpers = require('../../../../../core/frontend/services/routing/helpers'), - controllers = require('../../../../../core/frontend/services/routing/controllers'); +const should = require('should'); +const sinon = require('sinon'); +const testUtils = require('../../../../utils'); +const api = require('../../../../../core/server/api'); +const themeService = require('../../../../../core/frontend/services/themes'); +const helpers = require('../../../../../core/frontend/services/routing/helpers'); +const controllers = require('../../../../../core/frontend/services/routing/controllers'); function failTest(done) { return function (err) { @@ -14,14 +14,14 @@ function failTest(done) { } describe('Unit - services/routing/controllers/static', function () { - let req, - res, - secureStub, - renderStub, - handleErrorStub, - formatResponseStub, - postsPerPage, - tagsReadStub; + let req; + let res; + let secureStub; + let renderStub; + let handleErrorStub; + let formatResponseStub; + let postsPerPage; + let tagsReadStub; beforeEach(function () { postsPerPage = 5; diff --git a/test/unit/services/routing/helpers/context_spec.js b/test/unit/services/routing/helpers/context_spec.js index cd41c36c80..0f9ec012c1 100644 --- a/test/unit/services/routing/helpers/context_spec.js +++ b/test/unit/services/routing/helpers/context_spec.js @@ -1,12 +1,14 @@ -const should = require('should'), - sinon = require('sinon'), - _ = require('lodash'), - testUtils = require('../../../../utils'), - helpers = require('../../../../../core/frontend/services/routing/helpers'), - labs = require('../../../../../core/server/services/labs'); +const should = require('should'); +const sinon = require('sinon'); +const _ = require('lodash'); +const testUtils = require('../../../../utils'); +const helpers = require('../../../../../core/frontend/services/routing/helpers'); +const labs = require('../../../../../core/server/services/labs'); describe('Contexts', function () { - let req, res, data, setupContext; + let req; + let res; + let data; beforeEach(function () { req = { diff --git a/test/unit/services/routing/helpers/entry-lookup_spec.js b/test/unit/services/routing/helpers/entry-lookup_spec.js index 0f7b67a0ad..9dcd511d65 100644 --- a/test/unit/services/routing/helpers/entry-lookup_spec.js +++ b/test/unit/services/routing/helpers/entry-lookup_spec.js @@ -1,12 +1,13 @@ -const should = require('should'), - sinon = require('sinon'), - Promise = require('bluebird'), - testUtils = require('../../../../utils'), - api = require('../../../../../core/server/api'), - helpers = require('../../../../../core/frontend/services/routing/helpers'); +const should = require('should'); +const sinon = require('sinon'); +const Promise = require('bluebird'); +const testUtils = require('../../../../utils'); +const api = require('../../../../../core/server/api'); +const helpers = require('../../../../../core/frontend/services/routing/helpers'); describe('Unit - services/routing/helpers/entry-lookup', function () { - let posts, locals; + let posts; + let locals; afterEach(function () { sinon.restore(); diff --git a/test/unit/services/routing/helpers/error_spec.js b/test/unit/services/routing/helpers/error_spec.js index 10169c6c0a..7e4e20de3e 100644 --- a/test/unit/services/routing/helpers/error_spec.js +++ b/test/unit/services/routing/helpers/error_spec.js @@ -1,7 +1,7 @@ -const should = require('should'), - sinon = require('sinon'), - common = require('../../../../../core/server/lib/common'), - helpers = require('../../../../../core/frontend/services/routing/helpers'); +const should = require('should'); +const sinon = require('sinon'); +const common = require('../../../../../core/server/lib/common'); +const helpers = require('../../../../../core/frontend/services/routing/helpers'); describe('handleError', function () { let next; diff --git a/test/unit/services/routing/helpers/fetch-data_spec.js b/test/unit/services/routing/helpers/fetch-data_spec.js index 1262ea2437..e504536bd7 100644 --- a/test/unit/services/routing/helpers/fetch-data_spec.js +++ b/test/unit/services/routing/helpers/fetch-data_spec.js @@ -5,8 +5,11 @@ const helpers = require('../../../../../core/frontend/services/routing/helpers') const testUtils = require('../../../../utils'); describe('Unit - services/routing/helpers/fetch-data', function () { - let posts, tags, locals; - let browsePostsStub, readTagsStub; + let posts; + let tags; + let locals; + let browsePostsStub; + let readTagsStub; beforeEach(function () { posts = [ diff --git a/test/unit/services/routing/helpers/format-response_spec.js b/test/unit/services/routing/helpers/format-response_spec.js index 7ce7cd7005..9fdf5a66fd 100644 --- a/test/unit/services/routing/helpers/format-response_spec.js +++ b/test/unit/services/routing/helpers/format-response_spec.js @@ -1,9 +1,10 @@ -const should = require('should'), - testUtils = require('../../../../utils'), - helpers = require('../../../../../core/frontend/services/routing/helpers'); +const should = require('should'); +const testUtils = require('../../../../utils'); +const helpers = require('../../../../../core/frontend/services/routing/helpers'); describe('Unit - services/routing/helpers/format-response', function () { - let posts, tags; + let posts; + let tags; beforeEach(function () { posts = [ @@ -17,8 +18,8 @@ describe('Unit - services/routing/helpers/format-response', function () { describe('entry', function () { it('should return the post object wrapped in a post key', function () { - let formatted, - postObject = posts[0]; + let formatted; + let postObject = posts[0]; formatted = helpers.formatResponse.entry(postObject); @@ -29,11 +30,12 @@ describe('Unit - services/routing/helpers/format-response', function () { describe('entries', function () { it('should return posts and posts pagination as top level keys', function () { - let formatted, - data = { - posts: posts, - meta: {pagination: {}} - }; + let formatted; + + let data = { + posts: posts, + meta: {pagination: {}} + }; formatted = helpers.formatResponse.entries(data); @@ -43,12 +45,13 @@ describe('Unit - services/routing/helpers/format-response', function () { }); it('should flatten api read responses which have no pagination data', function () { - let formatted, - data = { - posts: posts, - meta: {pagination: {}}, - data: {tag: tags} - }; + let formatted; + + let data = { + posts: posts, + meta: {pagination: {}}, + data: {tag: tags} + }; formatted = helpers.formatResponse.entries(data); @@ -57,17 +60,18 @@ describe('Unit - services/routing/helpers/format-response', function () { }); it('should remove the meta key from api browse responses', function () { - let formatted, - data = { - posts: posts, - meta: {pagination: {}}, - data: { - featured: { - posts: posts, - meta: {pagination: {}} - } + let formatted; + + let data = { + posts: posts, + meta: {pagination: {}}, + data: { + featured: { + posts: posts, + meta: {pagination: {}} } - }; + } + }; formatted = helpers.formatResponse.entries(data); diff --git a/test/unit/services/routing/helpers/templates_spec.js b/test/unit/services/routing/helpers/templates_spec.js index 3311a426de..48cbcc197b 100644 --- a/test/unit/services/routing/helpers/templates_spec.js +++ b/test/unit/services/routing/helpers/templates_spec.js @@ -1,12 +1,13 @@ -const should = require('should'), - sinon = require('sinon'), - rewire = require('rewire'), - templates = rewire('../../../../../core/frontend/services/routing/helpers/templates'), - themes = require('../../../../../core/frontend/services/themes'); +const should = require('should'); +const sinon = require('sinon'); +const rewire = require('rewire'); +const templates = rewire('../../../../../core/frontend/services/routing/helpers/templates'); +const themes = require('../../../../../core/frontend/services/themes'); describe('templates', function () { - let getActiveThemeStub, hasTemplateStub, - _private = templates.__get__('_private'); + let getActiveThemeStub; + let hasTemplateStub; + let _private = templates.__get__('_private'); afterEach(function () { sinon.restore(); @@ -129,7 +130,7 @@ describe('templates', function () { it('will fall back to post even if no index.hbs', function () { hasTemplateStub.returns(false); - var view = _private.getTemplateForEntry({page: 1}); + const view = _private.getTemplateForEntry({page: 1}); should.exist(view); view.should.eql('post'); }); @@ -145,7 +146,7 @@ describe('templates', function () { }); it('post without custom slug template', function () { - var view = _private.getTemplateForEntry({ + const view = _private.getTemplateForEntry({ page: 0, slug: 'test-post' }); @@ -155,7 +156,7 @@ describe('templates', function () { it('post with custom slug template', function () { hasTemplateStub.withArgs('post-welcome-to-ghost').returns(true); - var view = _private.getTemplateForEntry({ + const view = _private.getTemplateForEntry({ page: 0, slug: 'welcome-to-ghost' }); @@ -164,7 +165,7 @@ describe('templates', function () { }); it('page without custom slug template', function () { - var view = _private.getTemplateForEntry({ + const view = _private.getTemplateForEntry({ page: 1, slug: 'contact' }); @@ -173,7 +174,7 @@ describe('templates', function () { }); it('page with custom slug template', function () { - var view = _private.getTemplateForEntry({ + const view = _private.getTemplateForEntry({ page: 1, slug: 'about' }); @@ -184,7 +185,7 @@ describe('templates', function () { it('post with custom template', function () { hasTemplateStub.withArgs('custom-about').returns(true); - var view = _private.getTemplateForEntry({ + const view = _private.getTemplateForEntry({ page: 0, custom_template: 'custom-about' }); @@ -195,7 +196,7 @@ describe('templates', function () { it('page with custom template', function () { hasTemplateStub.withArgs('custom-about').returns(true); - var view = _private.getTemplateForEntry({ + const view = _private.getTemplateForEntry({ page: 1, custom_template: 'custom-about' }); @@ -206,7 +207,7 @@ describe('templates', function () { it('post with custom template configured, but the template is missing', function () { hasTemplateStub.withArgs('custom-about').returns(false); - var view = _private.getTemplateForEntry({ + const view = _private.getTemplateForEntry({ page: 0, custom_template: 'custom-about' }); @@ -217,7 +218,7 @@ describe('templates', function () { it('page with custom template configured, but the template is missing', function () { hasTemplateStub.withArgs('custom-about').returns(false); - var view = _private.getTemplateForEntry({ + const view = _private.getTemplateForEntry({ page: 1, custom_template: 'custom-about' }); @@ -229,7 +230,7 @@ describe('templates', function () { hasTemplateStub.withArgs('custom-about').returns(true); hasTemplateStub.withArgs('post-about').returns(true); - var view = _private.getTemplateForEntry({ + const view = _private.getTemplateForEntry({ page: 0, slug: 'about', custom_template: 'custom-about' @@ -242,7 +243,7 @@ describe('templates', function () { hasTemplateStub.withArgs('custom-about').returns(false); hasTemplateStub.withArgs('post-about').returns(false); - var view = _private.getTemplateForEntry({ + const view = _private.getTemplateForEntry({ page: 0, slug: 'about', custom_template: 'custom-about' @@ -269,7 +270,7 @@ describe('templates', function () { }); it('will return correct view for a tag', function () { - var view = _private.getTemplateForEntries({name: 'tag', slugTemplate: true}, {slugParam: 'development'}); + const view = _private.getTemplateForEntries({name: 'tag', slugTemplate: true}, {slugParam: 'development'}); should.exist(view); view.should.eql('index'); }); @@ -284,20 +285,20 @@ describe('templates', function () { }); it('will return correct view for a tag', function () { - var view = _private.getTemplateForEntries({name: 'tag', slugTemplate: true}, {slugParam: 'design'}); + const view = _private.getTemplateForEntries({name: 'tag', slugTemplate: true}, {slugParam: 'design'}); should.exist(view); view.should.eql('tag-design'); }); it('will return correct view for a tag', function () { - var view = _private.getTemplateForEntries({name: 'tag', slugTemplate: true}, {slugParam: 'development'}); + const view = _private.getTemplateForEntries({name: 'tag', slugTemplate: true}, {slugParam: 'development'}); should.exist(view); view.should.eql('tag'); }); }); it('will fall back to index even if no index.hbs', function () { - var view = _private.getTemplateForEntries({name: 'tag', slugTemplate: true}, {slugParam: 'development'}); + const view = _private.getTemplateForEntries({name: 'tag', slugTemplate: true}, {slugParam: 'development'}); should.exist(view); view.should.eql('index'); }); @@ -383,7 +384,10 @@ describe('templates', function () { }); describe('fn: setTemplate', function () { - var stubs = {}, req, res, data; + const stubs = {}; + let req; + let res; + let data; beforeEach(function () { req = {}; diff --git a/test/unit/services/routing/middlewares/page-param_spec.js b/test/unit/services/routing/middlewares/page-param_spec.js index 53c4dbb683..4b298a841e 100644 --- a/test/unit/services/routing/middlewares/page-param_spec.js +++ b/test/unit/services/routing/middlewares/page-param_spec.js @@ -1,11 +1,13 @@ -const should = require('should'), - sinon = require('sinon'), - common = require('../../../../../core/server/lib/common'), - urlUtils = require('../../../../../core/server/lib/url-utils'), - middlewares = require('../../../../../core/frontend/services/routing/middlewares'); +const should = require('should'); +const sinon = require('sinon'); +const common = require('../../../../../core/server/lib/common'); +const urlUtils = require('../../../../../core/server/lib/url-utils'); +const middlewares = require('../../../../../core/frontend/services/routing/middlewares'); describe('UNIT: services/routing/middlewares/page-param', function () { - let req, res, next; + let req; + let res; + let next; beforeEach(function () { req = sinon.stub(); diff --git a/test/unit/services/routing/registry_spec.js b/test/unit/services/routing/registry_spec.js index 702daf62a0..6d1a066eea 100644 --- a/test/unit/services/routing/registry_spec.js +++ b/test/unit/services/routing/registry_spec.js @@ -1,7 +1,7 @@ -const should = require('should'), - sinon = require('sinon'), - rewire = require('rewire'), - registry = rewire('../../../../core/frontend/services/routing/registry'); +const should = require('should'); +const sinon = require('sinon'); +const rewire = require('rewire'); +const registry = rewire('../../../../core/frontend/services/routing/registry'); describe('UNIT: services/routing/registry', function () { let getRssUrlStub; diff --git a/test/unit/services/rss/cache_spec.js b/test/unit/services/rss/cache_spec.js index 6f0278a996..3d772f8590 100644 --- a/test/unit/services/rss/cache_spec.js +++ b/test/unit/services/rss/cache_spec.js @@ -1,11 +1,12 @@ -var should = require('should'), - sinon = require('sinon'), - rewire = require('rewire'), - configUtils = require('../../../utils/configUtils'), - rssCache = rewire('../../../../core/frontend/services/rss/cache'); +const should = require('should'); +const sinon = require('sinon'); +const rewire = require('rewire'); +const configUtils = require('../../../utils/configUtils'); +const rssCache = rewire('../../../../core/frontend/services/rss/cache'); describe('RSS: Cache', function () { - var generateSpy, generateFeedReset; + let generateSpy; + let generateFeedReset; afterEach(function () { configUtils.restore(); @@ -21,13 +22,13 @@ describe('RSS: Cache', function () { }); it('should not rebuild xml for same data and url', function (done) { - var xmlData1, - data = { - title: 'Test Title', - description: 'Testing Desc', - posts: [], - meta: {pagination: {pages: 1}} - }; + const data = { + title: 'Test Title', + description: 'Testing Desc', + posts: [], + meta: {pagination: {pages: 1}} + }; + let xmlData1; rssCache.getXML('/rss/', data) .then(function (_xmlData) { diff --git a/test/unit/services/rss/generate-feed_spec.js b/test/unit/services/rss/generate-feed_spec.js index 18b576defc..60a111c05d 100644 --- a/test/unit/services/rss/generate-feed_spec.js +++ b/test/unit/services/rss/generate-feed_spec.js @@ -1,16 +1,17 @@ -var should = require('should'), - sinon = require('sinon'), - _ = require('lodash'), - testUtils = require('../../../utils'), - urlUtils = require('../../../utils/urlUtils'), - urlService = require('../../../../core/frontend/services/url'), - generateFeed = require('../../../../core/frontend/services/rss/generate-feed'); +const should = require('should'); +const sinon = require('sinon'); +const _ = require('lodash'); +const testUtils = require('../../../utils'); +const urlUtils = require('../../../utils/urlUtils'); +const urlService = require('../../../../core/frontend/services/url'); +const generateFeed = require('../../../../core/frontend/services/rss/generate-feed'); describe('RSS: Generate Feed', function () { - var data = {}, - baseUrl, - // Static set of posts - posts; + const data = {}; + let baseUrl; + + // Static set of posts + let posts; before(function () { posts = _.cloneDeep(testUtils.DataGenerator.forKnex.posts); @@ -105,8 +106,8 @@ describe('RSS: Generate Feed', function () { xmlData.should.not.match(//); // basic structure check - var postEnd = '<\/code><\/pre>\]\]><\/content:encoded>', - firstIndex = xmlData.indexOf(postEnd); + const postEnd = '<\/code><\/pre>\]\]><\/content:encoded>'; + const firstIndex = xmlData.indexOf(postEnd); // The first title should be before the first content xmlData.indexOf('HTML Ipsum').should.be.below(firstIndex); @@ -118,7 +119,7 @@ describe('RSS: Generate Feed', function () { }); it('should only return visible tags', function (done) { - var postWithTags = posts[2]; + const postWithTags = posts[2]; postWithTags.tags = [ {name: 'public', visibility: 'public'}, {name: 'internal', visibility: 'internal'}, diff --git a/test/unit/services/rss/renderer_spec.js b/test/unit/services/rss/renderer_spec.js index 0169847918..9f031ac041 100644 --- a/test/unit/services/rss/renderer_spec.js +++ b/test/unit/services/rss/renderer_spec.js @@ -1,12 +1,13 @@ -var should = require('should'), - sinon = require('sinon'), - Promise = require('bluebird'), - - rssCache = require('../../../../core/frontend/services/rss/cache'), - renderer = require('../../../../core/frontend/services/rss/renderer'); +const should = require('should'); +const sinon = require('sinon'); +const Promise = require('bluebird'); +const rssCache = require('../../../../core/frontend/services/rss/cache'); +const renderer = require('../../../../core/frontend/services/rss/renderer'); describe('RSS: Renderer', function () { - var rssCacheStub, res, baseUrl; + let rssCacheStub; + let res; + let baseUrl; beforeEach(function () { rssCacheStub = sinon.stub(rssCache, 'getXML'); @@ -64,7 +65,7 @@ describe('RSS: Renderer', function () { rssCacheStub.returns(new Promise.resolve('dummyxml')); res.locals = {foo: 'bar'}; - var data = {foo: 'baz', fizz: 'buzz'}; + const data = {foo: 'baz', fizz: 'buzz'}; renderer.render(res, baseUrl, data).then(function () { rssCacheStub.calledOnce.should.be.true(); diff --git a/test/unit/services/settings/ensure-settings_spec.js b/test/unit/services/settings/ensure-settings_spec.js index bfad0d2d75..dc6dec8e0e 100644 --- a/test/unit/services/settings/ensure-settings_spec.js +++ b/test/unit/services/settings/ensure-settings_spec.js @@ -1,12 +1,11 @@ -const sinon = require('sinon'), - should = require('should'), - fs = require('fs-extra'), - yaml = require('js-yaml'), - path = require('path'), - configUtils = require('../../../utils/configUtils'), - common = require('../../../../core/server/lib/common'), - - ensureSettings = require('../../../../core/frontend/services/settings/ensure-settings'); +const sinon = require('sinon'); +const should = require('should'); +const fs = require('fs-extra'); +const yaml = require('js-yaml'); +const path = require('path'); +const configUtils = require('../../../utils/configUtils'); +const common = require('../../../../core/server/lib/common'); +const ensureSettings = require('../../../../core/frontend/services/settings/ensure-settings'); describe('UNIT > Settings Service ensure settings:', function () { beforeEach(function () { diff --git a/test/unit/services/settings/loader_spec.js b/test/unit/services/settings/loader_spec.js index 7215f616f8..286f403c16 100644 --- a/test/unit/services/settings/loader_spec.js +++ b/test/unit/services/settings/loader_spec.js @@ -1,11 +1,11 @@ -const sinon = require('sinon'), - should = require('should'), - rewire = require('rewire'), - fs = require('fs-extra'), - path = require('path'), - configUtils = require('../../../utils/configUtils'), - common = require('../../../../core/server/lib/common'), - loadSettings = rewire('../../../../core/frontend/services/settings/loader'); +const sinon = require('sinon'); +const should = require('should'); +const rewire = require('rewire'); +const fs = require('fs-extra'); +const path = require('path'); +const configUtils = require('../../../utils/configUtils'); +const common = require('../../../../core/server/lib/common'); +const loadSettings = rewire('../../../../core/frontend/services/settings/loader'); describe('UNIT > Settings Service loader:', function () { beforeEach(function () { diff --git a/test/unit/services/settings/settings_spec.js b/test/unit/services/settings/settings_spec.js index 4f9eb6b270..fc58acf3ca 100644 --- a/test/unit/services/settings/settings_spec.js +++ b/test/unit/services/settings/settings_spec.js @@ -1,8 +1,8 @@ -const sinon = require('sinon'), - should = require('should'), - rewire = require('rewire'), - common = require('../../../../core/server/lib/common'), - settings = rewire('../../../../core/frontend/services/settings'); +const sinon = require('sinon'); +const should = require('should'); +const rewire = require('rewire'); +const common = require('../../../../core/server/lib/common'); +const settings = rewire('../../../../core/frontend/services/settings'); describe('UNIT > Settings Service:', function () { afterEach(function () { @@ -78,24 +78,25 @@ describe('UNIT > Settings Service:', function () { }); describe('getAll', function () { - let settingsLoaderStub, - knownSettingsStub; + let settingsLoaderStub; + let knownSettingsStub; const settingsStubFile1 = { - routes: null, - collections: { - '/': { - permalink: '/{slug}/', - template: ['home', 'index'] - } - }, - resources: {tag: '/tag/{slug}/', author: '/author/{slug}/'} - }, - settingsStubFile2 = { - config: { - url: 'https://testblog.com' + routes: null, + collections: { + '/': { + permalink: '/{slug}/', + template: ['home', 'index'] } - }; + }, + resources: {tag: '/tag/{slug}/', author: '/author/{slug}/'} + }; + + const settingsStubFile2 = { + config: { + url: 'https://testblog.com' + } + }; beforeEach(function () { knownSettingsStub = sinon.stub().returns(['routes', 'globals']); diff --git a/test/unit/services/settings/yaml-parser_spec.js b/test/unit/services/settings/yaml-parser_spec.js index 4eb65ce2b9..23a36eede1 100644 --- a/test/unit/services/settings/yaml-parser_spec.js +++ b/test/unit/services/settings/yaml-parser_spec.js @@ -1,10 +1,9 @@ -const sinon = require('sinon'), - should = require('should'), - fs = require('fs-extra'), - yaml = require('js-yaml'), - path = require('path'), - - yamlParser = require('../../../../core/frontend/services/settings/yaml-parser'); +const sinon = require('sinon'); +const should = require('should'); +const fs = require('fs-extra'); +const yaml = require('js-yaml'); +const path = require('path'); +const yamlParser = require('../../../../core/frontend/services/settings/yaml-parser'); describe('UNIT > Settings Service yaml parser:', function () { let yamlSpy; diff --git a/test/unit/services/slack_spec.js b/test/unit/services/slack_spec.js index e04afb4d80..34e47bdca2 100644 --- a/test/unit/services/slack_spec.js +++ b/test/unit/services/slack_spec.js @@ -1,24 +1,26 @@ -var should = require('should'), - sinon = require('sinon'), - _ = require('lodash'), - rewire = require('rewire'), - testUtils = require('../../utils'), - configUtils = require('../../utils/configUtils'), +const should = require('should'); +const sinon = require('sinon'); +const _ = require('lodash'); +const rewire = require('rewire'); +const testUtils = require('../../utils'); +const configUtils = require('../../utils/configUtils'); - // Stuff we test - slack = rewire('../../../core/server/services/slack'), - common = require('../../../core/server/lib/common'), - imageLib = require('../../../core/server/lib/image'), - urlService = require('../../../core/frontend/services/url'), - schema = require('../../../core/server/data/schema').checks, - settingsCache = require('../../../core/server/services/settings/cache'), +// Stuff we test +const slack = rewire('../../../core/server/services/slack'); - // Test data - slackObjNoUrl = [{url: ''}], - slackObjWithUrl = [{url: 'https://hooks.slack.com/services/a-b-c-d'}]; +const common = require('../../../core/server/lib/common'); +const imageLib = require('../../../core/server/lib/image'); +const urlService = require('../../../core/frontend/services/url'); +const schema = require('../../../core/server/data/schema').checks; +const settingsCache = require('../../../core/server/services/settings/cache'); + +// Test data +const slackObjNoUrl = [{url: ''}]; + +const slackObjWithUrl = [{url: 'https://hooks.slack.com/services/a-b-c-d'}]; describe('Slack', function () { - var eventStub; + let eventStub; beforeEach(function () { eventStub = sinon.stub(common.events, 'on'); @@ -37,15 +39,17 @@ describe('Slack', function () { }); it('listener() calls ping() with toJSONified model', function () { - var testPost = _.clone(testUtils.DataGenerator.Content.posts[2]), - testModel = { - toJSON: function () { - return testPost; - } - }, - pingStub = sinon.stub(), - resetSlack = slack.__set__('ping', pingStub), - listener = slack.__get__('listener'); + const testPost = _.clone(testUtils.DataGenerator.Content.posts[2]); + + const testModel = { + toJSON: function () { + return testPost; + } + }; + + const pingStub = sinon.stub(); + const resetSlack = slack.__set__('ping', pingStub); + const listener = slack.__get__('listener'); listener(testModel); @@ -57,15 +61,17 @@ describe('Slack', function () { }); it('listener() does not call ping() when importing', function () { - var testPost = _.clone(testUtils.DataGenerator.Content.posts[2]), - testModel = { - toJSON: function () { - return testPost; - } - }, - pingStub = sinon.stub(), - resetSlack = slack.__set__('ping', pingStub), - listener = slack.__get__('listener'); + const testPost = _.clone(testUtils.DataGenerator.Content.posts[2]); + + const testModel = { + toJSON: function () { + return testPost; + } + }; + + const pingStub = sinon.stub(); + const resetSlack = slack.__set__('ping', pingStub); + const listener = slack.__get__('listener'); listener(testModel, {importing: true}); @@ -76,9 +82,9 @@ describe('Slack', function () { }); it('testPing() calls ping() with default message', function () { - var pingStub = sinon.stub(), - resetSlack = slack.__set__('ping', pingStub), - testPing = slack.__get__('testPing'); + const pingStub = sinon.stub(); + const resetSlack = slack.__set__('ping', pingStub); + const testPing = slack.__get__('testPing'); testPing(); @@ -90,12 +96,11 @@ describe('Slack', function () { }); describe('ping()', function () { - var isPostStub, - settingsCacheStub, - - slackReset, - makeRequestStub, - ping = slack.__get__('ping'); + let isPostStub; + let settingsCacheStub; + let slackReset; + let makeRequestStub; + const ping = slack.__get__('ping'); beforeEach(function () { isPostStub = sinon.stub(schema, 'isPost'); @@ -118,7 +123,8 @@ describe('Slack', function () { }); it('makes a request for a post if url is provided', function () { - var requestUrl, requestData; + let requestUrl; + let requestData; const post = testUtils.DataGenerator.forKnex.createPost({slug: 'webhook-test'}); urlService.getUrlByResourceId.withArgs(post.id, {absolute: true}).returns('http://myblog.com/' + post.slug + '/'); @@ -150,7 +156,8 @@ describe('Slack', function () { }); it('makes a request for a message if url is provided', function () { - var requestUrl, requestData; + let requestUrl; + let requestData; isPostStub.returns(false); settingsCacheStub.withArgs('slack').returns(slackObjWithUrl); diff --git a/test/unit/services/themes/active_spec.js b/test/unit/services/themes/active_spec.js index 8226aa1a85..1258578da0 100644 --- a/test/unit/services/themes/active_spec.js +++ b/test/unit/services/themes/active_spec.js @@ -1,10 +1,11 @@ -var should = require('should'), - sinon = require('sinon'), +const should = require('should'); +const sinon = require('sinon'); +const config = require('../../../../core/server/config'); - config = require('../../../../core/server/config'), - // is only exposed via themes.getActive() - activeTheme = require('../../../../core/frontend/services/themes/active'), - engine = require('../../../../core/frontend/services/themes/engine'); +// is only exposed via themes.getActive() +const activeTheme = require('../../../../core/frontend/services/themes/active'); + +const engine = require('../../../../core/frontend/services/themes/engine'); describe('Themes', function () { afterEach(function () { @@ -13,8 +14,11 @@ describe('Themes', function () { describe('Active', function () { describe('Mount', function () { - var engineStub, configStub, - fakeBlogApp, fakeLoadedTheme, fakeCheckedTheme; + let engineStub; + let configStub; + let fakeBlogApp; + let fakeLoadedTheme; + let fakeCheckedTheme; beforeEach(function () { engineStub = sinon.stub(engine, 'configure'); @@ -42,7 +46,7 @@ describe('Themes', function () { // setup partials fakeCheckedTheme.partials = ['loop', 'navigation']; - var theme = activeTheme.set(fakeLoadedTheme, fakeCheckedTheme); + const theme = activeTheme.set(fakeLoadedTheme, fakeCheckedTheme); // Check the theme is not yet mounted activeTheme.get().mounted.should.be.false(); @@ -73,7 +77,7 @@ describe('Themes', function () { // setup partials fakeCheckedTheme.partials = []; - var theme = activeTheme.set(fakeLoadedTheme, fakeCheckedTheme); + const theme = activeTheme.set(fakeLoadedTheme, fakeCheckedTheme); // Check the theme is not yet mounted activeTheme.get().mounted.should.be.false(); diff --git a/test/unit/services/themes/config_spec.js b/test/unit/services/themes/config_spec.js index 6b09e73012..29bad6fa5a 100644 --- a/test/unit/services/themes/config_spec.js +++ b/test/unit/services/themes/config_spec.js @@ -1,7 +1,6 @@ -var should = require('should'), - sinon = require('sinon'), - - themeConfig = require('../../../../core/frontend/services/themes/config'); +const should = require('should'); +const sinon = require('sinon'); +const themeConfig = require('../../../../core/frontend/services/themes/config'); describe('Themes', function () { afterEach(function () { @@ -10,25 +9,25 @@ describe('Themes', function () { describe('Config', function () { it('handles no package.json', function () { - var config = themeConfig.create(); + const config = themeConfig.create(); config.should.eql({posts_per_page: 5}); }); it('handles package.json without config', function () { - var config = themeConfig.create({name: 'casper'}); + const config = themeConfig.create({name: 'casper'}); config.should.eql({posts_per_page: 5}); }); it('handles allows package.json to overrideg default', function () { - var config = themeConfig.create({name: 'casper', config: {posts_per_page: 3}}); + const config = themeConfig.create({name: 'casper', config: {posts_per_page: 3}}); config.should.eql({posts_per_page: 3}); }); it('handles ignores non-allowed config', function () { - var config = themeConfig.create({name: 'casper', config: {magic: 'roundabout'}}); + const config = themeConfig.create({name: 'casper', config: {magic: 'roundabout'}}); config.should.eql({posts_per_page: 5}); }); diff --git a/test/unit/services/themes/handlebars/helpers_spec.js b/test/unit/services/themes/handlebars/helpers_spec.js index 015b18f810..d742260128 100644 --- a/test/unit/services/themes/handlebars/helpers_spec.js +++ b/test/unit/services/themes/handlebars/helpers_spec.js @@ -6,14 +6,15 @@ const hbs = require('../../../../../core/frontend/services/themes/engine'); const helpers = require('../../../../../core/frontend/helpers'); describe('Helpers', function () { - var hbsHelpers = ['each', 'if', 'unless', 'with', 'helperMissing', 'blockHelperMissing', 'log', 'lookup', 'block', 'contentFor'], - ghostHelpers = [ - 'asset', 'author', 'authors', 'body_class', 'cancel_link', 'concat', 'content', 'date', 'encode', 'excerpt', 'facebook_url', 'foreach', 'get', - 'ghost_foot', 'ghost_head', 'has', 'img_url', 'is', 'lang', 'link', 'link_class', 'meta_description', 'meta_title', 'navigation', - 'next_post', 'page_url', 'pagination', 'plural', 'post_class', 'prev_post', 'price', 'raw', 'reading_time', 't', 'tags', 'title', 'twitter_url', - 'url' - ], - expectedHelpers = _.concat(hbsHelpers, ghostHelpers); + const hbsHelpers = ['each', 'if', 'unless', 'with', 'helperMissing', 'blockHelperMissing', 'log', 'lookup', 'block', 'contentFor']; + const ghostHelpers = [ + 'asset', 'author', 'authors', 'body_class', 'cancel_link', 'concat', 'content', 'date', 'encode', 'excerpt', 'facebook_url', 'foreach', 'get', + 'ghost_foot', 'ghost_head', 'has', 'img_url', 'is', 'lang', 'link', 'link_class', 'meta_description', 'meta_title', 'navigation', + 'next_post', 'page_url', 'pagination', 'plural', 'post_class', 'prev_post', 'price', 'raw', 'reading_time', 't', 'tags', 'title', 'twitter_url', + 'url' + ]; + + const expectedHelpers = _.concat(hbsHelpers, ghostHelpers); describe('Load Core Helpers', function () { before(function () { @@ -23,12 +24,9 @@ describe('Helpers', function () { // This will work when we finish refactoring it('should have exactly the right helpers', function () { - var foundHelpers, missingHelpers, unexpectedHelpers; - - foundHelpers = _.keys(hbs.handlebars.helpers); - - missingHelpers = _.difference(expectedHelpers, foundHelpers); - unexpectedHelpers = _.difference(foundHelpers, expectedHelpers); + const foundHelpers = _.keys(hbs.handlebars.helpers); + const missingHelpers = _.difference(expectedHelpers, foundHelpers); + const unexpectedHelpers = _.difference(foundHelpers, expectedHelpers); missingHelpers.should.be.an.Array().with.lengthOf(0); unexpectedHelpers.should.be.an.Array().with.lengthOf(0); diff --git a/test/unit/services/themes/handlebars/template_spec.js b/test/unit/services/themes/handlebars/template_spec.js index ece2189e62..e2543a19bf 100644 --- a/test/unit/services/themes/handlebars/template_spec.js +++ b/test/unit/services/themes/handlebars/template_spec.js @@ -6,7 +6,7 @@ describe('Helpers Template', function () { it('can execute a template', function () { hbs.registerPartial('test', '

      Hello {{name}}

      '); - var safeString = template.execute('test', {name: 'world'}); + const safeString = template.execute('test', {name: 'world'}); should.exist(safeString); safeString.should.have.property('string').and.equal('

      Hello world

      '); diff --git a/test/unit/services/themes/list_spec.js b/test/unit/services/themes/list_spec.js index 5f99929dc8..5e8c1d27f6 100644 --- a/test/unit/services/themes/list_spec.js +++ b/test/unit/services/themes/list_spec.js @@ -1,7 +1,7 @@ -var should = require('should'), - sinon = require('sinon'), - _ = require('lodash'), - themeList = require('../../../../core/frontend/services/themes/list'); +const should = require('should'); +const sinon = require('sinon'); +const _ = require('lodash'); +const themeList = require('../../../../core/frontend/services/themes/list'); describe('Themes', function () { afterEach(function () { @@ -30,7 +30,7 @@ describe('Themes', function () { }); it('set() updates an existing theme', function () { - var origCasper = _.cloneDeep(themeList.get('casper')); + const origCasper = _.cloneDeep(themeList.get('casper')); themeList.set('casper', {magic: 'update'}); themeList.get('casper').should.not.eql(origCasper); @@ -59,7 +59,7 @@ describe('Themes', function () { }); it('init() calls set for each theme', function () { - var setSpy = sinon.spy(themeList, 'set'); + const setSpy = sinon.spy(themeList, 'set'); themeList.init({test: {a: 'b'}, casper: {c: 'd'}}); setSpy.calledTwice.should.be.true(); @@ -69,7 +69,7 @@ describe('Themes', function () { it('init() with empty object resets the list', function () { themeList.init(); - var result = themeList.getAll(); + const result = themeList.getAll(); should.exist(result); result.should.be.an.Object(); result.should.eql({}); diff --git a/test/unit/services/themes/loader_spec.js b/test/unit/services/themes/loader_spec.js index 2e7e277c92..d81976c32d 100644 --- a/test/unit/services/themes/loader_spec.js +++ b/test/unit/services/themes/loader_spec.js @@ -1,11 +1,11 @@ -var should = require('should'), - sinon = require('sinon'), - fs = require('fs-extra'), - tmp = require('tmp'), - join = require('path').join, - config = require('../../../../core/server/config'), - loader = require('../../../../core/frontend/services/themes/loader'), - themeList = require('../../../../core/frontend/services/themes/list'); +const should = require('should'); +const sinon = require('sinon'); +const fs = require('fs-extra'); +const tmp = require('tmp'); +const join = require('path').join; +const config = require('../../../../core/server/config'); +const loader = require('../../../../core/frontend/services/themes/loader'); +const themeList = require('../../../../core/frontend/services/themes/list'); describe('Themes', function () { afterEach(function () { @@ -13,7 +13,7 @@ describe('Themes', function () { }); describe('Loader', function () { - var themePath; + let themePath; beforeEach(function () { themePath = tmp.dirSync({unsafeCleanup: true}); @@ -38,7 +38,7 @@ describe('Themes', function () { loader.loadAllThemes() .then(function (result) { - var themeResult = themeList.getAll(); + const themeResult = themeList.getAll(); // Loader doesn't return anything should.not.exist(result); @@ -71,7 +71,7 @@ describe('Themes', function () { loader.loadAllThemes() .then(function (result) { - var themeResult = themeList.getAll(); + const themeResult = themeList.getAll(); // Loader doesn't return anything should.not.exist(result); diff --git a/test/unit/services/url/UrlGenerator_spec.js b/test/unit/services/url/UrlGenerator_spec.js index c3e910196b..7e91fe7ee8 100644 --- a/test/unit/services/url/UrlGenerator_spec.js +++ b/test/unit/services/url/UrlGenerator_spec.js @@ -7,7 +7,12 @@ const urlUtils = require('../../../../core/server/lib/url-utils'); const UrlGenerator = require('../../../../core/frontend/services/url/UrlGenerator'); describe('Unit: services/url/UrlGenerator', function () { - let queue, router, urls, resources, resource, resource2; + let queue; + let router; + let urls; + let resources; + let resource; + let resource2; beforeEach(function () { queue = { diff --git a/test/unit/services/url/UrlService_spec.js b/test/unit/services/url/UrlService_spec.js index b3c4e7de85..ebbda7289a 100644 --- a/test/unit/services/url/UrlService_spec.js +++ b/test/unit/services/url/UrlService_spec.js @@ -11,7 +11,11 @@ const Urls = require('../../../../core/frontend/services/url/Urls'); const UrlService = rewire('../../../../core/frontend/services/url/UrlService'); describe('Unit: services/url/UrlService', function () { - let QueueStub, ResourcesStub, UrlsStub, UrlGeneratorStub, urlService; + let QueueStub; + let ResourcesStub; + let UrlsStub; + let UrlGeneratorStub; + let urlService; beforeEach(function () { QueueStub = sinon.stub(); diff --git a/test/unit/services/url/Urls_spec.js b/test/unit/services/url/Urls_spec.js index b3b3409cdd..0df47122b1 100644 --- a/test/unit/services/url/Urls_spec.js +++ b/test/unit/services/url/Urls_spec.js @@ -7,7 +7,8 @@ const common = require('../../../../core/server/lib/common'); const Urls = require('../../../../core/frontend/services/url/Urls'); describe('Unit: services/url/Urls', function () { - let urls, eventsToRemember; + let urls; + let eventsToRemember; beforeEach(function () { urls = new Urls(); diff --git a/test/unit/services/xmlrpc_spec.js b/test/unit/services/xmlrpc_spec.js index 8cd0d45cf5..460367f583 100644 --- a/test/unit/services/xmlrpc_spec.js +++ b/test/unit/services/xmlrpc_spec.js @@ -1,16 +1,16 @@ -var should = require('should'), - sinon = require('sinon'), - _ = require('lodash'), - nock = require('nock'), - http = require('http'), - rewire = require('rewire'), - testUtils = require('../../utils'), - configUtils = require('../../utils/configUtils'), - xmlrpc = rewire('../../../core/server/services/xmlrpc'), - common = require('../../../core/server/lib/common'); +const should = require('should'); +const sinon = require('sinon'); +const _ = require('lodash'); +const nock = require('nock'); +const http = require('http'); +const rewire = require('rewire'); +const testUtils = require('../../utils'); +const configUtils = require('../../utils/configUtils'); +const xmlrpc = rewire('../../../core/server/services/xmlrpc'); +const common = require('../../../core/server/lib/common'); describe('XMLRPC', function () { - var eventStub; + let eventStub; beforeEach(function () { eventStub = sinon.stub(common.events, 'on'); @@ -30,15 +30,17 @@ describe('XMLRPC', function () { }); it('listener() calls ping() with toJSONified model', function () { - var testPost = _.clone(testUtils.DataGenerator.Content.posts[2]), - testModel = { - toJSON: function () { - return testPost; - } - }, - pingStub = sinon.stub(), - resetXmlRpc = xmlrpc.__set__('ping', pingStub), - listener = xmlrpc.__get__('listener'); + const testPost = _.clone(testUtils.DataGenerator.Content.posts[2]); + + const testModel = { + toJSON: function () { + return testPost; + } + }; + + const pingStub = sinon.stub(); + const resetXmlRpc = xmlrpc.__set__('ping', pingStub); + const listener = xmlrpc.__get__('listener'); listener(testModel); @@ -50,15 +52,17 @@ describe('XMLRPC', function () { }); it('listener() does not call ping() when importing', function () { - var testPost = _.clone(testUtils.DataGenerator.Content.posts[2]), - testModel = { - toJSON: function () { - return testPost; - } - }, - pingStub = sinon.stub(), - resetXmlRpc = xmlrpc.__set__('ping', pingStub), - listener = xmlrpc.__get__('listener'); + const testPost = _.clone(testUtils.DataGenerator.Content.posts[2]); + + const testModel = { + toJSON: function () { + return testPost; + } + }; + + const pingStub = sinon.stub(); + const resetXmlRpc = xmlrpc.__set__('ping', pingStub); + const listener = xmlrpc.__get__('listener'); listener(testModel, {importing: true}); @@ -69,11 +73,11 @@ describe('XMLRPC', function () { }); describe('ping()', function () { - var ping = xmlrpc.__get__('ping'); + const ping = xmlrpc.__get__('ping'); it('with a post should execute two pings', function (done) { - var ping1 = nock('http://rpc.pingomatic.com').post('/').reply(200), - testPost = _.clone(testUtils.DataGenerator.Content.posts[2]); + const ping1 = nock('http://rpc.pingomatic.com').post('/').reply(200); + const testPost = _.clone(testUtils.DataGenerator.Content.posts[2]); ping(testPost); @@ -87,8 +91,8 @@ describe('XMLRPC', function () { }); it('with default post should not execute pings', function () { - var ping1 = nock('http://rpc.pingomatic.com').post('/').reply(200), - testPost = _.clone(testUtils.DataGenerator.Content.posts[2]); + const ping1 = nock('http://rpc.pingomatic.com').post('/').reply(200); + const testPost = _.clone(testUtils.DataGenerator.Content.posts[2]); testPost.slug = 'welcome'; @@ -98,8 +102,8 @@ describe('XMLRPC', function () { }); it('with a page should not execute pings', function () { - var ping1 = nock('http://rpc.pingomatic.com').post('/').reply(200), - testPage = _.clone(testUtils.DataGenerator.Content.posts[5]); + const ping1 = nock('http://rpc.pingomatic.com').post('/').reply(200); + const testPage = _.clone(testUtils.DataGenerator.Content.posts[5]); ping(testPage); @@ -107,8 +111,8 @@ describe('XMLRPC', function () { }); it('when privacy.useRpcPing is false should not execute pings', function () { - var ping1 = nock('http://rpc.pingomatic.com').post('/').reply(200), - testPost = _.clone(testUtils.DataGenerator.Content.posts[2]); + const ping1 = nock('http://rpc.pingomatic.com').post('/').reply(200); + const testPost = _.clone(testUtils.DataGenerator.Content.posts[2]); configUtils.set({privacy: {useRpcPing: false}}); @@ -118,9 +122,9 @@ describe('XMLRPC', function () { }); it('captures && logs errors from requests', function (done) { - var testPost = _.clone(testUtils.DataGenerator.Content.posts[2]), - ping1 = nock('http://rpc.pingomatic.com').post('/').reply(400), - loggingStub = sinon.stub(common.logging, 'error'); + const testPost = _.clone(testUtils.DataGenerator.Content.posts[2]); + const ping1 = nock('http://rpc.pingomatic.com').post('/').reply(400); + const loggingStub = sinon.stub(common.logging, 'error'); ping(testPost); @@ -136,32 +140,34 @@ describe('XMLRPC', function () { }); it('captures && logs XML errors from requests with newlines between tags', function (done) { - var testPost = _.clone(testUtils.DataGenerator.Content.posts[2]), - ping1 = nock('http://rpc.pingomatic.com').post('/').reply(200, - ` - - - - - - - flerror - - 1 - - - - message - - Uh oh. A wee lil error. - - - - - - - `), - loggingStub = sinon.stub(common.logging, 'error'); + const testPost = _.clone(testUtils.DataGenerator.Content.posts[2]); + + const ping1 = nock('http://rpc.pingomatic.com').post('/').reply(200, + ` + + + + + + + flerror + + 1 + + + + message + + Uh oh. A wee lil error. + + + + + + + `); + + const loggingStub = sinon.stub(common.logging, 'error'); ping(testPost); @@ -177,32 +183,34 @@ describe('XMLRPC', function () { }); it('captures && logs XML errors from requests without newlines between tags', function (done) { - var testPost = _.clone(testUtils.DataGenerator.Content.posts[2]), - ping1 = nock('http://rpc.pingomatic.com').post('/').reply(200, - (` - - - - - - - flerror - - 1 - - - - message - - Uh oh. A wee lil error. - - - - - - - `).replace('\n', '')), - loggingStub = sinon.stub(common.logging, 'error'); + const testPost = _.clone(testUtils.DataGenerator.Content.posts[2]); + + const ping1 = nock('http://rpc.pingomatic.com').post('/').reply(200, + (` + + + + + + + flerror + + 1 + + + + message + + Uh oh. A wee lil error. + + + + + + + `).replace('\n', '')); + + const loggingStub = sinon.stub(common.logging, 'error'); ping(testPost); @@ -218,22 +226,24 @@ describe('XMLRPC', function () { }); it('does not error with responses that have 0 as flerror value', function (done) { - var testPost = _.clone(testUtils.DataGenerator.Content.posts[2]), - ping1 = nock('http://rpc.pingomatic.com').post('/').reply(200, - ` - - - - - - flerror0 - messagePings being forwarded to 9 services! - - - - - `), - loggingStub = sinon.stub(common.logging, 'error'); + const testPost = _.clone(testUtils.DataGenerator.Content.posts[2]); + + const ping1 = nock('http://rpc.pingomatic.com').post('/').reply(200, + ` + + + + + + flerror0 + messagePings being forwarded to 9 services! + + + + + `); + + const loggingStub = sinon.stub(common.logging, 'error'); ping(testPost); diff --git a/test/unit/web/admin/middleware_spec.js b/test/unit/web/admin/middleware_spec.js index 5b352b46e9..05990235dd 100644 --- a/test/unit/web/admin/middleware_spec.js +++ b/test/unit/web/admin/middleware_spec.js @@ -1,8 +1,8 @@ -var should = require('should'), - sinon = require('sinon'), +const should = require('should'); +const sinon = require('sinon'); - // Thing we are testing - redirectAdminUrls = require('../../../../core/server/web/admin/middleware')[0]; +// Thing we are testing +const redirectAdminUrls = require('../../../../core/server/web/admin/middleware')[0]; describe('Admin App', function () { afterEach(function () { @@ -11,7 +11,9 @@ describe('Admin App', function () { describe('middleware', function () { describe('redirectAdminUrls', function () { - var req, res, next; + let req; + let res; + let next; // Input: req.originalUrl // Output: either next or res.redirect are called beforeEach(function () { diff --git a/test/unit/web/api/middleware/cors_spec.js b/test/unit/web/api/middleware/cors_spec.js index 5b23612aef..d84ca08759 100644 --- a/test/unit/web/api/middleware/cors_spec.js +++ b/test/unit/web/api/middleware/cors_spec.js @@ -6,7 +6,9 @@ const urlUtils = require('../../../../utils/urlUtils'); let cors = rewire('../../../../../core/server/web/api/middleware/cors'); describe('cors', function () { - let res, req, next; + let res; + let req; + let next; beforeEach(function () { req = { diff --git a/test/unit/web/api/middleware/normalize-image_spec.js b/test/unit/web/api/middleware/normalize-image_spec.js index 44fbc3a915..eb15d3d0d0 100644 --- a/test/unit/web/api/middleware/normalize-image_spec.js +++ b/test/unit/web/api/middleware/normalize-image_spec.js @@ -6,7 +6,8 @@ const {logging} = require('../../../../../core/server/lib/common'); const normalize = require('../../../../../core/server/web/api/middleware/normalize-image'); describe('normalize', function () { - let res, req; + let res; + let req; beforeEach(function () { req = { diff --git a/test/unit/web/api/middleware/version-match_spec.js b/test/unit/web/api/middleware/version-match_spec.js index ecc98108d1..62797884c0 100644 --- a/test/unit/web/api/middleware/version-match_spec.js +++ b/test/unit/web/api/middleware/version-match_spec.js @@ -3,7 +3,10 @@ const sinon = require('sinon'); const versionMatch = require('../../../../../core/server/web/api/middleware/version-match'); describe('Version Mismatch', function () { - let req, res, getStub, nextStub; + let req; + let res; + let getStub; + let nextStub; afterEach(function () { sinon.restore(); diff --git a/test/unit/web/parent/middleware/ghost-locals_spec.js b/test/unit/web/parent/middleware/ghost-locals_spec.js index c3d4fbaab3..bbfa3aa190 100644 --- a/test/unit/web/parent/middleware/ghost-locals_spec.js +++ b/test/unit/web/parent/middleware/ghost-locals_spec.js @@ -4,7 +4,9 @@ const ghostLocals = require('../../../../../core/server/web/parent/middleware/gh const themeService = require('../../../../../core/frontend/services/themes'); describe('Theme Handler', function () { - let req, res, next; + let req; + let res; + let next; beforeEach(function () { req = sinon.spy(); diff --git a/test/unit/web/parent/middleware/request-id_spec.js b/test/unit/web/parent/middleware/request-id_spec.js index 73414aefd9..9b0a1418d3 100644 --- a/test/unit/web/parent/middleware/request-id_spec.js +++ b/test/unit/web/parent/middleware/request-id_spec.js @@ -5,7 +5,9 @@ const validator = require('validator'); const requestId = require('../../../../../core/server/web/parent/middleware/request-id'); describe('Request ID middleware', function () { - let res, req, next; + let res; + let req; + let next; beforeEach(function () { req = { diff --git a/test/unit/web/shared/middleware/uncapitalise_spec.js b/test/unit/web/shared/middleware/uncapitalise_spec.js index 06958caa9d..86889bb5a9 100644 --- a/test/unit/web/shared/middleware/uncapitalise_spec.js +++ b/test/unit/web/shared/middleware/uncapitalise_spec.js @@ -5,7 +5,9 @@ const uncapitalise = require('../../../../../core/server/web/shared/middlewares/ // NOTE: all urls will have had trailing slashes added before uncapitalise is called describe('Middleware: uncapitalise', function () { - let res, req, next; + let res; + let req; + let next; beforeEach(function () { res = { diff --git a/test/unit/web/shared/middleware/url-redirects_spec.js b/test/unit/web/shared/middleware/url-redirects_spec.js index 91ec4548b3..c6f2202725 100644 --- a/test/unit/web/shared/middleware/url-redirects_spec.js +++ b/test/unit/web/shared/middleware/url-redirects_spec.js @@ -9,7 +9,10 @@ const getFrontendRedirectUrl = urlRedirects.__get__('_private.getFrontendRedirec const redirect = urlRedirects.__get__('_private.redirect'); describe('UNIT: url redirects', function () { - let res, req, next, host; + let res; + let req; + let next; + let host; beforeEach(function () { req = { diff --git a/test/unit/web/site/middleware/serve-favicon_spec.js b/test/unit/web/site/middleware/serve-favicon_spec.js index baf798713a..d770b104e5 100644 --- a/test/unit/web/site/middleware/serve-favicon_spec.js +++ b/test/unit/web/site/middleware/serve-favicon_spec.js @@ -8,7 +8,12 @@ const configUtils = require('../../../../utils/configUtils'); const path = require('path'); describe('Serve Favicon', function () { - let req, res, next, blogApp, localSettingsCache = {}, originalStoragePath; + let req; + let res; + let next; + let blogApp; + let localSettingsCache = {}; + let originalStoragePath; beforeEach(function () { req = sinon.spy(); diff --git a/test/unit/web/site/middleware/serve-public-file_spec.js b/test/unit/web/site/middleware/serve-public-file_spec.js index 4eb03ed55c..ed03a5f788 100644 --- a/test/unit/web/site/middleware/serve-public-file_spec.js +++ b/test/unit/web/site/middleware/serve-public-file_spec.js @@ -4,7 +4,9 @@ const fs = require('fs-extra'); const servePublicFile = require('../../../../../core/server/web/site/middleware/serve-public-file'); describe('servePublicFile', function () { - let res, req, next; + let res; + let req; + let next; beforeEach(function () { res = sinon.spy(); @@ -30,8 +32,8 @@ describe('servePublicFile', function () { }); it('should load the file and send it', function () { - const middleware = servePublicFile('robots.txt', 'text/plain', 3600), - body = 'User-agent: * Disallow: /'; + const middleware = servePublicFile('robots.txt', 'text/plain', 3600); + const body = 'User-agent: * Disallow: /'; req.path = '/robots.txt'; sinon.stub(fs, 'readFile').callsFake(function (file, cb) { @@ -56,8 +58,8 @@ describe('servePublicFile', function () { }); it('should send the correct headers', function () { - const middleware = servePublicFile('robots.txt', 'text/plain', 3600), - body = 'User-agent: * Disallow: /'; + const middleware = servePublicFile('robots.txt', 'text/plain', 3600); + const body = 'User-agent: * Disallow: /'; req.path = '/robots.txt'; sinon.stub(fs, 'readFile').callsFake(function (file, cb) { @@ -80,8 +82,8 @@ describe('servePublicFile', function () { }); it('should replace {{blog-url}} in text/plain', function () { - const middleware = servePublicFile('robots.txt', 'text/plain', 3600), - body = 'User-agent: {{blog-url}}'; + const middleware = servePublicFile('robots.txt', 'text/plain', 3600); + const body = 'User-agent: {{blog-url}}'; req.path = '/robots.txt'; sinon.stub(fs, 'readFile').callsFake(function (file, cb) { diff --git a/test/unit/web/site/middleware/static-theme_spec.js b/test/unit/web/site/middleware/static-theme_spec.js index db5e8f19da..49c2dbe76f 100644 --- a/test/unit/web/site/middleware/static-theme_spec.js +++ b/test/unit/web/site/middleware/static-theme_spec.js @@ -6,7 +6,10 @@ const themeUtils = require('../../../../../core/frontend/services/themes'); const staticTheme = require('../../../../../core/server/web/site/middleware/static-theme'); describe('staticTheme', function () { - let expressStaticStub, activeThemeStub, req, res; + let expressStaticStub; + let activeThemeStub; + let req; + let res; beforeEach(function () { req = {}; diff --git a/test/utils/api.js b/test/utils/api.js index eb7f8698d0..e2c1455380 100644 --- a/test/utils/api.js +++ b/test/utils/api.js @@ -27,9 +27,9 @@ function isISO8601(date) { // make sure the API only returns expected properties only function checkResponseValue(jsonResponse, expectedProperties) { - var providedProperties = _.keys(jsonResponse), - missing = _.difference(expectedProperties, providedProperties), - unexpected = _.difference(providedProperties, expectedProperties); + const providedProperties = _.keys(jsonResponse); + const missing = _.difference(expectedProperties, providedProperties); + const unexpected = _.difference(providedProperties, expectedProperties); _.each(missing, function (prop) { jsonResponse.should.have.property(prop); diff --git a/test/utils/assertions.js b/test/utils/assertions.js index 290e48bf6b..b2d0ad6f99 100644 --- a/test/utils/assertions.js +++ b/test/utils/assertions.js @@ -1,5 +1,5 @@ -var should = require('should'), - errorProps = ['message', 'errorType']; +const should = require('should'); +const errorProps = ['message', 'errorType']; should.Assertion.add('JSONErrorObject', function () { this.params = {operator: 'to be a valid JSON Error Object'}; diff --git a/test/utils/configUtils.js b/test/utils/configUtils.js index 8206f7e956..ac8514febf 100644 --- a/test/utils/configUtils.js +++ b/test/utils/configUtils.js @@ -1,6 +1,6 @@ -var _ = require('lodash'), - config = require('../../core/server/config'), - configUtils = {}; +const _ = require('lodash'); +const config = require('../../core/server/config'); +const configUtils = {}; configUtils.config = config; configUtils.defaultConfig = _.cloneDeep(config.get()); @@ -10,8 +10,8 @@ configUtils.defaultConfig = _.cloneDeep(config.get()); * configUtils.set('key', 'value'); */ configUtils.set = function () { - var key = arguments[0], - value = arguments[1]; + const key = arguments[0]; + const value = arguments[1]; if (_.isObject(key)) { _.each(key, function (value, key) { diff --git a/test/utils/fixtures/data-generator.js b/test/utils/fixtures/data-generator.js index 0fe2f72dc3..0989b3a8e8 100644 --- a/test/utils/fixtures/data-generator.js +++ b/test/utils/fixtures/data-generator.js @@ -1,12 +1,12 @@ -var _ = require('lodash'), - uuid = require('uuid'), - ObjectId = require('bson-objectid'), - moment = require('moment'), - constants = require('../../../core/server/lib/constants'), - DataGenerator = {}; +const _ = require('lodash'); +const uuid = require('uuid'); +const ObjectId = require('bson-objectid'); +const moment = require('moment'); +const constants = require('../../../core/server/lib/constants'); +const DataGenerator = {}; DataGenerator.markdownToMobiledoc = function markdownToMobiledoc(content) { - var mobiledoc = { + const mobiledoc = { version: '0.3.1', markups: [], atoms: [], @@ -401,7 +401,7 @@ DataGenerator.Content.emails[1].post_id = DataGenerator.Content.posts[1].id; DataGenerator.forKnex = (function () { function createBasic(overrides) { - var newObj = _.cloneDeep(overrides); + const newObj = _.cloneDeep(overrides); return _.defaults(newObj, { id: ObjectId.generate(), @@ -413,7 +413,7 @@ DataGenerator.forKnex = (function () { } function createTag(overrides) { - var newObj = _.cloneDeep(overrides); + const newObj = _.cloneDeep(overrides); return _.defaults(newObj, { id: ObjectId.generate(), @@ -434,8 +434,8 @@ DataGenerator.forKnex = (function () { function createPost(overrides) { overrides = overrides || {}; - var newObj = _.cloneDeep(overrides), - mobiledocObj; + const newObj = _.cloneDeep(overrides); + let mobiledocObj; if (!newObj.mobiledoc) { newObj.mobiledoc = DataGenerator.markdownToMobiledoc('## markdown'); @@ -485,7 +485,7 @@ DataGenerator.forKnex = (function () { } function createUser(overrides) { - var newObj = _.cloneDeep(overrides || {}); + const newObj = _.cloneDeep(overrides || {}); if (!newObj.slug) { newObj.slug = 'slug_' + Date.now(); @@ -515,8 +515,8 @@ DataGenerator.forKnex = (function () { function createClient(overrides) { overrides = overrides || {}; - var newObj = _.cloneDeep(overrides), - basics = createBasic(newObj); + const newObj = _.cloneDeep(overrides); + const basics = createBasic(newObj); return _.defaults(newObj, { id: ObjectId.generate(), @@ -591,7 +591,7 @@ DataGenerator.forKnex = (function () { } function createToken(overrides) { - var newObj = _.cloneDeep(overrides); + const newObj = _.cloneDeep(overrides); return _.defaults(newObj, { id: ObjectId.generate(), @@ -601,7 +601,7 @@ DataGenerator.forKnex = (function () { } function createInvite(overrides) { - var newObj = _.cloneDeep(overrides); + const newObj = _.cloneDeep(overrides); return _.defaults(newObj, { id: ObjectId.generate(), @@ -616,7 +616,7 @@ DataGenerator.forKnex = (function () { } function createWebhook(overrides) { - var newObj = _.cloneDeep(overrides); + const newObj = _.cloneDeep(overrides); return _.defaults(newObj, { id: ObjectId.generate(), @@ -630,7 +630,7 @@ DataGenerator.forKnex = (function () { } function createIntegration(overrides) { - var newObj = _.cloneDeep(overrides); + const newObj = _.cloneDeep(overrides); return _.defaults(newObj, { id: ObjectId.generate(), @@ -874,10 +874,10 @@ DataGenerator.forKnex = (function () { // @TODO: this logic only exists because we are now using our models :/ DataGenerator.forModel = (function () { - var posts, - tags, - users, - roles; + let posts; + let tags; + let users; + let roles; posts = _.map(DataGenerator.Content.posts, function (post) { return _.pick(post, 'title', 'mobiledoc'); diff --git a/test/utils/fixtures/filter-param/index.js b/test/utils/fixtures/filter-param/index.js index cd221ca9ad..29a6a62015 100644 --- a/test/utils/fixtures/filter-param/index.js +++ b/test/utils/fixtures/filter-param/index.js @@ -1,11 +1,12 @@ /** * These fixtures are just for testing the filter spec */ -var _ = require('lodash'), - ObjectId = require('bson-objectid'), - db = require('../../../../core/server/data/db'), - markdownToMobiledoc = require('../data-generator').markdownToMobiledoc, - data = {}; +const _ = require('lodash'); + +const ObjectId = require('bson-objectid'); +const db = require('../../../../core/server/data/db'); +const markdownToMobiledoc = require('../data-generator').markdownToMobiledoc; +const data = {}; // Password = Sl1m3rson data.users = [ @@ -279,7 +280,7 @@ data.posts = [ ]; function fixDataIndexes(origData, storedData) { - var indexedData = {}; + const indexedData = {}; _.each(origData, function (orig, index) { indexedData[index + 1] = _.find(storedData, function (stored) { return stored.slug === orig.slug; @@ -317,7 +318,8 @@ function createTags(knex, DataGenerator) { } function createPosts(knex, DataGenerator) { - var postsTags = [], postsAuthors = []; + const postsTags = []; + const postsAuthors = []; data.posts = _.map(data.posts, function (post) { post = DataGenerator.forKnex.createPost(post); @@ -353,7 +355,7 @@ function createPosts(knex, DataGenerator) { } module.exports = function (DataGenerator) { - var created = {}; + const created = {}; // Create users first return createUsers(db.knex, DataGenerator).then(function () { // Next create tags diff --git a/test/utils/fixtures/themes/casper/gulpfile.js b/test/utils/fixtures/themes/casper/gulpfile.js index 73024d048a..311b002a9f 100644 --- a/test/utils/fixtures/themes/casper/gulpfile.js +++ b/test/utils/fixtures/themes/casper/gulpfile.js @@ -1,26 +1,26 @@ -var gulp = require('gulp'); +const gulp = require('gulp'); // gulp plugins and utils -var gutil = require('gulp-util'); -var livereload = require('gulp-livereload'); -var postcss = require('gulp-postcss'); -var sourcemaps = require('gulp-sourcemaps'); -var zip = require('gulp-zip'); +const gutil = require('gulp-util'); +const livereload = require('gulp-livereload'); +const postcss = require('gulp-postcss'); +const sourcemaps = require('gulp-sourcemaps'); +const zip = require('gulp-zip'); // postcss plugins -var autoprefixer = require('autoprefixer'); -var colorFunction = require('postcss-color-function'); -var cssnano = require('cssnano'); -var customProperties = require('postcss-custom-properties'); -var easyimport = require('postcss-easy-import'); +const autoprefixer = require('autoprefixer'); +const colorFunction = require('postcss-color-function'); +const cssnano = require('cssnano'); +const customProperties = require('postcss-custom-properties'); +const easyimport = require('postcss-easy-import'); -var swallowError = function swallowError(error) { +const swallowError = function swallowError(error) { gutil.log(error.toString()); gutil.beep(); this.emit('end'); }; -var nodemonServerInit = function () { +const nodemonServerInit = function () { livereload.listen(1234); }; @@ -29,7 +29,7 @@ gulp.task('build', ['css'], function (/* cb */) { }); gulp.task('css', function () { - var processors = [ + const processors = [ easyimport, customProperties, colorFunction(), @@ -51,9 +51,9 @@ gulp.task('watch', function () { }); gulp.task('zip', ['css'], function () { - var targetDir = 'dist/'; - var themeName = require('./package.json').name; - var filename = themeName + '.zip'; + const targetDir = 'dist/'; + const themeName = require('./package.json').name; + const filename = themeName + '.zip'; return gulp.src([ '**', diff --git a/test/utils/index.js b/test/utils/index.js index 0f2885e3f2..24f96d20f7 100644 --- a/test/utils/index.js +++ b/test/utils/index.js @@ -1,55 +1,53 @@ -var Promise = require('bluebird'), - _ = require('lodash'), - fs = require('fs-extra'), - path = require('path'), - os = require('os'), - express = require('express'), - debug = require('ghost-ignition').debug('test'), - ObjectId = require('bson-objectid'), - uuid = require('uuid'), - KnexMigrator = require('knex-migrator'), - ghost = require('../../core/server'), - GhostServer = require('../../core/server/ghost-server'), - common = require('../../core/server/lib/common'), - fixtureUtils = require('../../core/server/data/schema/fixtures/utils'), - db = require('../../core/server/data/db'), - schema = require('../../core/server/data/schema').tables, - schemaTables = Object.keys(schema), - models = require('../../core/server/models'), - urlUtils = require('../../core/server/lib/url-utils'), - urlService = require('../../core/frontend/services/url'), - routingService = require('../../core/frontend/services/routing'), - settingsService = require('../../core/server/services/settings'), - frontendSettingsService = require('../../core/frontend/services/settings'), - settingsCache = require('../../core/server/services/settings/cache'), - imageLib = require('../../core/server/lib/image'), - web = require('../../core/server/web'), - permissions = require('../../core/server/services/permissions'), - sequence = require('../../core/server/lib/promise/sequence'), - themes = require('../../core/frontend/services/themes'), - DataGenerator = require('./fixtures/data-generator'), - configUtils = require('./configUtils'), - filterData = require('./fixtures/filter-param'), - APIUtils = require('./api'), - config = require('../../core/server/config'), - knexMigrator = new KnexMigrator(), - fixtures, - getFixtureOps, - toDoList, - originalRequireFn, - postsInserted = 0, - - teardownDb, - setup, - truncate, - createUser, - createPost, - startGhost, - - initFixtures, - initData, - clearData, - clearBruteData; +const Promise = require('bluebird'); +const _ = require('lodash'); +const fs = require('fs-extra'); +const path = require('path'); +const os = require('os'); +const express = require('express'); +const debug = require('ghost-ignition').debug('test'); +const ObjectId = require('bson-objectid'); +const uuid = require('uuid'); +const KnexMigrator = require('knex-migrator'); +const ghost = require('../../core/server'); +const GhostServer = require('../../core/server/ghost-server'); +const common = require('../../core/server/lib/common'); +const fixtureUtils = require('../../core/server/data/schema/fixtures/utils'); +const db = require('../../core/server/data/db'); +const schema = require('../../core/server/data/schema').tables; +const schemaTables = Object.keys(schema); +const models = require('../../core/server/models'); +const urlUtils = require('../../core/server/lib/url-utils'); +const urlService = require('../../core/frontend/services/url'); +const routingService = require('../../core/frontend/services/routing'); +const settingsService = require('../../core/server/services/settings'); +const frontendSettingsService = require('../../core/frontend/services/settings'); +const settingsCache = require('../../core/server/services/settings/cache'); +const imageLib = require('../../core/server/lib/image'); +const web = require('../../core/server/web'); +const permissions = require('../../core/server/services/permissions'); +const sequence = require('../../core/server/lib/promise/sequence'); +const themes = require('../../core/frontend/services/themes'); +const DataGenerator = require('./fixtures/data-generator'); +const configUtils = require('./configUtils'); +const filterData = require('./fixtures/filter-param'); +const APIUtils = require('./api'); +const config = require('../../core/server/config'); +const knexMigrator = new KnexMigrator(); +let fixtures; +let getFixtureOps; +let toDoList; +let originalRequireFn; +let postsInserted = 0; +let teardownDb; +let setup; +let truncate; +let createUser; +let createPost; +let startGhost; +let initFixtures; +let initData; +let clearData; +let clearBruteData; // Require additional assertions which help us keep our tests small and clear require('./assertions'); @@ -86,8 +84,10 @@ fixtures = { }, insertMultiAuthorPosts: function insertMultiAuthorPosts() { - let i, j, k = 0, - posts = []; + let i; + let j; + let k = 0; + let posts = []; // NOTE: this variable should become a parameter as test logic depends on it const count = 10; @@ -103,8 +103,8 @@ fixtures = { models.Tag.fetchAll(_.merge({columns: ['id']}, module.exports.context.internal)) ]); }).then(function (results) { - let users = results[0], - tags = results[1]; + let users = results[0]; + let tags = results[1]; tags = tags.toJSON(); @@ -127,10 +127,12 @@ fixtures = { }, insertExtraPosts: function insertExtraPosts(max) { - var lang, - status, - posts = [], - i, j, k = postsInserted; + let lang; + let status; + const posts = []; + let i; + let j; + let k = postsInserted; max = max || 50; @@ -166,9 +168,9 @@ fixtures = { insertExtraTags: function insertExtraTags(max) { max = max || 50; - var tags = [], - tagName, - i; + const tags = []; + let tagName; + let i; for (i = 0; i < max; i += 1) { tagName = uuid.v4().split('-')[0]; @@ -216,7 +218,7 @@ fixtures = { }, initOwnerUser: function initOwnerUser() { - var user = DataGenerator.Content.users[0]; + let user = DataGenerator.Content.users[0]; user = DataGenerator.forKnex.createBasic(user); user = _.extend({}, user, {status: 'inactive'}); @@ -239,7 +241,7 @@ fixtures = { overrideOwnerUser: function overrideOwnerUser(slug) { return models.User.getOwnerUser(module.exports.context.internal) .then(function (ownerUser) { - var user = DataGenerator.forKnex.createUser(DataGenerator.Content.users[0]); + const user = DataGenerator.forKnex.createUser(DataGenerator.Content.users[0]); if (slug) { user.slug = slug; @@ -287,7 +289,7 @@ fixtures = { }, createUsersWithoutOwner: function createUsersWithoutOwner() { - var usersWithoutOwner = _.cloneDeep(DataGenerator.forKnex.users.slice(1)); + const usersWithoutOwner = _.cloneDeep(DataGenerator.forKnex.users.slice(1)); return Promise.map(usersWithoutOwner, function (user) { let userRolesRelations = _.filter(DataGenerator.forKnex.roles_users, {user_id: user.id}); @@ -313,7 +315,7 @@ fixtures = { createExtraUsers: function createExtraUsers() { // grab 3 more users - var extraUsers = _.cloneDeep(DataGenerator.Content.users.slice(2, 6)); + let extraUsers = _.cloneDeep(DataGenerator.Content.users.slice(2, 6)); extraUsers = _.map(extraUsers, function (user) { return DataGenerator.forKnex.createUser(_.extend({}, user, { id: ObjectId.generate(), @@ -360,15 +362,15 @@ fixtures = { }, getExportFixturePath: function (filename) { - var relativePath = '/fixtures/export/'; + const relativePath = '/fixtures/export/'; return path.resolve(__dirname + relativePath + filename + '.json'); }, loadExportFixture: function loadExportFixture(filename) { - var filePath = this.getExportFixturePath(filename); + const filePath = this.getExportFixturePath(filename); return fs.readFile(filePath).then(function (fileContents) { - var data; + let data; // Parse the json data try { @@ -382,18 +384,19 @@ fixtures = { }, permissionsFor: function permissionsFor(obj) { - var permsToInsert = _.cloneDeep(fixtureUtils.findModelFixtures('Permission', {object_type: obj}).entries), - permsRolesToInsert = fixtureUtils.findPermissionRelationsForObject(obj).entries, - actions = [], - permissionsRoles = {}, - roles = { - Administrator: DataGenerator.Content.roles[0].id, - Editor: DataGenerator.Content.roles[1].id, - Author: DataGenerator.Content.roles[2].id, - Owner: DataGenerator.Content.roles[3].id, - Contributor: DataGenerator.Content.roles[4].id, - 'Admin Integration': DataGenerator.Content.roles[5].id - }; + let permsToInsert = _.cloneDeep(fixtureUtils.findModelFixtures('Permission', {object_type: obj}).entries); + const permsRolesToInsert = fixtureUtils.findPermissionRelationsForObject(obj).entries; + const actions = []; + const permissionsRoles = {}; + + const roles = { + Administrator: DataGenerator.Content.roles[0].id, + Editor: DataGenerator.Content.roles[1].id, + Author: DataGenerator.Content.roles[2].id, + Owner: DataGenerator.Content.roles[3].id, + Contributor: DataGenerator.Content.roles[4].id, + 'Admin Integration': DataGenerator.Content.roles[5].id + }; // CASE: if empty db will throw SQLITE_MISUSE, hard to debug if (_.isEmpty(permsToInsert)) { @@ -614,8 +617,9 @@ toDoList = { */ getFixtureOps = function getFixtureOps(toDos) { // default = default fixtures, if it isn't present, init with tables only - var tablesOnly = !toDos.default, - fixtureOps = []; + const tablesOnly = !toDos.default; + + const fixtureOps = []; // Database initialisation if (toDos.init || toDos.default) { @@ -634,7 +638,7 @@ getFixtureOps = function getFixtureOps(toDos) { // Go through our list of things to do, and add them to an array _.each(toDos, function (value, toDo) { - var tmp; + let tmp; if ((toDo !== 'perms:init' && toDo.indexOf('perms:') !== -1)) { tmp = toDo.split(':'); @@ -657,10 +661,11 @@ getFixtureOps = function getFixtureOps(toDos) { // ## Test Setup and Teardown initFixtures = function initFixtures() { - var options = _.merge({init: true}, _.transform(arguments, function (result, val) { - result[val] = true; - })), - fixtureOps = getFixtureOps(options); + const options = _.merge({init: true}, _.transform(arguments, function (result, val) { + result[val] = true; + })); + + const fixtureOps = getFixtureOps(options); return sequence(fixtureOps); }; @@ -673,8 +678,9 @@ initFixtures = function initFixtures() { */ setup = function setup() { /*eslint no-invalid-this: "off"*/ - const self = this, - args = arguments; + const self = this; + + const args = arguments; return function setup() { models.init(); @@ -683,8 +689,8 @@ setup = function setup() { }; createUser = function createUser(options) { - var user = options.user, - role = options.role; + const user = options.user; + const role = options.role; return models.Role.fetchAll(module.exports.context.internal) .then(function (roles) { @@ -699,7 +705,7 @@ createUser = function createUser(options) { }; createPost = function createPost(options) { - var post = DataGenerator.forKnex.createPost(options.post); + const post = DataGenerator.forKnex.createPost(options.post); if (options.author) { post.author_id = options.author.id; @@ -717,7 +723,7 @@ teardownDb = function teardownDb() { debug('Database teardown'); urlService.softReset(); - var tables = schemaTables.concat(['migrations']); + const tables = schemaTables.concat(['migrations']); if (config.get('database:client') === 'sqlite3') { return Promise @@ -756,7 +762,7 @@ teardownDb = function teardownDb() { }); }; -var ghostServer; +let ghostServer; /** * 1. reset & init db @@ -775,8 +781,8 @@ startGhost = function startGhost(options) { subdir: false }, options); - var contentFolderForTests = options.contentFolder, - parentApp; + const contentFolderForTests = options.contentFolder; + let parentApp; /** * We never use the root content folder for testing! @@ -1065,19 +1071,20 @@ module.exports = { * templateOptions: hbs.updateTemplateOptions(...) */ createHbsResponse: function createHbsResponse(options) { - var renderObject = options.renderObject || {}, - templateOptions = options.templateOptions, - locals = options.locals || {}, - hbsStructure = { - data: { - site: {}, - config: {}, - labs: {}, - root: { - _locals: {} - } + const renderObject = options.renderObject || {}; + const templateOptions = options.templateOptions; + const locals = options.locals || {}; + + const hbsStructure = { + data: { + site: {}, + config: {}, + labs: {}, + root: { + _locals: {} } - }; + } + }; _.merge(hbsStructure.data, templateOptions); _.merge(hbsStructure.data.root, renderObject);