diff --git a/.eslintrc b/.eslintrc index e22f8a9618..1ef276fdb5 100644 --- a/.eslintrc +++ b/.eslintrc @@ -110,7 +110,6 @@ // WORKING ON "prefer-rest-params": "off", "prefer-spread": "off", - "prefer-arrow-callback": "off", "no-var": "off", "vars-on-top": "off", diff --git a/Gruntfile.js b/Gruntfile.js index bdf465d608..5d97280f84 100644 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -164,7 +164,7 @@ module.exports = function (grunt) { grunt.task.run('init'); grunt.event.removeAllListeners('watch'); - grunt.event.on('watch', function update(action, filepath, target) { + grunt.event.on('watch', (action, filepath, target) => { var compiling; if (target === 'styleUpdated_Client') { compiling = 'clientCSS'; @@ -183,7 +183,7 @@ module.exports = function (grunt) { return run(); } - require('./src/meta/build').build([compiling], function (err) { + require('./src/meta/build').build([compiling], (err) => { if (err) { winston.error(err.stack); } diff --git a/install/web.js b/install/web.js index cd500f104f..1329797498 100644 --- a/install/web.js +++ b/install/web.js @@ -72,7 +72,7 @@ web.install = async function (port) { winston.info(`Launching web installer on port ${port}`); app.use(express.static('public', {})); - app.engine('tpl', function (filepath, options, callback) { + app.engine('tpl', (filepath, options, callback) => { filepath = filepath.replace(/\.tpl$/, '.js'); Benchpress.__express(filepath, options, callback); @@ -99,7 +99,7 @@ web.install = async function (port) { function launchExpress(port) { - server = app.listen(port, function () { + server = app.listen(port, () => { winston.info('Web installer listening on http://%s:%s', '0.0.0.0', port); }); } @@ -118,10 +118,8 @@ function ping(req, res) { function welcome(req, res) { var dbs = ['redis', 'mongo', 'postgres']; - var databases = dbs.map(function (databaseName) { - var questions = require(`../src/database/${databaseName}`).questions.filter(function (question) { - return question && !question.hideOnWebInstall; - }); + var databases = dbs.map((databaseName) => { + var questions = require(`../src/database/${databaseName}`).questions.filter(question => question && !question.hideOnWebInstall); return { name: databaseName, @@ -180,7 +178,7 @@ function install(req, res) { env: setupEnvVars, }); - child.on('close', function (data) { + child.on('close', (data) => { installing = false; success = data === 0; error = data !== 0; diff --git a/loader.js b/loader.js index c6e35ac912..67c8743a88 100644 --- a/loader.js +++ b/loader.js @@ -60,14 +60,14 @@ Loader.displayStartupMessages = function (callback) { }; Loader.addWorkerEvents = function (worker) { - worker.on('exit', function (code, signal) { + worker.on('exit', (code, signal) => { if (code !== 0) { if (Loader.timesStarted < numProcs * 3) { Loader.timesStarted += 1; if (Loader.crashTimer) { clearTimeout(Loader.crashTimer); } - Loader.crashTimer = setTimeout(function () { + Loader.crashTimer = setTimeout(() => { Loader.timesStarted = 0; }, 10000); } else { @@ -84,7 +84,7 @@ Loader.addWorkerEvents = function (worker) { } }); - worker.on('message', function (message) { + worker.on('message', (message) => { if (message && typeof message === 'object' && message.action) { switch (message.action) { case 'restart': @@ -92,12 +92,12 @@ Loader.addWorkerEvents = function (worker) { Loader.restart(); break; case 'pubsub': - workers.forEach(function (w) { + workers.forEach((w) => { w.send(message); }); break; case 'socket.io': - workers.forEach(function (w) { + workers.forEach((w) => { if (w !== worker) { w.send(message); } @@ -172,7 +172,7 @@ Loader.restart = function () { nconf.remove('file'); nconf.use('file', { file: pathToConfig }); - fs.readFile(pathToConfig, { encoding: 'utf-8' }, function (err, configFile) { + fs.readFile(pathToConfig, { encoding: 'utf-8' }, (err, configFile) => { if (err) { console.error('Error reading config'); throw err; @@ -201,13 +201,13 @@ Loader.stop = function () { }; function killWorkers() { - workers.forEach(function (worker) { + workers.forEach((worker) => { worker.suicide = true; worker.kill(); }); } -fs.open(pathToConfig, 'r', function (err) { +fs.open(pathToConfig, 'r', (err) => { if (err) { // No config detected, kickstart web installer fork('app'); @@ -238,7 +238,7 @@ fs.open(pathToConfig, 'r', function (err) { Loader.init, Loader.displayStartupMessages, Loader.start, - ], function (err) { + ], (err) => { if (err) { console.error('[loader] Error during startup'); throw err; diff --git a/src/admin/search.js b/src/admin/search.js index 64dd6ab0e0..8cc0d3ab12 100644 --- a/src/admin/search.js +++ b/src/admin/search.js @@ -10,20 +10,22 @@ const file = require('../file'); const Translator = require('../translator').Translator; function filterDirectories(directories) { - return directories.map(function (dir) { + return directories.map( // get the relative path // convert dir to use forward slashes - return dir.replace(/^.*(admin.*?).tpl$/, '$1').split(path.sep).join('/'); - }).filter(function (dir) { + dir => dir.replace(/^.*(admin.*?).tpl$/, '$1').split(path.sep).join('/') + ).filter( // exclude .js files // exclude partials // only include subpaths // exclude category.tpl, group.tpl, category-analytics.tpl - return !dir.endsWith('.js') && + dir => ( + !dir.endsWith('.js') && !dir.includes('/partials/') && /\/.*\//.test(dir) && - !/manage\/(category|group|category-analytics)$/.test(dir); - }); + !/manage\/(category|group|category-analytics)$/.test(dir) + ) + ); } async function getAdminNamespaces() { @@ -50,9 +52,7 @@ function simplify(translations) { } function nsToTitle(namespace) { - return namespace.replace('admin/', '').split('/').map(function (str) { - return str[0].toUpperCase() + str.slice(1); - }).join(' > ') + return namespace.replace('admin/', '').split('/').map(str => str[0].toUpperCase() + str.slice(1)).join(' > ') .replace(/[^a-zA-Z> ]/g, ' '); } @@ -97,9 +97,7 @@ async function buildNamespace(language, namespace) { return await fallback(namespace); } // join all translations into one string separated by newlines - let str = Object.keys(translations).map(function (key) { - return translations[key]; - }).join('\n'); + let str = Object.keys(translations).map(key => translations[key]).join('\n'); str = sanitize(str); let title = namespace; diff --git a/src/admin/versions.js b/src/admin/versions.js index 3d1570704b..aeb3e7e21c 100644 --- a/src/admin/versions.js +++ b/src/admin/versions.js @@ -23,7 +23,7 @@ function getLatestVersion(callback) { json: true, headers: headers, timeout: 2000, - }, function (err, res, latestRelease) { + }, (err, res, latestRelease) => { if (err) { return callback(err); } diff --git a/src/analytics.js b/src/analytics.js index 068e54c743..3b3a995b34 100644 --- a/src/analytics.js +++ b/src/analytics.js @@ -33,9 +33,9 @@ Analytics.init = async function () { maxAge: 0, }); - new cronJob('*/10 * * * * *', function () { + new cronJob('*/10 * * * * *', (() => { Analytics.writeData(); - }, null, true); + }), null, true); }; Analytics.increment = function (keys, callback) { @@ -43,7 +43,7 @@ Analytics.increment = function (keys, callback) { plugins.hooks.fire('action:analytics.increment', { keys: keys }); - keys.forEach(function (key) { + keys.forEach((key) => { counters[key] = counters[key] || 0; counters[key] += 1; }); @@ -163,14 +163,14 @@ Analytics.getHourlyStatsForSet = async function (set, hour, numHours) { const counts = await db.sortedSetScores(set, hoursArr); - hoursArr.forEach(function (term, index) { + hoursArr.forEach((term, index) => { terms[term] = parseInt(counts[index], 10) || 0; }); const termsArr = []; hoursArr.reverse(); - hoursArr.forEach(function (hour) { + hoursArr.forEach((hour) => { termsArr.push(terms[hour]); }); diff --git a/src/api/helpers.js b/src/api/helpers.js index 9d50c2cbc6..c283449253 100644 --- a/src/api/helpers.js +++ b/src/api/helpers.js @@ -54,7 +54,7 @@ exports.doTopicAction = async function (action, event, caller, { tids }) { const uids = await user.getUidsFromSet('users:online', 0, -1); - await Promise.all(tids.map(async function (tid) { + await Promise.all(tids.map(async (tid) => { const title = await topics.getTopicField(tid, 'title'); const data = await topics.tools[action](tid, caller.uid); const notifyUids = await privileges.categories.filterUids('topics:read', data.cid, uids); diff --git a/src/cacheCreate.js b/src/cacheCreate.js index 98b60ff7f9..e3d7342165 100644 --- a/src/cacheCreate.js +++ b/src/cacheCreate.js @@ -55,11 +55,11 @@ module.exports = function (opts) { cache.misses = 0; } - pubsub.on(`${cache.name}:cache:reset`, function () { + pubsub.on(`${cache.name}:cache:reset`, () => { localReset(); }); - pubsub.on(`${cache.name}:cache:del`, function (keys) { + pubsub.on(`${cache.name}:cache:del`, (keys) => { if (Array.isArray(keys)) { keys.forEach(key => cacheDel.apply(cache, [key])); } @@ -71,7 +71,7 @@ module.exports = function (opts) { } let data; let isCached; - const unCachedKeys = keys.filter(function (key) { + const unCachedKeys = keys.filter((key) => { data = cache.get(key); isCached = data !== undefined; if (isCached) { diff --git a/src/categories/create.js b/src/categories/create.js index 2bb97ff267..2c2d78ca21 100644 --- a/src/categories/create.js +++ b/src/categories/create.js @@ -104,7 +104,7 @@ module.exports = function (Categories) { children = children[0]; - children.forEach(function (child) { + children.forEach((child) => { child.parentCid = parentCid; child.cloneFromCid = child.cid; child.cloneChildren = true; @@ -195,7 +195,7 @@ module.exports = function (Categories) { const currentMembers = await db.getSortedSetsMembers(toGroups.concat(fromGroups)); const copyGroups = _.uniq(_.flatten(currentMembers)); - await async.each(copyGroups, async function (group) { + await async.each(copyGroups, async (group) => { await copyPrivilegesByGroup(privileges, fromCid, toCid, group); }); } diff --git a/src/categories/delete.js b/src/categories/delete.js index 86061ad13c..080f90a308 100644 --- a/src/categories/delete.js +++ b/src/categories/delete.js @@ -11,14 +11,14 @@ var cache = require('../cache'); module.exports = function (Categories) { Categories.purge = async function (cid, uid) { - await batch.processSortedSet(`cid:${cid}:tids`, async function (tids) { - await async.eachLimit(tids, 10, async function (tid) { + await batch.processSortedSet(`cid:${cid}:tids`, async (tids) => { + await async.eachLimit(tids, 10, async (tid) => { await topics.purgePostsAndTopic(tid, uid); }); }, { alwaysStartAt: 0 }); const pinnedTids = await db.getSortedSetRevRange(`cid:${cid}:tids:pinned`, 0, -1); - await async.eachLimit(pinnedTids, 10, async function (tid) { + await async.eachLimit(pinnedTids, 10, async (tid) => { await topics.purgePostsAndTopic(tid, uid); }); const categoryData = await Categories.getCategoryData(cid); @@ -58,7 +58,7 @@ module.exports = function (Categories) { ]); const bulkAdd = []; - const childrenKeys = children.map(function (cid) { + const childrenKeys = children.map((cid) => { bulkAdd.push(['cid:0:children', cid, cid]); return `category:${cid}`; }); diff --git a/src/categories/index.js b/src/categories/index.js index 2779080084..9a87d5ebbb 100644 --- a/src/categories/index.js +++ b/src/categories/index.js @@ -97,7 +97,7 @@ Categories.getModerators = async function (cid) { }; Categories.getModeratorUids = async function (cids) { - const groupNames = cids.reduce(function (memo, cid) { + const groupNames = cids.reduce((memo, cid) => { memo.push(`cid:${cid}:privileges:moderate`); memo.push(`cid:${cid}:privileges:groups:moderate`); return memo; @@ -105,7 +105,7 @@ Categories.getModeratorUids = async function (cids) { const memberSets = await groups.getMembersOfGroups(groupNames); // Every other set is actually a list of user groups, not uids, so convert those to members - const sets = memberSets.reduce(function (memo, set, idx) { + const sets = memberSets.reduce((memo, set, idx) => { if (idx % 2) { memo.groupNames.push(set); } else { @@ -137,7 +137,7 @@ Categories.getCategories = async function (cids, uid) { Categories.getTagWhitelist(cids), Categories.hasReadCategories(cids, uid), ]); - categories.forEach(function (category, i) { + categories.forEach((category, i) => { if (category) { category.tagWhitelist = tagWhitelist[i]; category['unread-class'] = (category.topic_count === 0 || (hasRead[i] && uid !== 0)) ? '' : 'unread'; @@ -180,7 +180,7 @@ function calculateTopicPostCount(category) { let postCount = category.post_count; let topicCount = category.topic_count; if (Array.isArray(category.children)) { - category.children.forEach(function (child) { + category.children.forEach((child) => { calculateTopicPostCount(child); postCount += parseInt(child.totalPostCount, 10) || 0; topicCount += parseInt(child.totalTopicCount, 10) || 0; @@ -222,7 +222,7 @@ async function getChildrenTree(category, uid) { childrenData = childrenData.filter(Boolean); childrenCids = childrenData.map(child => child.cid); const hasRead = await Categories.hasReadCategories(childrenCids, uid); - childrenData.forEach(function (child, i) { + childrenData.forEach((child, i) => { child['unread-class'] = (child.topic_count === 0 || (hasRead[i] && uid !== 0)) ? '' : 'unread'; }); Categories.getTree([category].concat(childrenData), category.parentCid); @@ -270,7 +270,7 @@ Categories.getChildrenCids = async function (rootCid) { }; Categories.flattenCategories = function (allCategories, categoryData) { - categoryData.forEach(function (category) { + categoryData.forEach((category) => { if (category) { allCategories.push(category); @@ -302,7 +302,7 @@ Categories.getTree = function (categories, parentCid) { const tree = []; - categories.forEach(function (category) { + categories.forEach((category) => { if (category) { category.children = category.children || []; if (!category.cid) { diff --git a/src/categories/recentreplies.js b/src/categories/recentreplies.js index da4915ed23..93f2a283f1 100644 --- a/src/categories/recentreplies.js +++ b/src/categories/recentreplies.js @@ -95,7 +95,7 @@ module.exports = function (Categories) { tids, ['tid', 'mainPid', 'slug', 'title', 'teaserPid', 'cid', 'postcount'] ); - topicData.forEach(function (topic) { + topicData.forEach((topic) => { if (topic) { topic.teaserPid = topic.teaserPid || topic.mainPid; } @@ -108,7 +108,7 @@ module.exports = function (Categories) { ]); const cidToRoot = _.zipObject(cids, toRoot); - teasers.forEach(function (teaser, index) { + teasers.forEach((teaser, index) => { if (teaser) { teaser.cid = topicData[index].cid; teaser.parentCids = cidToRoot[teaser.cid]; @@ -124,7 +124,7 @@ module.exports = function (Categories) { } function assignTopicsToCategories(categories, topics) { - categories.forEach(function (category) { + categories.forEach((category) => { if (category) { category.posts = topics.filter(t => t.cid && (t.cid === category.cid || t.parentCids.includes(category.cid))) .sort((a, b) => b.pid - a.pid) @@ -135,7 +135,7 @@ module.exports = function (Categories) { } function bubbleUpChildrenPosts(categoryData) { - categoryData.forEach(function (category) { + categoryData.forEach((category) => { if (category) { if (category.posts.length) { return; @@ -168,7 +168,7 @@ module.exports = function (Categories) { topics.getTopicField(tid, 'deleted'), ]); - await batch.processArray(pids, async function (pids) { + await batch.processArray(pids, async (pids) => { const postData = await posts.getPostsFields(pids, ['pid', 'deleted', 'uid', 'timestamp', 'upvotes', 'downvotes']); const bulkRemove = []; diff --git a/src/categories/search.js b/src/categories/search.js index e878b2d9de..671d3775c2 100644 --- a/src/categories/search.js +++ b/src/categories/search.js @@ -41,16 +41,16 @@ module.exports = function (Categories) { Categories.getTree(categoryData, 0); await Categories.getRecentTopicReplies(categoryData, uid, data.qs); - categoryData.forEach(function (category) { + categoryData.forEach((category) => { if (category && Array.isArray(category.children)) { category.children = category.children.slice(0, category.subCategoriesPerPage); - category.children.forEach(function (child) { + category.children.forEach((child) => { child.children = undefined; }); } }); - categoryData.sort(function (c1, c2) { + categoryData.sort((c1, c2) => { if (c1.parentCid !== c2.parentCid) { return c1.parentCid - c2.parentCid; } diff --git a/src/categories/topics.js b/src/categories/topics.js index 221e25b7b8..c2253491f2 100644 --- a/src/categories/topics.js +++ b/src/categories/topics.js @@ -150,7 +150,7 @@ module.exports = function (Categories) { return; } - topics.forEach(function (topic) { + topics.forEach((topic) => { if (topic.deleted && !topic.isOwner) { topic.title = '[[topic:topic_is_deleted]]'; topic.slug = topic.tid; diff --git a/src/categories/update.js b/src/categories/update.js index 04de42b0fd..6c2f5c5e0d 100644 --- a/src/categories/update.js +++ b/src/categories/update.js @@ -37,7 +37,7 @@ module.exports = function (Categories) { fields.splice(0, 0, fields.splice(parentCidIndex, 1)[0]); } - await async.eachSeries(fields, async function (key) { + await async.eachSeries(fields, async (key) => { await updateCategoryField(cid, key, category[key]); }); plugins.hooks.fire('action:category.update', { cid: cid, modified: category }); diff --git a/src/cli/colors.js b/src/cli/colors.js index 5430e60e09..eeb00b8dab 100644 --- a/src/cli/colors.js +++ b/src/cli/colors.js @@ -61,9 +61,7 @@ function humanReadableArgName(arg) { } Command.prototype.usage = function () { - var args = this._args.map(function (arg) { - return humanReadableArgName(arg); - }); + var args = this._args.map(arg => humanReadableArgName(arg)); var usage = '[options]'[optionColor] + (this.commands.length ? ' [command]' : '')[subCommandColor] + @@ -82,12 +80,8 @@ Command.prototype.commandHelp = function () { return ''; } - var commands = this.commands.filter(function (cmd) { - return !cmd._noHelp; - }).map(function (cmd) { - var args = cmd._args.map(function (arg) { - return humanReadableArgName(arg); - }).join(' '); + var commands = this.commands.filter(cmd => !cmd._noHelp).map((cmd) => { + var args = cmd._args.map(arg => humanReadableArgName(arg)).join(' '); return [ `${cmd._name[subCommandColor] + @@ -98,15 +92,13 @@ Command.prototype.commandHelp = function () { ]; }); - var width = commands.reduce(function (max, command) { - return Math.max(max, command[0].length); - }, 0); + var width = commands.reduce((max, command) => Math.max(max, command[0].length), 0); return [ '', ' Commands:', '', - commands.map(function (cmd) { + commands.map((cmd) => { var desc = cmd[1] ? ` ${cmd[1]}` : ''; return pad(cmd[0], width) + desc; }).join('\n').replace(/^/gm, ' '), @@ -119,9 +111,7 @@ Command.prototype.optionHelp = function () { // Append the help information return this.options - .map(function (option) { - return `${pad(option.flags, width)[optionColor]} ${option.description}`; - }) + .map(option => `${pad(option.flags, width)[optionColor]} ${option.description}`) .concat([`${pad('-h, --help', width)[optionColor]} output usage information`]) .join('\n'); }; diff --git a/src/cli/index.js b/src/cli/index.js index 9d00c4d44c..f4c137b3bd 100644 --- a/src/cli/index.js +++ b/src/cli/index.js @@ -119,7 +119,7 @@ process.env.CONFIG = configFile; program .command('start') .description('Start the NodeBB server') - .action(function () { + .action(() => { require('./running').start(program); }); program @@ -127,7 +127,7 @@ program noHelp: true, }) .description('Start the NodeBB server and view the live output log') - .action(function () { + .action(() => { program.log = true; require('./running').start(program); }); @@ -136,7 +136,7 @@ program noHelp: true, }) .description('Start NodeBB in verbose development mode') - .action(function () { + .action(() => { program.dev = true; process.env.NODE_ENV = 'development'; global.env = 'development'; @@ -145,25 +145,25 @@ program program .command('stop') .description('Stop the NodeBB server') - .action(function () { + .action(() => { require('./running').stop(program); }); program .command('restart') .description('Restart the NodeBB server') - .action(function () { + .action(() => { require('./running').restart(program); }); program .command('status') .description('Check the running status of the NodeBB server') - .action(function () { + .action(() => { require('./running').status(program); }); program .command('log') .description('Open the output log (useful for debugging)') - .action(function () { + .action(() => { require('./running').log(program); }); @@ -172,7 +172,7 @@ program .command('setup [config]') .description('Run the NodeBB setup script, or setup with an initial config') .option('--skip-build', 'Run setup without building assets') - .action(function (initConfig) { + .action((initConfig) => { if (initConfig) { try { initConfig = JSON.parse(initConfig); @@ -189,41 +189,41 @@ program program .command('install') .description('Launch the NodeBB web installer for configuration setup') - .action(function () { + .action(() => { require('./setup').webInstall(); }); program .command('build [targets...]') .description(`Compile static assets ${'(JS, CSS, templates, languages)'.red}`) .option('-s, --series', 'Run builds in series without extra processes') - .action(function (targets, options) { + .action((targets, options) => { require('./manage').build(targets.length ? targets : true, options); }) - .on('--help', function () { + .on('--help', () => { require('../meta/aliases').buildTargets(); }); program .command('activate [plugin]') .description('Activate a plugin for the next startup of NodeBB (nodebb-plugin- prefix is optional)') - .action(function (plugin) { + .action((plugin) => { require('./manage').activate(plugin); }); program .command('plugins') - .action(function () { + .action(() => { require('./manage').listPlugins(); }) .description('List all installed plugins'); program .command('events [count]') .description('Outputs the most recent administrative events recorded by NodeBB') - .action(function (count) { + .action((count) => { require('./manage').listEvents(count); }); program .command('info') .description('Outputs various system info') - .action(function () { + .action(() => { require('./manage').info(); }); @@ -237,16 +237,14 @@ resetCommand .option('-w, --widgets', 'Disable all widgets') .option('-s, --settings', 'Reset settings to their default values') .option('-a, --all', 'All of the above') - .action(function (options) { - const valid = ['theme', 'plugin', 'widgets', 'settings', 'all'].some(function (x) { - return options[x]; - }); + .action((options) => { + const valid = ['theme', 'plugin', 'widgets', 'settings', 'all'].some(x => options[x]); if (!valid) { console.warn('\n No valid options passed in, so nothing was reset.'.red); resetCommand.help(); } - require('./reset').reset(options, function (err) { + require('./reset').reset(options, (err) => { if (err) { return process.exit(1); } @@ -264,7 +262,7 @@ program .option('-p, --plugins', 'Check installed plugins for updates', false) .option('-s, --schema', 'Update NodeBB data store schema', false) .option('-b, --build', 'Rebuild assets', false) - .on('--help', function () { + .on('--help', () => { console.log(`\n${[ 'When running particular upgrade scripts, options are ignored.', 'By default all options are enabled. Passing any options disables that default.', @@ -272,7 +270,7 @@ program `Only database update: ${'./nodebb upgrade -s'.yellow}`, ].join('\n')}`); }) - .action(function (scripts, options) { + .action((scripts, options) => { require('./upgrade').upgrade(scripts.length ? scripts : true, options); }); @@ -282,8 +280,8 @@ program }) .alias('upgradePlugins') .description('Upgrade plugins') - .action(function () { - require('./upgrade-plugins').upgradePlugins(function (err) { + .action(() => { + require('./upgrade-plugins').upgradePlugins((err) => { if (err) { throw err; } @@ -295,12 +293,12 @@ program program .command('help [command]') .description('Display help for [command]') - .action(function (name) { + .action((name) => { if (!name) { return program.help(); } - const command = program.commands.find(function (command) { return command._name === name; }); + const command = program.commands.find(command => command._name === name); if (command) { command.help(); } else { diff --git a/src/cli/manage.js b/src/cli/manage.js index a03c3c91ff..cb12f6aa10 100644 --- a/src/cli/manage.js +++ b/src/cli/manage.js @@ -86,7 +86,7 @@ async function listEvents(count) { await db.init(); const eventData = await events.getEvents('', 0, (count || 10) - 1); console.log((`\nDisplaying last ${count} administrative events...`).bold); - eventData.forEach(function (event) { + eventData.forEach((event) => { console.log(` * ${String(event.timestampISO).green} ${String(event.type).yellow}${event.text ? ` ${event.text}` : ''}${' (uid: '.reset}${event.uid ? event.uid : 0})`); }); process.exit(); @@ -132,7 +132,7 @@ async function info() { const min = Math.min(...analyticsData); const max = Math.max(...analyticsData); - analyticsData.forEach(function (point, idx) { + analyticsData.forEach((point, idx) => { graph.addPoint(idx + 1, Math.round(point / max * 10)); }); diff --git a/src/cli/package-install.js b/src/cli/package-install.js index 521763c075..4f391c18c1 100644 --- a/src/cli/package-install.js +++ b/src/cli/package-install.js @@ -99,14 +99,14 @@ function preserveExtraneousPlugins() { const extraneous = packages // only extraneous plugins (ones not in package.json) which are not links - .filter(function (pkgName) { + .filter((pkgName) => { const extraneous = !packageContents.dependencies.hasOwnProperty(pkgName); const isLink = fs.lstatSync(path.join(paths.nodeModules, pkgName)).isSymbolicLink(); return extraneous && !isLink; }) // reduce to a map of package names to package versions - .reduce(function (map, pkgName) { + .reduce((map, pkgName) => { const pkgConfig = JSON.parse(fs.readFileSync(path.join(paths.nodeModules, pkgName, 'package.json'), 'utf8')); map[pkgName] = pkgConfig.version; return map; diff --git a/src/cli/running.js b/src/cli/running.js index 47dd180858..ac81f998fe 100644 --- a/src/cli/running.js +++ b/src/cli/running.js @@ -11,7 +11,7 @@ const cwd = paths.baseDir; function getRunningPid(callback) { fs.readFile(paths.pidfile, { encoding: 'utf-8', - }, function (err, pid) { + }, (err, pid) => { if (err) { return callback(err); } @@ -69,7 +69,7 @@ function start(options) { } function stop() { - getRunningPid(function (err, pid) { + getRunningPid((err, pid) => { if (!err) { process.kill(pid, 'SIGTERM'); console.log('Stopping NodeBB. Goodbye!'); @@ -80,7 +80,7 @@ function stop() { } function restart(options) { - getRunningPid(function (err, pid) { + getRunningPid((err, pid) => { if (!err) { console.log('\nRestarting NodeBB'.bold); process.kill(pid, 'SIGTERM'); @@ -94,7 +94,7 @@ function restart(options) { } function status() { - getRunningPid(function (err, pid) { + getRunningPid((err, pid) => { if (!err) { console.log(`\n${[ 'NodeBB Running '.bold + (`(pid ${pid.toString()})`).cyan, diff --git a/src/cli/setup.js b/src/cli/setup.js index 7ec26a3f88..e0822b44e0 100644 --- a/src/cli/setup.js +++ b/src/cli/setup.js @@ -40,7 +40,7 @@ function setup(initConfig) { setImmediate(next); } }, - ], function (err, data) { + ], (err, data) => { // Disregard build step data data = data[0]; diff --git a/src/cli/upgrade-plugins.js b/src/cli/upgrade-plugins.js index f82584a4cd..8ec46f7a62 100644 --- a/src/cli/upgrade-plugins.js +++ b/src/cli/upgrade-plugins.js @@ -25,8 +25,8 @@ if (process.platform === 'win32') { function getModuleVersions(modules, callback) { const versionHash = {}; - async.eachLimit(modules, 50, function (module, next) { - fs.readFile(path.join(paths.nodeModules, module, 'package.json'), { encoding: 'utf-8' }, function (err, pkg) { + async.eachLimit(modules, 50, (module, next) => { + fs.readFile(path.join(paths.nodeModules, module, 'package.json'), { encoding: 'utf-8' }, (err, pkg) => { if (err) { return next(err); } @@ -39,7 +39,7 @@ function getModuleVersions(modules, callback) { next(err); } }); - }, function (err) { + }, (err) => { callback(err, versionHash); }); } @@ -49,14 +49,12 @@ function getInstalledPlugins(callback) { files: async.apply(fs.readdir, paths.nodeModules), deps: async.apply(fs.readFile, paths.currentPackage, { encoding: 'utf-8' }), bundled: async.apply(fs.readFile, paths.installPackage, { encoding: 'utf-8' }), - }, function (err, payload) { + }, (err, payload) => { if (err) { return callback(err); } - payload.files = payload.files.filter(function (file) { - return pluginNamePattern.test(file); - }); + payload.files = payload.files.filter(file => pluginNamePattern.test(file)); try { payload.deps = Object.keys(JSON.parse(payload.deps).dependencies); @@ -65,15 +63,11 @@ function getInstalledPlugins(callback) { return callback(err); } - payload.bundled = payload.bundled.filter(function (pkgName) { - return pluginNamePattern.test(pkgName); - }); - payload.deps = payload.deps.filter(function (pkgName) { - return pluginNamePattern.test(pkgName); - }); + payload.bundled = payload.bundled.filter(pkgName => pluginNamePattern.test(pkgName)); + payload.deps = payload.deps.filter(pkgName => pluginNamePattern.test(pkgName)); // Whittle down deps to send back only extraneously installed plugins/themes/etc - const checklist = payload.deps.filter(function (pkgName) { + const checklist = payload.deps.filter((pkgName) => { if (payload.bundled.includes(pkgName)) { return false; } @@ -92,7 +86,7 @@ function getInstalledPlugins(callback) { } function getCurrentVersion(callback) { - fs.readFile(paths.installPackage, { encoding: 'utf-8' }, function (err, pkg) { + fs.readFile(paths.installPackage, { encoding: 'utf-8' }, (err, pkg) => { if (err) { return callback(err); } @@ -128,7 +122,7 @@ function checkPlugins(standalone, callback) { method: 'GET', url: `https://packages.nodebb.org/api/v1/suggest?version=${payload.version}&package[]=${toCheck.join('&package[]=')}`, json: true, - }, function (err, res, body) { + }, (err, res, body) => { if (err) { process.stdout.write('error'.red + ''.reset); return next(err); @@ -141,7 +135,7 @@ function checkPlugins(standalone, callback) { let current; let suggested; - const upgradable = body.map(function (suggestObj) { + const upgradable = body.map((suggestObj) => { current = payload.plugins[suggestObj.package]; suggested = suggestObj.version; @@ -168,7 +162,7 @@ function upgradePlugins(callback) { standalone = true; } - checkPlugins(standalone, function (err, found) { + checkPlugins(standalone, (err, found) => { if (err) { console.log('Warning'.yellow + ': An unexpected error occured when attempting to verify plugin upgradability'.reset); return callback(err); @@ -176,7 +170,7 @@ function upgradePlugins(callback) { if (found && found.length) { process.stdout.write(`\n\nA total of ${String(found.length).bold} package(s) can be upgraded:\n\n`); - found.forEach(function (suggestObj) { + found.forEach((suggestObj) => { process.stdout.write(`${' * '.yellow + suggestObj.name.reset} (${suggestObj.current.yellow}${' -> '.reset}${suggestObj.suggested.green}${')\n'.reset}`); }); } else { @@ -194,18 +188,16 @@ function upgradePlugins(callback) { name: 'upgrade', description: '\nProceed with upgrade (y|n)?'.reset, type: 'string', - }, function (err, result) { + }, (err, result) => { if (err) { return callback(err); } if (['y', 'Y', 'yes', 'YES'].includes(result.upgrade)) { console.log('\nUpgrading packages...'); - const args = packageManagerInstallArgs.concat(found.map(function (suggestObj) { - return `${suggestObj.name}@${suggestObj.suggested}`; - })); + const args = packageManagerInstallArgs.concat(found.map(suggestObj => `${suggestObj.name}@${suggestObj.suggested}`)); - cproc.execFile(packageManagerExecutable, args, { stdio: 'ignore' }, function (err) { + cproc.execFile(packageManagerExecutable, args, { stdio: 'ignore' }, (err) => { callback(err, false); }); } else { diff --git a/src/cli/upgrade.js b/src/cli/upgrade.js index 6ad0ef36a3..28858ab537 100644 --- a/src/cli/upgrade.js +++ b/src/cli/upgrade.js @@ -53,17 +53,15 @@ var steps = { }; function runSteps(tasks) { - tasks = tasks.map(function (key, i) { - return function (next) { - process.stdout.write(`\n${(`${i + 1}. `).bold}${steps[key].message.yellow}`); - return steps[key].handler(function (err) { - if (err) { return next(err); } - next(); - }); - }; + tasks = tasks.map((key, i) => function (next) { + process.stdout.write(`\n${(`${i + 1}. `).bold}${steps[key].message.yellow}`); + return steps[key].handler((err) => { + if (err) { return next(err); } + next(); + }); }); - async.series(tasks, function (err) { + async.series(tasks, (err) => { if (err) { console.error(`Error occurred during upgrade: ${err.stack}`); throw err; @@ -90,9 +88,7 @@ function runUpgrade(upgrades, options) { var tasks = Object.keys(steps); if (options.package || options.install || options.plugins || options.schema || options.build) { - tasks = tasks.filter(function (key) { - return options[key]; - }); + tasks = tasks.filter(key => options[key]); } runSteps(tasks); return; @@ -104,7 +100,7 @@ function runUpgrade(upgrades, options) { async function () { await upgrade.runParticular(upgrades); }, - ], function (err) { + ], (err) => { if (err) { throw err; } diff --git a/src/controllers/accounts/categories.js b/src/controllers/accounts/categories.js index 347edc3e22..c752a377f7 100644 --- a/src/controllers/accounts/categories.js +++ b/src/controllers/accounts/categories.js @@ -26,7 +26,7 @@ categoriesController.get = async function (req, res, next) { const categoriesData = allCategoriesData.slice(start, stop + 1); - categoriesData.forEach(function (category) { + categoriesData.forEach((category) => { if (category) { category.isIgnored = states[category.cid] === categories.watchStates.ignoring; category.isWatched = states[category.cid] === categories.watchStates.watching; diff --git a/src/controllers/accounts/edit.js b/src/controllers/accounts/edit.js index d680cfcbb9..397d7c2aa3 100644 --- a/src/controllers/accounts/edit.js +++ b/src/controllers/accounts/edit.js @@ -49,7 +49,7 @@ editController.get = async function (req, res, next) { } return i1 - i2; }); - userData.groups.forEach(function (group) { + userData.groups.forEach((group) => { group.userTitle = group.userTitle || group.displayName; group.selected = userData.groupTitleArray.includes(group.name); }); diff --git a/src/controllers/accounts/groups.js b/src/controllers/accounts/groups.js index f86664b019..db9651e9fe 100644 --- a/src/controllers/accounts/groups.js +++ b/src/controllers/accounts/groups.js @@ -15,7 +15,7 @@ groupsController.get = async function (req, res, next) { groupsData = groupsData[0]; const groupNames = groupsData.filter(Boolean).map(group => group.name); const members = await groups.getMemberUsers(groupNames, 0, 3); - groupsData.forEach(function (group, index) { + groupsData.forEach((group, index) => { group.members = members[index]; }); userData.groups = groupsData; diff --git a/src/controllers/accounts/helpers.js b/src/controllers/accounts/helpers.js index 02611c6bac..94723980ec 100644 --- a/src/controllers/accounts/helpers.js +++ b/src/controllers/accounts/helpers.js @@ -231,7 +231,7 @@ async function parseAboutMe(userData) { } function filterLinks(links, states) { - return links.filter(function (link, index) { + return links.filter((link, index) => { // Default visibility link.visibility = { self: true, other: true, @@ -241,9 +241,7 @@ function filterLinks(links, states) { canViewInfo: true, ...link.visibility }; - var permit = Object.keys(states).some(function (state) { - return states[state] && link.visibility[state]; - }); + var permit = Object.keys(states).some(state => states[state] && link.visibility[state]); links[index].public = permit; return permit; diff --git a/src/controllers/accounts/notifications.js b/src/controllers/accounts/notifications.js index 2e1bb83833..2eed832c2d 100644 --- a/src/controllers/accounts/notifications.js +++ b/src/controllers/accounts/notifications.js @@ -44,7 +44,7 @@ notificationsController.get = async function (req, res, next) { { separator: true }, ]).concat(filters.moderatorFilters); } - const selectedFilter = allFilters.find(function (filterData) { + const selectedFilter = allFilters.find((filterData) => { filterData.selected = filterData.filter === filter; return filterData.selected; }); diff --git a/src/controllers/accounts/posts.js b/src/controllers/accounts/posts.js index daf7ffbf45..b8a1cbc1d0 100644 --- a/src/controllers/accounts/posts.js +++ b/src/controllers/accounts/posts.js @@ -178,7 +178,7 @@ async function getFromUserSet(template, req, res, callback) { { url: `${baseUrl}?sort=lastpost`, name: '[[global:lastpost]]' }, { url: `${baseUrl}?sort=firstpost`, name: '[[global:firstpost]]' }, ]; - userData.sortOptions.forEach(function (option) { + userData.sortOptions.forEach((option) => { option.selected = option.url.includes(`sort=${req.query.sort}`); }); diff --git a/src/controllers/accounts/settings.js b/src/controllers/accounts/settings.js index c09cb4c97a..e78ccc8158 100644 --- a/src/controllers/accounts/settings.js +++ b/src/controllers/accounts/settings.js @@ -76,16 +76,16 @@ settingsController.get = async function (req, res, next) { { name: 'Yeti', value: 'yeti' }, ]; - userData.bootswatchSkinOptions.forEach(function (skin) { + userData.bootswatchSkinOptions.forEach((skin) => { skin.selected = skin.value === userData.settings.bootswatchSkin; }); - userData.languages.forEach(function (language) { + userData.languages.forEach((language) => { language.selected = language.code === userData.settings.userLang; }); if (userData.isAdmin && userData.isSelf) { - userData.acpLanguages.forEach(function (language) { + userData.acpLanguages.forEach((language) => { language.selected = language.code === userData.settings.acpLang; }); } @@ -122,7 +122,7 @@ settingsController.get = async function (req, res, next) { }; const unsubscribable = ['digest', 'notification']; -const jwtVerifyAsync = util.promisify(function (token, callback) { +const jwtVerifyAsync = util.promisify((token, callback) => { jwt.verify(token, nconf.get('secret'), (err, payload) => callback(err, payload)); }); const doUnsubscribe = async (payload) => { @@ -221,7 +221,7 @@ async function getHomePageRoutes(userData) { // Set selected for each route var customIdx; var hasSelected = false; - routes = routes.map(function (route, idx) { + routes = routes.map((route, idx) => { if (route.route === userData.settings.homePageRoute) { route.selected = true; hasSelected = true; diff --git a/src/controllers/accounts/uploads.js b/src/controllers/accounts/uploads.js index aed470a44e..95fce14801 100644 --- a/src/controllers/accounts/uploads.js +++ b/src/controllers/accounts/uploads.js @@ -25,12 +25,10 @@ uploadsController.get = async function (req, res, next) { db.getSortedSetRevRange(`uid:${userData.uid}:uploads`, start, stop), ]); - userData.uploads = uploadNames.map(function (uploadName) { - return { - name: uploadName, - url: nconf.get('upload_url') + uploadName, - }; - }); + userData.uploads = uploadNames.map(uploadName => ({ + name: uploadName, + url: nconf.get('upload_url') + uploadName, + })); const pageCount = Math.ceil(itemCount / itemsPerPage); userData.pagination = pagination.create(page, pageCount, req.query); userData.privateUploads = meta.config.privateUploads === 1; diff --git a/src/controllers/admin/cache.js b/src/controllers/admin/cache.js index a0f6692943..15d8ffb91a 100644 --- a/src/controllers/admin/cache.js +++ b/src/controllers/admin/cache.js @@ -50,7 +50,7 @@ cacheController.dump = function (req, res, next) { const data = JSON.stringify(caches[req.query.name].dump(), null, 4); res.setHeader('Content-disposition', `attachment; filename= ${req.query.name}-cache.json`); res.setHeader('Content-type', 'application/json'); - res.write(data, function (err) { + res.write(data, (err) => { if (err) { return next(err); } diff --git a/src/controllers/admin/categories.js b/src/controllers/admin/categories.js index 9eec6a9818..2e211d087e 100644 --- a/src/controllers/admin/categories.js +++ b/src/controllers/admin/categories.js @@ -116,7 +116,7 @@ async function buildBreadcrumbs(req, categoryData) { const allCrumbs = await helpers.buildCategoryBreadcrumbs(categoryData.parentCid); const crumbs = allCrumbs.filter(c => c.cid); - crumbs.forEach(function (c) { + crumbs.forEach((c) => { c.url = `/admin/manage/categories?cid=${c.cid}`; }); crumbs.unshift({ diff --git a/src/controllers/admin/events.js b/src/controllers/admin/events.js index f6828d42d1..1ca791ac16 100644 --- a/src/controllers/admin/events.js +++ b/src/controllers/admin/events.js @@ -25,13 +25,11 @@ eventsController.get = async function (req, res) { events.getEvents(currentFilter, start, stop, from || '-inf', to), ]); - const types = [''].concat(events.types).map(function (type) { - return { - value: type, - name: type || 'all', - selected: type === currentFilter, - }; - }); + const types = [''].concat(events.types).map(type => ({ + value: type, + name: type || 'all', + selected: type === currentFilter, + })); const pageCount = Math.max(1, Math.ceil(eventCount / itemsPerPage)); diff --git a/src/controllers/admin/groups.js b/src/controllers/admin/groups.js index 9f789cd0b7..9368dba9f7 100644 --- a/src/controllers/admin/groups.js +++ b/src/controllers/admin/groups.js @@ -42,13 +42,11 @@ groupsController.get = async function (req, res, next) { } group.isOwner = true; - const groupNameData = groupNames.map(function (name) { - return { - encodedName: encodeURIComponent(name), - displayName: validator.escape(String(name)), - selected: name === groupName, - }; - }); + const groupNameData = groupNames.map(name => ({ + encodedName: encodeURIComponent(name), + displayName: validator.escape(String(name)), + selected: name === groupName, + })); res.render('admin/manage/group', { group: group, diff --git a/src/controllers/admin/hooks.js b/src/controllers/admin/hooks.js index 86cbc0ddd1..0f68a7e47e 100644 --- a/src/controllers/admin/hooks.js +++ b/src/controllers/admin/hooks.js @@ -7,7 +7,7 @@ const hooksController = module.exports; hooksController.get = function (req, res) { const hooks = []; - Object.keys(plugins.loadedHooks).forEach(function (key, hookIndex) { + Object.keys(plugins.loadedHooks).forEach((key, hookIndex) => { const current = { hookName: key, methods: [], @@ -15,7 +15,7 @@ hooksController.get = function (req, res) { count: plugins.loadedHooks[key].length, }; - plugins.loadedHooks[key].forEach(function (hookData, methodIndex) { + plugins.loadedHooks[key].forEach((hookData, methodIndex) => { current.methods.push({ id: hookData.id, priority: hookData.priority, diff --git a/src/controllers/admin/info.js b/src/controllers/admin/info.js index 854a98d347..0d924225eb 100644 --- a/src/controllers/admin/info.js +++ b/src/controllers/admin/info.js @@ -16,10 +16,10 @@ infoController.get = function (req, res) { info = {}; pubsub.publish('sync:node:info:start'); const timeoutMS = 1000; - setTimeout(function () { + setTimeout(() => { const data = []; Object.keys(info).forEach(key => data.push(info[key])); - data.sort(function (a, b) { + data.sort((a, b) => { if (a.id < b.id) { return -1; } @@ -46,7 +46,7 @@ infoController.get = function (req, res) { }, timeoutMS); }; -pubsub.on('sync:node:info:start', async function () { +pubsub.on('sync:node:info:start', async () => { try { const data = await getNodeInfo(); data.id = `${os.hostname()}:${nconf.get('port')}`; @@ -56,7 +56,7 @@ pubsub.on('sync:node:info:start', async function () { } }); -pubsub.on('sync:node:info:end', function (data) { +pubsub.on('sync:node:info:end', (data) => { info[data.id] = data.data; }); @@ -77,7 +77,7 @@ async function getNodeInfo() { platform: os.platform(), arch: os.arch(), release: os.release(), - load: os.loadavg().map(function (load) { return load.toFixed(2); }).join(', '), + load: os.loadavg().map(load => load.toFixed(2)).join(', '), freemem: os.freemem(), totalmem: os.totalmem(), }, @@ -118,7 +118,7 @@ function humanReadableUptime(seconds) { async function getGitInfo() { function get(cmd, callback) { - exec(cmd, function (err, stdout) { + exec(cmd, (err, stdout) => { if (err) { winston.error(err.stack); } diff --git a/src/controllers/admin/plugins.js b/src/controllers/admin/plugins.js index 464a844a5a..271c91f29d 100644 --- a/src/controllers/admin/plugins.js +++ b/src/controllers/admin/plugins.js @@ -32,18 +32,14 @@ pluginsController.get = async function (req, res) { installedCount: installedPlugins.length, activeCount: activePlugins.length, inactiveCount: Math.max(0, installedPlugins.length - activePlugins.length), - upgradeCount: compatible.reduce(function (count, current) { + upgradeCount: compatible.reduce((count, current) => { if (current.installed && current.outdated) { count += 1; } return count; }, 0), - download: compatible.filter(function (plugin) { - return !plugin.installed; - }), - incompatible: all.filter(function (plugin) { - return !compatiblePkgNames.includes(plugin.name); - }), + download: compatible.filter(plugin => !plugin.installed), + incompatible: all.filter(plugin => !compatiblePkgNames.includes(plugin.name)), trending: trendingPlugins, submitPluginUsage: meta.config.submitPluginUsage, version: nconf.get('version'), diff --git a/src/controllers/admin/privileges.js b/src/controllers/admin/privileges.js index ad68818d5e..fbcd504a53 100644 --- a/src/controllers/admin/privileges.js +++ b/src/controllers/admin/privileges.js @@ -27,7 +27,7 @@ privilegesController.get = async function (req, res) { }]; let selectedCategory; - categoriesData.forEach(function (category) { + categoriesData.forEach((category) => { if (category) { category.selected = category.cid === (!isAdminPriv ? cid : 'admin'); diff --git a/src/controllers/admin/settings.js b/src/controllers/admin/settings.js index f85d867529..41166e6d1c 100644 --- a/src/controllers/admin/settings.js +++ b/src/controllers/admin/settings.js @@ -30,12 +30,10 @@ settingsController.email = async (req, res) => { settingsController.user = async (req, res) => { const notificationTypes = await notifications.getAllNotificationTypes(); - const notificationSettings = notificationTypes.map(function (type) { - return { - name: type, - label: `[[notifications:${type}]]`, - }; - }); + const notificationSettings = notificationTypes.map(type => ({ + name: type, + label: `[[notifications:${type}]]`, + })); res.render('admin/settings/user', { notificationSettings: notificationSettings, }); @@ -50,7 +48,7 @@ settingsController.post = async (req, res) => { settingsController.languages = async function (req, res) { const languageData = await languages.list(); - languageData.forEach(function (language) { + languageData.forEach((language) => { language.selected = language.code === meta.config.defaultLang; }); @@ -69,20 +67,18 @@ settingsController.navigation = async function (req, res) { allGroups.sort((a, b) => b.system - a.system); admin.groups = allGroups.map(group => ({ name: group.name, displayName: group.displayName })); - admin.enabled.forEach(function (enabled, index) { + admin.enabled.forEach((enabled, index) => { enabled.index = index; enabled.selected = index === 0; enabled.title = translator.escape(enabled.title); enabled.text = translator.escape(enabled.text); - enabled.groups = admin.groups.map(function (group) { - return { - displayName: group.displayName, - selected: enabled.groups.includes(group.name), - }; - }); + enabled.groups = admin.groups.map(group => ({ + displayName: group.displayName, + selected: enabled.groups.includes(group.name), + })); }); - admin.available.forEach(function (available) { + admin.available.forEach((available) => { available.groups = admin.groups; }); diff --git a/src/controllers/admin/uploads.js b/src/controllers/admin/uploads.js index 45169d25ca..eb3d7eed5e 100644 --- a/src/controllers/admin/uploads.js +++ b/src/controllers/admin/uploads.js @@ -33,7 +33,7 @@ uploadsController.get = async function (req, res, next) { files = await filesToData(currentFolder, files); // Float directories to the top - files.sort(function (a, b) { + files.sort((a, b) => { if (a.isDirectory && !b.isDirectory) { return -1; } else if (!a.isDirectory && b.isDirectory) { @@ -48,7 +48,7 @@ uploadsController.get = async function (req, res, next) { // Add post usage info if in /files if (['/files', '/files/'].includes(req.query.dir)) { const usage = await posts.uploads.getUsage(files); - files.forEach(function (file, idx) { + files.forEach((file, idx) => { file.inPids = usage[idx].map(pid => parseInt(pid, 10)); }); } @@ -68,7 +68,7 @@ function buildBreadcrumbs(currentFolder) { var crumbs = []; var parts = currentFolder.replace(nconf.get('upload_path'), '').split(path.sep); var currentPath = ''; - parts.forEach(function (part) { + parts.forEach((part) => { var dir = path.join(currentPath, part); crumbs.push({ text: part || 'Uploads', diff --git a/src/controllers/admin/users.js b/src/controllers/admin/users.js index 95268e323c..386a821b7a 100644 --- a/src/controllers/admin/users.js +++ b/src/controllers/admin/users.js @@ -164,7 +164,7 @@ usersController.search = async function (req, res) { const uids = searchData.users.map(user => user && user.uid); const userInfo = await user.getUsersFields(uids, ['email', 'flags', 'lastonline', 'joindate']); - searchData.users.forEach(function (user, index) { + searchData.users.forEach((user, index) => { if (user && userInfo[index]) { user.email = userInfo[index].email; user.flags = userInfo[index].flags || 0; @@ -203,7 +203,7 @@ async function getInvites() { let usernames = await user.getUsersFields(uids, ['username']); usernames = usernames.map(user => user.username); - invitations.forEach(function (invites, index) { + invitations.forEach((invites, index) => { invites.username = usernames[index]; }); @@ -215,13 +215,11 @@ async function getInvites() { usernames = await Promise.all(invitations.map(invites => getUsernamesByEmails(invites.invitations))); - invitations.forEach(function (invites, index) { - invites.invitations = invites.invitations.map(function (email, i) { - return { - email: email, - username: usernames[index][i] === '[[global:guest]]' ? '' : usernames[index][i], - }; - }); + invitations.forEach((invites, index) => { + invites.invitations = invites.invitations.map((email, i) => ({ + email: email, + username: usernames[index][i] === '[[global:guest]]' ? '' : usernames[index][i], + })); }); return invitations; } @@ -238,7 +236,7 @@ async function render(req, res, data) { data[`searchBy_${validator.escape(String(req.query.searchBy))}`] = true; } const filterBy = Array.isArray(req.query.filters || []) ? (req.query.filters || []) : [req.query.filters]; - filterBy.forEach(function (filter) { + filterBy.forEach((filter) => { data[`filterBy_${validator.escape(String(filter))}`] = true; }); data.userCount = parseInt(await db.getObjectField('global', 'userCount'), 10); @@ -265,7 +263,7 @@ usersController.getCSV = async function (req, res, next) { 'Content-Type': 'text/csv', 'Content-Disposition': 'attachment; filename=users.csv', }, - }, function (err) { + }, (err) => { if (err) { if (err.code === 'ENOENT') { res.locals.isAPI = false; diff --git a/src/controllers/authentication.js b/src/controllers/authentication.js index fed337b52a..7f54289c95 100644 --- a/src/controllers/authentication.js +++ b/src/controllers/authentication.js @@ -142,7 +142,7 @@ authenticationController.registerComplete = function (req, res, next) { return next(err); } - var callbacks = data.interstitials.reduce(function (memo, cur) { + var callbacks = data.interstitials.reduce((memo, cur) => { if (cur.hasOwnProperty('callback') && typeof cur.callback === 'function') { req.body.files = req.files; memo.push(cur.callback && cur.callback.constructor && cur.callback.constructor.name === 'AsyncFunction' ? cur.callback : util.promisify(cur.callback)); @@ -201,7 +201,7 @@ authenticationController.registerComplete = function (req, res, next) { authenticationController.registerAbort = function (req, res) { // End the session and redirect to home - req.session.destroy(function () { + req.session.destroy(() => { res.clearCookie(nconf.get('sessionKey'), meta.configs.cookie.get()); res.redirect(`${nconf.get('relative_path')}/`); }); @@ -248,7 +248,7 @@ authenticationController.login = async (req, res, next) => { }; function continueLogin(strategy, req, res, next) { - passport.authenticate(strategy, async function (err, userData, info) { + passport.authenticate(strategy, async (err, userData, info) => { if (err) { return helpers.noScriptErrors(req, res, err.message, 403); } diff --git a/src/controllers/categories.js b/src/controllers/categories.js index ee3040ef49..435ea41334 100644 --- a/src/controllers/categories.js +++ b/src/controllers/categories.js @@ -41,7 +41,7 @@ categoriesController.list = async function (req, res) { pagination: pagination.create(page, pageCount, req.query), }; - data.categories.forEach(function (category) { + data.categories.forEach((category) => { if (category) { helpers.trimChildren(category); helpers.setCategoryTeaser(category); diff --git a/src/controllers/category.js b/src/controllers/category.js index 9265424c44..be9edb603a 100644 --- a/src/controllers/category.js +++ b/src/controllers/category.js @@ -104,7 +104,7 @@ categoryController.get = async function (req, res, next) { categoryData.hasMoreSubCategories = categoryData.children.length > categoryData.subCategoriesPerPage; categoryData.nextSubCategoryStart = categoryData.subCategoriesPerPage; categoryData.children = categoryData.children.slice(0, categoryData.subCategoriesPerPage); - categoryData.children.forEach(function (child) { + categoryData.children.forEach((child) => { if (child) { helpers.trimChildren(child); helpers.setCategoryTeaser(child); @@ -130,7 +130,7 @@ categoryController.get = async function (req, res, next) { categoryData['feeds:disableRSS'] = meta.config['feeds:disableRSS'] || 0; categoryData['reputation:disabled'] = meta.config['reputation:disabled']; categoryData.pagination = pagination.create(currentPage, pageCount, req.query); - categoryData.pagination.rel.forEach(function (rel) { + categoryData.pagination.rel.forEach((rel) => { rel.href = `${url}/category/${categoryData.slug}${rel.href}`; res.locals.linkTags.push(rel); }); diff --git a/src/controllers/errors.js b/src/controllers/errors.js index 177da067a3..d2877d9b48 100644 --- a/src/controllers/errors.js +++ b/src/controllers/errors.js @@ -67,7 +67,7 @@ exports.handleErrors = function handleErrors(err, req, res, next) { // eslint-di plugins.hooks.fire('filter:error.handle', { cases: cases, - }, function (_err, data) { + }, (_err, data) => { if (_err) { // Assume defaults winston.warn(`[errors/handle] Unable to retrieve plugin handlers for errors: ${_err.message}`); diff --git a/src/controllers/helpers.js b/src/controllers/helpers.js index ebfca2eb40..e7c9826d19 100644 --- a/src/controllers/helpers.js +++ b/src/controllers/helpers.js @@ -58,7 +58,7 @@ helpers.addLinkTags = function (params) { href: `${url}/${params.url}`, }); - params.tags.forEach(function (rel) { + params.tags.forEach((rel) => { rel.href = `${url}/${params.url}${rel.href}`; params.res.locals.linkTags.push(rel); }); @@ -208,7 +208,7 @@ helpers.buildBreadcrumbs = function (crumbs) { }, ]; - crumbs.forEach(function (crumb) { + crumbs.forEach((crumb) => { if (crumb) { if (crumb.url) { crumb.url = relative_path + crumb.url; @@ -253,7 +253,7 @@ async function getCategoryData(cids, uid, selectedCid, states, privilege) { let selectedCategory = []; const selectedCids = []; - categoriesData.forEach(function (category) { + categoriesData.forEach((category) => { category.selected = selectedCid ? selectedCid.includes(String(category.cid)) : false; if (category.selected) { selectedCategory.push(category); @@ -312,7 +312,7 @@ helpers.getVisibleCategories = async function (params) { const cidToCategory = _.zipObject(cids, categoriesData); const cidToWatchState = _.zipObject(cids, watchState); - return categoriesData.filter(function (c) { + return categoriesData.filter((c) => { if (!c) { return false; } @@ -360,7 +360,7 @@ helpers.getSelectedCategory = async function (cid) { helpers.trimChildren = function (category) { if (Array.isArray(category.children)) { category.children = category.children.slice(0, category.subCategoriesPerPage); - category.children.forEach(function (child) { + category.children.forEach((child) => { child.children = undefined; }); } diff --git a/src/controllers/index.js b/src/controllers/index.js index 6051ead24c..46ba28a67c 100644 --- a/src/controllers/index.js +++ b/src/controllers/index.js @@ -216,7 +216,7 @@ Controllers.registerInterstitial = async function (req, res, next) { }; Controllers.confirmEmail = function (req, res) { - user.email.confirmByCode(req.params.code, function (err) { + user.email.confirmByCode(req.params.code, (err) => { res.render('confirm', { error: err ? err.message : '', title: '[[pages:confirm]]', diff --git a/src/controllers/mods.js b/src/controllers/mods.js index 0de133d3c9..7907cc243e 100644 --- a/src/controllers/mods.js +++ b/src/controllers/mods.js @@ -39,7 +39,7 @@ modsController.flags.list = async function (req, res, next) { } // Parse query string params for filters, eliminate non-valid filters - filters = filters.reduce(function (memo, cur) { + filters = filters.reduce((memo, cur) => { if (req.query.hasOwnProperty(cur)) { if (req.query[cur] !== '') { memo[cur] = req.query[cur]; @@ -129,7 +129,7 @@ modsController.flags.detail = async function (req, res, next) { res.render('flags/detail', Object.assign(results.flagData, { assignees: results.assignees, - type_bool: ['post', 'user', 'empty'].reduce(function (memo, cur) { + type_bool: ['post', 'user', 'empty'].reduce((memo, cur) => { if (cur !== 'empty') { memo[cur] = results.flagData.type === cur && (!results.flagData.target || !!Object.keys(results.flagData.target).length); } else { @@ -196,7 +196,7 @@ modsController.postQueue = async function (req, res, next) { async function getQueuedPosts(ids) { const keys = ids.map(id => `post:queue:${id}`); const postData = await db.getObjects(keys); - postData.forEach(function (data) { + postData.forEach((data) => { if (data) { data.data = JSON.parse(data.data); data.data.timestampISO = utils.toISOString(data.data.timestamp); @@ -204,7 +204,7 @@ async function getQueuedPosts(ids) { }); const uids = postData.map(data => data && data.uid); const userData = await user.getUsersFields(uids, ['username', 'userslug', 'picture']); - postData.forEach(function (postData, index) { + postData.forEach((postData, index) => { if (postData) { postData.user = userData[index]; postData.data.rawContent = validator.escape(String(postData.data.content)); diff --git a/src/controllers/sitemap.js b/src/controllers/sitemap.js index 098fe035ff..7f1ac3dca9 100644 --- a/src/controllers/sitemap.js +++ b/src/controllers/sitemap.js @@ -24,9 +24,7 @@ sitemapController.getCategories = function (req, res, next) { }; sitemapController.getTopicPage = function (req, res, next) { - sendSitemap(async function () { - return await sitemap.getTopicPage(parseInt(req.params[0], 10)); - }, res, next); + sendSitemap(async () => await sitemap.getTopicPage(parseInt(req.params[0], 10)), res, next); }; async function sendSitemap(method, res, callback) { diff --git a/src/controllers/topics.js b/src/controllers/topics.js index 58269efc20..7ced57b9db 100644 --- a/src/controllers/topics.js +++ b/src/controllers/topics.js @@ -102,7 +102,7 @@ topicsController.get = async function getTopic(req, res, callback) { ]); topicData.pagination = pagination.create(currentPage, pageCount, req.query); - topicData.pagination.rel.forEach(function (rel) { + topicData.pagination.rel.forEach((rel) => { rel.href = `${url}/topic/${topicData.slug}${rel.href}`; res.locals.linkTags.push(rel); }); @@ -344,7 +344,7 @@ topicsController.pagination = async function (req, res, callback) { const pageCount = Math.max(1, Math.ceil(postCount / settings.postsPerPage)); const paginationData = pagination.create(currentPage, pageCount); - paginationData.rel.forEach(function (rel) { + paginationData.rel.forEach((rel) => { rel.href = `${url}/topic/${topic.slug}${rel.href}`; }); diff --git a/src/controllers/uploads.js b/src/controllers/uploads.js index a8a7773f20..a5e3b50bd9 100644 --- a/src/controllers/uploads.js +++ b/src/controllers/uploads.js @@ -49,7 +49,7 @@ uploadsController.upload = async function (req, res, filesIterator) { }; uploadsController.uploadPost = async function (req, res) { - await uploadsController.upload(req, res, async function (uploadedFile) { + await uploadsController.upload(req, res, async (uploadedFile) => { const isImage = uploadedFile.type.match(/image./); if (isImage) { return await uploadAsImage(req, uploadedFile); @@ -123,7 +123,7 @@ uploadsController.uploadThumb = async function (req, res) { return helpers.formatApiResponse(503, res, new Error('[[error:topic-thumbnails-are-disabled]]')); } - return await uploadsController.upload(req, res, async function (uploadedFile) { + return await uploadsController.upload(req, res, async (uploadedFile) => { if (!uploadedFile.type.match(/image./)) { throw new Error('[[error:invalid-file]]'); } diff --git a/src/controllers/user.js b/src/controllers/user.js index ab69b7d8ff..353c4170c1 100644 --- a/src/controllers/user.js +++ b/src/controllers/user.js @@ -95,7 +95,7 @@ function sendExport(filename, type, res, next) { 'Content-Type': type, 'Content-Disposition': `attachment; filename=${filename}`, }, - }, function (err) { + }, (err) => { if (err) { if (err.code === 'ENOENT') { res.locals.isAPI = false; diff --git a/src/controllers/users.js b/src/controllers/users.js index 611cf52619..147841cf21 100644 --- a/src/controllers/users.js +++ b/src/controllers/users.js @@ -50,7 +50,7 @@ usersController.getOnlineUsers = async function (req, res) { let hiddenCount = 0; if (!userData.isAdminOrGlobalMod) { - userData.users = userData.users.filter(function (user) { + userData.users = userData.users.filter((user) => { if (user && user.status === 'offline') { hiddenCount += 1; } diff --git a/src/controllers/write/topics.js b/src/controllers/write/topics.js index 303fa60c4f..e940fd28e7 100644 --- a/src/controllers/write/topics.js +++ b/src/controllers/write/topics.js @@ -152,7 +152,7 @@ Topics.migrateThumbs = async (req, res) => { Topics.deleteThumb = async (req, res) => { if (!req.body.path.startsWith('http')) { - await middleware.assert.path(req, res, function () {}); + await middleware.assert.path(req, res, () => {}); if (res.headersSent) { return; } diff --git a/src/controllers/write/users.js b/src/controllers/write/users.js index 4fc80aa6f1..efa048f5aa 100644 --- a/src/controllers/write/users.js +++ b/src/controllers/write/users.js @@ -136,7 +136,7 @@ Users.deleteToken = async (req, res) => { } }; -const getSessionAsync = util.promisify(function (sid, callback) { +const getSessionAsync = util.promisify((sid, callback) => { db.sessionStore.get(sid, (err, sessionObj) => callback(err, sessionObj || null)); }); diff --git a/src/database/mongo.js b/src/database/mongo.js index 5323bc6578..a139a6ada3 100644 --- a/src/database/mongo.js +++ b/src/database/mongo.js @@ -135,17 +135,15 @@ mongoModule.info = async function (db) { stats.serverStatusError = serverStatusError; const scale = 1024 * 1024 * 1024; - listCollections = listCollections.map(function (collectionInfo) { - return { - name: collectionInfo.ns, - count: collectionInfo.count, - size: collectionInfo.size, - avgObjSize: collectionInfo.avgObjSize, - storageSize: collectionInfo.storageSize, - totalIndexSize: collectionInfo.totalIndexSize, - indexSizes: collectionInfo.indexSizes, - }; - }); + listCollections = listCollections.map(collectionInfo => ({ + name: collectionInfo.ns, + count: collectionInfo.count, + size: collectionInfo.size, + avgObjSize: collectionInfo.avgObjSize, + storageSize: collectionInfo.storageSize, + totalIndexSize: collectionInfo.totalIndexSize, + indexSizes: collectionInfo.indexSizes, + })); stats.mem = serverStatus.mem || { resident: 0, virtual: 0, mapped: 0 }; stats.mem.resident = (stats.mem.resident / 1024).toFixed(3); diff --git a/src/database/mongo/hash.js b/src/database/mongo/hash.js index ba89a516d1..4056b64b7a 100644 --- a/src/database/mongo/hash.js +++ b/src/database/mongo/hash.js @@ -115,7 +115,7 @@ module.exports = function (module) { } const map = helpers.toMap(data); - unCachedKeys.forEach(function (key) { + unCachedKeys.forEach((key) => { cachedData[key] = map[key] || null; cache.set(key, cachedData[key]); }); @@ -123,7 +123,7 @@ module.exports = function (module) { if (!fields.length) { return keys.map(key => (cachedData[key] ? { ...cachedData[key] } : null)); } - return keys.map(function (key) { + return keys.map((key) => { const item = cachedData[key] || {}; const result = {}; fields.forEach((field) => { @@ -154,7 +154,7 @@ module.exports = function (module) { } const data = {}; - fields.forEach(function (field) { + fields.forEach((field) => { field = helpers.fieldToString(field); data[field] = 1; }); @@ -178,7 +178,7 @@ module.exports = function (module) { } var data = {}; - fields.forEach(function (field) { + fields.forEach((field) => { field = helpers.fieldToString(field); data[field] = ''; }); @@ -211,7 +211,7 @@ module.exports = function (module) { if (Array.isArray(key)) { var bulk = module.client.collection('objects').initializeUnorderedBulkOp(); - key.forEach(function (key) { + key.forEach((key) => { bulk.find({ _key: key }).upsert().update({ $inc: increment }); }); await bulk.execute(); diff --git a/src/database/mongo/main.js b/src/database/mongo/main.js index a1cba7b1e7..a3e513583c 100644 --- a/src/database/mongo/main.js +++ b/src/database/mongo/main.js @@ -22,7 +22,7 @@ module.exports = function (module) { }, { _id: 0, _key: 1 }).toArray(); const map = {}; - data.forEach(function (item) { + data.forEach((item) => { map[item._key] = true; }); diff --git a/src/database/mongo/sets.js b/src/database/mongo/sets.js index a88ec7096b..9e10ef312a 100644 --- a/src/database/mongo/sets.js +++ b/src/database/mongo/sets.js @@ -104,7 +104,7 @@ module.exports = function (module) { const result = await module.client.collection('objects').find({ _key: { $in: sets }, members: value }, { projection: { _id: 0, members: 0 } }).toArray(); var map = {}; - result.forEach(function (item) { + result.forEach((item) => { map[item._key] = true; }); @@ -127,7 +127,7 @@ module.exports = function (module) { const data = await module.client.collection('objects').find({ _key: { $in: keys } }, { projection: { _id: 0 } }).toArray(); var sets = {}; - data.forEach(function (set) { + data.forEach((set) => { sets[set._key] = set.members || []; }); diff --git a/src/database/mongo/sorted.js b/src/database/mongo/sorted.js index e5580ecc93..d852c4535a 100644 --- a/src/database/mongo/sorted.js +++ b/src/database/mongo/sorted.js @@ -247,7 +247,7 @@ module.exports = function (module) { return [await getSortedSetRank(reverse, key, values[0])]; } const sortedSet = await module[reverse ? 'getSortedSetRevRange' : 'getSortedSetRange'](key, 0, -1); - return values.map(function (value) { + return values.map((value) => { if (!value) { return null; } @@ -272,7 +272,7 @@ module.exports = function (module) { value = helpers.valueToString(value); const result = await module.client.collection('objects').find({ _key: { $in: keys }, value: value }, { projection: { _id: 0, value: 0 } }).toArray(); var map = {}; - result.forEach(function (item) { + result.forEach((item) => { if (item) { map[item._key] = item; } @@ -292,7 +292,7 @@ module.exports = function (module) { const result = await module.client.collection('objects').find({ _key: key, value: { $in: values } }, { projection: { _id: 0, _key: 0 } }).toArray(); var valueToScore = {}; - result.forEach(function (item) { + result.forEach((item) => { if (item) { valueToScore[item.value] = item.score; } @@ -329,7 +329,7 @@ module.exports = function (module) { }).toArray(); var isMember = {}; - results.forEach(function (item) { + results.forEach((item) => { if (item) { isMember[item.value] = true; } @@ -350,7 +350,7 @@ module.exports = function (module) { }).toArray(); var isMember = {}; - results.forEach(function (item) { + results.forEach((item) => { if (item) { isMember[item._key] = true; } @@ -381,7 +381,7 @@ module.exports = function (module) { return [data.map(item => item.value)]; } const sets = {}; - data.forEach(function (item) { + data.forEach((item) => { sets[item._key] = sets[item._key] || []; sets[item._key].push(item.value); }); diff --git a/src/database/mongo/sorted/add.js b/src/database/mongo/sorted/add.js index 934e77bc1a..f157774293 100644 --- a/src/database/mongo/sorted/add.js +++ b/src/database/mongo/sorted/add.js @@ -75,7 +75,7 @@ module.exports = function (module) { return; } var bulk = module.client.collection('objects').initializeUnorderedBulkOp(); - data.forEach(function (item) { + data.forEach((item) => { if (!utils.isNumber(item[1])) { throw new Error(`[[error:invalid-score, ${item[1]}]]`); } diff --git a/src/database/mongo/sorted/intersect.js b/src/database/mongo/sorted/intersect.js index 88bf8830fe..a91388539c 100644 --- a/src/database/mongo/sorted/intersect.js +++ b/src/database/mongo/sorted/intersect.js @@ -140,7 +140,7 @@ module.exports = function (module) { items.push(nextItem); } - const members = await Promise.all(otherSets.map(async function (s) { + const members = await Promise.all(otherSets.map(async (s) => { const data = await module.client.collection('objects').find({ _key: s, value: { $in: items.map(i => i.value) }, }, { @@ -170,7 +170,7 @@ module.exports = function (module) { } const pipeline = [{ $match: { _key: { $in: params.sets } } }]; - params.weights.forEach(function (weight, index) { + params.weights.forEach((weight, index) => { if (weight !== 1) { pipeline.push({ $project: { diff --git a/src/database/postgres.js b/src/database/postgres.js index 9187f73bb7..25809ca1e6 100644 --- a/src/database/postgres.js +++ b/src/database/postgres.js @@ -337,7 +337,7 @@ postgresModule.createIndices = function (callback) { async.series([ async.apply(query, `CREATE INDEX IF NOT EXISTS "idx__legacy_zset__key__score" ON "legacy_zset"("_key" ASC, "score" DESC)`), async.apply(query, `CREATE INDEX IF NOT EXISTS "idx__legacy_object__expireAt" ON "legacy_object"("expireAt" ASC)`), - ], function (err) { + ], (err) => { if (err) { winston.error(`Error creating index ${err.message}`); return callback(err); diff --git a/src/database/postgres/hash.js b/src/database/postgres/hash.js index 9872b86794..7321e31d47 100644 --- a/src/database/postgres/hash.js +++ b/src/database/postgres/hash.js @@ -12,7 +12,7 @@ module.exports = function (module) { delete data['']; } - await module.transaction(async function (client) { + await module.transaction(async (client) => { const dataString = JSON.stringify(data); async function setOne(key) { await helpers.ensureLegacyObjectType(client, key, 'hash'); @@ -47,7 +47,7 @@ module.exports = function (module) { return; } - await module.transaction(async function (client) { + await module.transaction(async (client) => { const valueString = JSON.stringify(value); async function setOne(key) { await helpers.ensureLegacyObjectType(client, key, 'hash'); @@ -159,7 +159,7 @@ SELECT (SELECT jsonb_object_agg(f, d."value") } var obj = {}; - fields.forEach(function (f) { + fields.forEach((f) => { obj[f] = null; }); @@ -292,7 +292,7 @@ SELECT (h."data" ? $2::TEXT AND h."data"->>$2::TEXT IS NOT NULL) b return null; } - return await module.transaction(async function (client) { + return await module.transaction(async (client) => { if (Array.isArray(key)) { await helpers.ensureLegacyObjectsType(client, key, 'hash'); } else { diff --git a/src/database/postgres/helpers.js b/src/database/postgres/helpers.js index 5a24aa5da3..9749d67444 100644 --- a/src/database/postgres/helpers.js +++ b/src/database/postgres/helpers.js @@ -88,9 +88,7 @@ SELECT "_key", "type" throw new Error(`database: cannot insert multiple objects as ${type} because they already exist: ${parts.join(', ')}`); } - var missing = keys.filter(function (k) { - return !res.rows.some(r => r._key === k); - }); + var missing = keys.filter(k => !res.rows.some(r => r._key === k)); if (missing.length) { throw new Error(`database: failed to insert keys for objects: ${JSON.stringify(missing)}`); diff --git a/src/database/postgres/list.js b/src/database/postgres/list.js index 33325516f8..a67705660c 100644 --- a/src/database/postgres/list.js +++ b/src/database/postgres/list.js @@ -8,7 +8,7 @@ module.exports = function (module) { return; } - await module.transaction(async function (client) { + await module.transaction(async (client) => { await helpers.ensureLegacyObjectType(client, key, 'list'); await client.query({ name: 'listPrepend', @@ -27,7 +27,7 @@ DO UPDATE SET "array" = ARRAY[$2::TEXT] || "legacy_list"."array"`, return; } - await module.transaction(async function (client) { + await module.transaction(async (client) => { await helpers.ensureLegacyObjectType(client, key, 'list'); await client.query({ name: 'listAppend', diff --git a/src/database/postgres/main.js b/src/database/postgres/main.js index c5fbb67847..313f8a4f5b 100644 --- a/src/database/postgres/main.js +++ b/src/database/postgres/main.js @@ -26,9 +26,7 @@ module.exports = function (module) { WHERE o."_key" = ANY($1::TEXT[])`, values: [key], }); - return key.map(function (k) { - return res.rows.some(r => r.k === k); - }); + return key.map(k => res.rows.some(r => r.k === k)); } const res = await module.pool.query({ name: 'exists', @@ -115,7 +113,7 @@ SELECT s."data" t return; } - await module.transaction(async function (client) { + await module.transaction(async (client) => { await helpers.ensureLegacyObjectType(client, key, 'string'); await client.query({ name: 'set', @@ -134,7 +132,7 @@ DO UPDATE SET "data" = $2::TEXT`, return; } - return await module.transaction(async function (client) { + return await module.transaction(async (client) => { await helpers.ensureLegacyObjectType(client, key, 'string'); const res = await client.query({ name: 'increment', @@ -151,7 +149,7 @@ RETURNING "data" d`, }; module.rename = async function (oldKey, newKey) { - await module.transaction(async function (client) { + await module.transaction(async (client) => { await client.query({ name: 'deleteRename', text: ` diff --git a/src/database/postgres/sets.js b/src/database/postgres/sets.js index 99894140cf..de84bbbc67 100644 --- a/src/database/postgres/sets.js +++ b/src/database/postgres/sets.js @@ -12,7 +12,7 @@ module.exports = function (module) { if (!value.length) { return; } - await module.transaction(async function (client) { + await module.transaction(async (client) => { await helpers.ensureLegacyObjectType(client, key, 'set'); await client.query({ name: 'setAdd', @@ -38,7 +38,7 @@ DO NOTHING`, keys = _.uniq(keys); - await module.transaction(async function (client) { + await module.transaction(async (client) => { await helpers.ensureLegacyObjectsType(client, keys, 'set'); await client.query({ name: 'setsAdd', @@ -129,9 +129,7 @@ SELECT s."member" m values: [key, values], }); - return values.map(function (v) { - return res.rows.some(r => r.m === v); - }); + return values.map(v => res.rows.some(r => r.m === v)); }; module.isMemberOfSets = async function (sets, value) { @@ -154,9 +152,7 @@ SELECT o."_key" k values: [sets, value], }); - return sets.map(function (s) { - return res.rows.some(r => r.k === s); - }); + return sets.map(s => res.rows.some(r => r.k === s)); }; module.getSetMembers = async function (key) { @@ -198,9 +194,7 @@ SELECT o."_key" k, values: [keys], }); - return keys.map(function (k) { - return (res.rows.find(r => r.k === k) || { m: [] }).m; - }); + return keys.map(k => (res.rows.find(r => r.k === k) || { m: [] }).m); }; module.setCount = async function (key) { @@ -238,9 +232,7 @@ SELECT o."_key" k, values: [keys], }); - return keys.map(function (k) { - return (res.rows.find(r => r.k === k) || { c: 0 }).c; - }); + return keys.map(k => (res.rows.find(r => r.k === k) || { c: 0 }).c); }; module.setRemoveRandom = async function (key) { diff --git a/src/database/postgres/sorted.js b/src/database/postgres/sorted.js index 14d68a7374..dfae4df874 100644 --- a/src/database/postgres/sorted.js +++ b/src/database/postgres/sorted.js @@ -218,9 +218,7 @@ SELECT o."_key" k, values: [keys], }); - return keys.map(function (k) { - return parseInt((res.rows.find(r => r.k === k) || { c: 0 }).c, 10); - }); + return keys.map(k => parseInt((res.rows.find(r => r.k === k) || { c: 0 }).c, 10)); }; module.sortedSetsCardSum = async function (keys) { @@ -347,7 +345,7 @@ SELECT o."_key" k, values: [keys, value], }); - return keys.map(function (k) { + return keys.map((k) => { var s = res.rows.find(r => r.k === k); return s ? parseFloat(s.s) : null; }); @@ -376,7 +374,7 @@ SELECT z."value" v, values: [key, values], }); - return values.map(function (v) { + return values.map((v) => { var s = res.rows.find(r => r.v === v); return s ? parseFloat(s.s) : null; }); @@ -428,9 +426,7 @@ SELECT z."value" v values: [key, values], }); - return values.map(function (v) { - return res.rows.some(r => r.v === v); - }); + return values.map(v => res.rows.some(r => r.v === v)); }; module.isMemberOfSortedSets = async function (keys, value) { @@ -453,9 +449,7 @@ SELECT o."_key" k values: [keys, value], }); - return keys.map(function (k) { - return res.rows.some(r => r.k === k); - }); + return keys.map(k => res.rows.some(r => r.k === k)); }; module.getSortedSetMembers = async function (key) { @@ -477,9 +471,7 @@ SELECT "_key" k, values: [keys], }); - return keys.map(function (k) { - return (res.rows.find(r => r.k === k) || {}).m || []; - }); + return keys.map(k => (res.rows.find(r => r.k === k) || {}).m || []); }; module.sortedSetIncrBy = async function (key, increment, value) { @@ -490,7 +482,7 @@ SELECT "_key" k, value = helpers.valueToString(value); increment = parseFloat(increment); - return await module.transaction(async function (client) { + return await module.transaction(async (client) => { await helpers.ensureLegacyObjectType(client, key, 'zset'); const res = await client.query({ name: 'sortedSetIncrBy', diff --git a/src/database/postgres/sorted/add.js b/src/database/postgres/sorted/add.js index 24e2bad459..058946d1a2 100644 --- a/src/database/postgres/sorted/add.js +++ b/src/database/postgres/sorted/add.js @@ -18,7 +18,7 @@ module.exports = function (module) { value = helpers.valueToString(value); score = parseFloat(score); - await module.transaction(async function (client) { + await module.transaction(async (client) => { await helpers.ensureLegacyObjectType(client, key, 'zset'); await client.query({ name: 'sortedSetAdd', @@ -49,7 +49,7 @@ module.exports = function (module) { helpers.removeDuplicateValues(values, scores); - await module.transaction(async function (client) { + await module.transaction(async (client) => { await helpers.ensureLegacyObjectType(client, key, 'zset'); await client.query({ name: 'sortedSetAddBulk', @@ -81,7 +81,7 @@ DO UPDATE SET "score" = EXCLUDED."score"`, value = helpers.valueToString(value); scores = isArrayOfScores ? scores.map(score => parseFloat(score)) : parseFloat(scores); - await module.transaction(async function (client) { + await module.transaction(async (client) => { await helpers.ensureLegacyObjectsType(client, keys, 'zset'); await client.query({ name: isArrayOfScores ? 'sortedSetsAddScores' : 'sortedSetsAdd', @@ -108,7 +108,7 @@ INSERT INTO "legacy_zset" ("_key", "value", "score") const keys = []; const values = []; const scores = []; - data.forEach(function (item) { + data.forEach((item) => { if (!utils.isNumber(item[1])) { throw new Error(`[[error:invalid-score, ${item[1]}]]`); } @@ -116,7 +116,7 @@ INSERT INTO "legacy_zset" ("_key", "value", "score") scores.push(item[1]); values.push(item[2]); }); - await module.transaction(async function (client) { + await module.transaction(async (client) => { await helpers.ensureLegacyObjectsType(client, keys, 'zset'); await client.query({ name: 'sortedSetAddBulk2', diff --git a/src/database/postgres/sorted/intersect.js b/src/database/postgres/sorted/intersect.js index 04eeed49e6..6e20ed49c1 100644 --- a/src/database/postgres/sorted/intersect.js +++ b/src/database/postgres/sorted/intersect.js @@ -79,12 +79,10 @@ OFFSET $3::INTEGER`, }); if (params.withScores) { - res.rows = res.rows.map(function (r) { - return { - value: r.value, - score: parseFloat(r.score), - }; - }); + res.rows = res.rows.map(r => ({ + value: r.value, + score: parseFloat(r.score), + })); } else { res.rows = res.rows.map(r => r.value); } diff --git a/src/database/postgres/sorted/union.js b/src/database/postgres/sorted/union.js index 7f330e70c2..e9b9154156 100644 --- a/src/database/postgres/sorted/union.js +++ b/src/database/postgres/sorted/union.js @@ -71,12 +71,10 @@ OFFSET $3::INTEGER`, }); if (params.withScores) { - res.rows = res.rows.map(function (r) { - return { - value: r.value, - score: parseFloat(r.score), - }; - }); + res.rows = res.rows.map(r => ({ + value: r.value, + score: parseFloat(r.score), + })); } else { res.rows = res.rows.map(r => r.value); } diff --git a/src/database/redis.js b/src/database/redis.js index ae15dae8c1..cef6105b5e 100644 --- a/src/database/redis.js +++ b/src/database/redis.js @@ -76,7 +76,7 @@ redisModule.info = async function (cxn) { const data = await infoAsync(); const lines = data.toString().split('\r\n').sort(); const redisData = {}; - lines.forEach(function (line) { + lines.forEach((line) => { const parts = line.split(':'); if (parts[1]) { redisData[parts[0]] = parts[1]; diff --git a/src/database/redis/connection.js b/src/database/redis/connection.js index bcedf0c333..6e685eadcf 100644 --- a/src/database/redis/connection.js +++ b/src/database/redis/connection.js @@ -20,7 +20,7 @@ connection.getConnectionOptions = function (redis) { }; connection.connect = async function (options) { - return new Promise(function (resolve, reject) { + return new Promise((resolve, reject) => { options = options || nconf.get('redis'); const redis_socket_or_host = options.host; const connOptions = connection.getConnectionOptions(options); @@ -39,11 +39,11 @@ connection.connect = async function (options) { throw new Error('[[error:no-database-selected]]'); } - cxn.on('error', function (err) { + cxn.on('error', (err) => { winston.error(err.stack); reject(err); }); - cxn.on('ready', function () { + cxn.on('ready', () => { resolve(cxn); }); diff --git a/src/database/redis/hash.js b/src/database/redis/hash.js index 583cce6613..4965790468 100644 --- a/src/database/redis/hash.js +++ b/src/database/redis/hash.js @@ -16,7 +16,7 @@ module.exports = function (module) { delete data['']; } - Object.keys(data).forEach(function (key) { + Object.keys(data).forEach((key) => { if (data[key] === undefined || data[key] === null) { delete data[key]; } @@ -99,7 +99,7 @@ module.exports = function (module) { return []; } if (!Array.isArray(fields)) { - return keys.map(function () { return {}; }); + return keys.map(() => ({})); } const cachedData = {}; const unCachedKeys = cache.getUnCachedKeys(keys, cachedData); @@ -113,7 +113,7 @@ module.exports = function (module) { data = [await module.client.async.hgetall(unCachedKeys[0])]; } - unCachedKeys.forEach(function (key, i) { + unCachedKeys.forEach((key, i) => { cachedData[key] = data[i] || null; cache.set(key, cachedData[key]); }); @@ -121,7 +121,7 @@ module.exports = function (module) { if (!fields.length) { return keys.map(key => (cachedData[key] ? { ...cachedData[key] } : null)); } - return keys.map(function (key) { + return keys.map((key) => { const item = cachedData[key] || {}; const result = {}; fields.forEach((field) => { diff --git a/src/database/redis/pubsub.js b/src/database/redis/pubsub.js index e7b57e195f..2287798674 100644 --- a/src/database/redis/pubsub.js +++ b/src/database/redis/pubsub.js @@ -11,10 +11,10 @@ const PubSub = function () { const self = this; channelName = `db:${nconf.get('redis:database')}:pubsub_channel`; - connection.connect().then(function (client) { + connection.connect().then((client) => { self.subClient = client; self.subClient.subscribe(channelName); - self.subClient.on('message', function (channel, message) { + self.subClient.on('message', (channel, message) => { if (channel !== channelName) { return; } @@ -28,7 +28,7 @@ const PubSub = function () { }); }); - connection.connect().then(function (client) { + connection.connect().then((client) => { self.pubClient = client; }); }; diff --git a/src/database/redis/sorted/add.js b/src/database/redis/sorted/add.js index c7ab9a809f..56920e0454 100644 --- a/src/database/redis/sorted/add.js +++ b/src/database/redis/sorted/add.js @@ -65,7 +65,7 @@ module.exports = function (module) { return; } var batch = module.client.batch(); - data.forEach(function (item) { + data.forEach((item) => { if (!utils.isNumber(item[1])) { throw new Error(`[[error:invalid-score, ${item[1]}]]`); } diff --git a/src/events.js b/src/events.js index 6d4f1aed57..d781fd851f 100644 --- a/src/events.js +++ b/src/events.js @@ -98,8 +98,8 @@ events.getEvents = async function (filter, start, stop, from, to) { eventsData = eventsData.filter(Boolean); await addUserData(eventsData, 'uid', 'user'); await addUserData(eventsData, 'targetUid', 'targetUser'); - eventsData.forEach(function (event) { - Object.keys(event).forEach(function (key) { + eventsData.forEach((event) => { + Object.keys(event).forEach((key) => { if (typeof event[key] === 'string') { event[key] = validator.escape(String(event[key] || '')); } @@ -129,12 +129,12 @@ async function addUserData(eventsData, field, objectName) { ]); const map = {}; - userData.forEach(function (user, index) { + userData.forEach((user, index) => { user.isAdmin = isAdmin[index]; map[user.uid] = user; }); - eventsData.forEach(function (event) { + eventsData.forEach((event) => { if (map[event[field]]) { event[objectName] = map[event[field]]; } @@ -153,7 +153,7 @@ events.deleteEvents = async function (eids) { }; events.deleteAll = async function () { - await batch.processSortedSet('events:time', async function (eids) { + await batch.processSortedSet('events:time', async (eids) => { await events.deleteEvents(eids); }, { alwaysStartAt: 0, batch: 500 }); }; diff --git a/src/file.js b/src/file.js index 8a17947524..6f1f0ebedd 100644 --- a/src/file.js +++ b/src/file.js @@ -60,7 +60,7 @@ file.allowedExtensions = function () { return []; } allowedExtensions = allowedExtensions.split(','); - allowedExtensions = allowedExtensions.filter(Boolean).map(function (extension) { + allowedExtensions = allowedExtensions.filter(Boolean).map((extension) => { extension = extension.trim(); if (!extension.startsWith('.')) { extension = `.${extension}`; diff --git a/src/flags.js b/src/flags.js index 56a671b747..09ae62067d 100644 --- a/src/flags.js +++ b/src/flags.js @@ -235,9 +235,7 @@ Flags.sort = async function (flagIds, sort) { const mapped = heat.map((el, i) => ({ index: i, heat: el, })); - mapped.sort(function (a, b) { - return b.heat - a.heat; - }); + mapped.sort((a, b) => b.heat - a.heat); flagIds = mapped.map(obj => flagIds[obj.index]); break; } @@ -340,7 +338,7 @@ Flags.getFlagIdByTarget = async function (type, id) { async function modifyNotes(notes) { const uids = []; - notes = notes.map(function (note) { + notes = notes.map((note) => { const noteObj = JSON.parse(note.value); uids.push(noteObj[0]); return { @@ -351,7 +349,7 @@ async function modifyNotes(notes) { }; }); const userData = await user.getUsersFields(uids, ['username', 'userslug', 'picture']); - return notes.map(function (note, idx) { + return notes.map((note, idx) => { note.user = userData[idx]; note.content = validator.escape(note.content); return note; @@ -452,7 +450,7 @@ Flags.create = async function (type, id, uid, reason, timestamp) { Flags.getReports = async function (flagId) { const payload = await db.getSortedSetRevRangeWithScores(`flag:${flagId}:reports`, 0, -1); - const [reports, uids] = payload.reduce(function (memo, cur) { + const [reports, uids] = payload.reduce((memo, cur) => { const value = cur.value.split(';'); memo[1].push(value.shift()); cur.value = value.join(';'); @@ -634,7 +632,7 @@ Flags.resolveFlag = async function (type, id, uid) { Flags.resolveUserPostFlags = async function (uid, callerUid) { if (meta.config['flags:autoResolveOnBan']) { - await batch.processSortedSet(`uid:${uid}:posts`, async function (pids) { + await batch.processSortedSet(`uid:${uid}:posts`, async (pids) => { let postData = await posts.getPostsFields(pids, ['pid', 'flagId']); postData = postData.filter(p => p && p.flagId); for (const postObj of postData) { @@ -654,7 +652,7 @@ Flags.getHistory = async function (flagId) { let history = await db.getSortedSetRevRangeWithScores(`flag:${flagId}:history`, 0, -1); const targetUid = await db.getObjectField(`flag:${flagId}`, 'targetUid'); - history = history.map(function (entry) { + history = history.map((entry) => { entry.value = JSON.parse(entry.value); uids.push(entry.value[0]); diff --git a/src/groups/data.js b/src/groups/data.js index d4eaa8fafc..40ab3f3846 100644 --- a/src/groups/data.js +++ b/src/groups/data.js @@ -19,7 +19,7 @@ module.exports = function (Groups) { return []; } - const ephemeralIdx = groupNames.reduce(function (memo, cur, idx) { + const ephemeralIdx = groupNames.reduce((memo, cur, idx) => { if (Groups.ephemeralGroups.includes(cur)) { memo.push(idx); } @@ -29,7 +29,7 @@ module.exports = function (Groups) { const keys = groupNames.map(groupName => `group:${groupName}`); const groupData = await (fields.length ? db.getObjectsFields(keys, fields) : db.getObjects(keys)); if (ephemeralIdx.length) { - ephemeralIdx.forEach(function (idx) { + ephemeralIdx.forEach((idx) => { groupData[idx] = Groups.getEphemeralGroup(groupNames[idx]); }); } diff --git a/src/groups/delete.js b/src/groups/delete.js index b49f63a45a..df097d5c54 100644 --- a/src/groups/delete.js +++ b/src/groups/delete.js @@ -17,7 +17,7 @@ module.exports = function (Groups) { return; } const keys = []; - groupNames.forEach(function (groupName) { + groupNames.forEach((groupName) => { keys.push(`group:${groupName}`, `group:${groupName}:members`, `group:${groupName}:pending`, @@ -45,7 +45,7 @@ module.exports = function (Groups) { }; async function removeGroupsFromPrivilegeGroups(groupNames) { - await batch.processSortedSet('groups:createtime', async function (otherGroups) { + await batch.processSortedSet('groups:createtime', async (otherGroups) => { const privilegeGroups = otherGroups.filter(group => Groups.isPrivilegeGroup(group)); const keys = privilegeGroups.map(group => `group:${group}:members`); await db.sortedSetRemove(keys, groupNames); diff --git a/src/groups/index.js b/src/groups/index.js index d9ed8fb93c..4c5bda43ae 100644 --- a/src/groups/index.js +++ b/src/groups/index.js @@ -100,7 +100,7 @@ Groups.getGroupsAndMembers = async function (groupNames) { Groups.getGroupsData(groupNames), Groups.getMemberUsers(groupNames, 0, 3), ]); - groups.forEach(function (group, index) { + groups.forEach((group, index) => { if (group) { group.members = members[index] || []; group.truncated = group.memberCount > group.members.length; @@ -157,7 +157,7 @@ Groups.getOwnersAndMembers = async function (groupName, uid, start, stop) { const countToReturn = stop - start + 1; const ownerUidsOnPage = ownerUids.slice(start, stop !== -1 ? stop + 1 : undefined); const owners = await user.getUsers(ownerUidsOnPage, uid); - owners.forEach(function (user) { + owners.forEach((user) => { if (user) { user.isOwner = true; } diff --git a/src/groups/join.js b/src/groups/join.js index 383c4782c3..d578b04841 100644 --- a/src/groups/join.js +++ b/src/groups/join.js @@ -74,7 +74,7 @@ module.exports = function (Groups) { return; } - await async.eachSeries(groupsToCreate, async function (groupName) { + await async.eachSeries(groupsToCreate, async (groupName) => { try { await Groups.create({ name: groupName, diff --git a/src/groups/membership.js b/src/groups/membership.js index 1ee2259521..f37853d433 100644 --- a/src/groups/membership.js +++ b/src/groups/membership.js @@ -55,7 +55,7 @@ module.exports = function (Groups) { } const isMembers = await db.isSortedSetMembers(`group:${groupName}:members`, nonCachedUids); - nonCachedUids.forEach(function (uid, index) { + nonCachedUids.forEach((uid, index) => { cachedData[`${uid}:${groupName}`] = isMembers[index]; Groups.cache.set(`${uid}:${groupName}`, isMembers[index]); }); @@ -74,7 +74,7 @@ module.exports = function (Groups) { } const nonCachedGroupsMemberSets = nonCachedGroups.map(groupName => `group:${groupName}:members`); const isMembers = await db.isMemberOfSortedSets(nonCachedGroupsMemberSets, uid); - nonCachedGroups.forEach(function (groupName, index) { + nonCachedGroups.forEach((groupName, index) => { cachedData[`${uid}:${groupName}`] = isMembers[index]; Groups.cache.set(`${uid}:${groupName}`, isMembers[index]); }); @@ -124,9 +124,7 @@ module.exports = function (Groups) { const isMembers = await Groups.isMemberOfGroups(uid, uniqueGroups); const isGroupMember = _.zipObject(uniqueGroups, isMembers); - return members.map(function (groupNames) { - return !!groupNames.find(name => isGroupMember[name]); - }); + return members.map(groupNames => !!groupNames.find(name => isGroupMember[name])); }; Groups.isMembersOfGroupList = async function (uids, groupListKey) { @@ -139,8 +137,8 @@ module.exports = function (Groups) { } const isGroupMembers = await Promise.all(groupNames.map(name => Groups.isMembers(uids, name))); - isGroupMembers.forEach(function (isMembers) { - results.forEach(function (isMember, index) { + isGroupMembers.forEach((isMembers) => { + results.forEach((isMember, index) => { if (!isMember && isMembers[index]) { results[index] = true; } @@ -154,7 +152,7 @@ module.exports = function (Groups) { keys = isArray ? keys : [keys]; const cachedData = {}; - const nonCachedKeys = keys.filter(function (groupName) { + const nonCachedKeys = keys.filter((groupName) => { const groupMembers = cache.get(`group:${groupName}:members`); const isInCache = groupMembers !== undefined; if (isInCache) { @@ -168,7 +166,7 @@ module.exports = function (Groups) { } const groupMembers = await db.getSortedSetsMembers(nonCachedKeys.map(name => `group:${name}:members`)); - nonCachedKeys.forEach(function (groupName, index) { + nonCachedKeys.forEach((groupName, index) => { cachedData[groupName] = groupMembers[index]; cache.set(`group:${groupName}:members`, groupMembers[index]); }); diff --git a/src/groups/search.js b/src/groups/search.js index 3cda01a30f..4bec5085af 100644 --- a/src/groups/search.js +++ b/src/groups/search.js @@ -65,13 +65,13 @@ module.exports = function (Groups) { const uids = results.users.map(user => user && user.uid); const isOwners = await Groups.ownership.isOwners(uids, data.groupName); - results.users.forEach(function (user, index) { + results.users.forEach((user, index) => { if (user) { user.isOwner = isOwners[index]; } }); - results.users.sort(function (a, b) { + results.users.sort((a, b) => { if (a.isOwner && !b.isOwner) { return -1; } else if (!a.isOwner && b.isOwner) { diff --git a/src/groups/update.js b/src/groups/update.js index fc5cf08ca0..24f4b53797 100644 --- a/src/groups/update.js +++ b/src/groups/update.js @@ -216,11 +216,11 @@ module.exports = function (Groups) { }; async function updateMemberGroupTitles(oldName, newName) { - await batch.processSortedSet(`group:${oldName}:members`, async function (uids) { + await batch.processSortedSet(`group:${oldName}:members`, async (uids) => { let usersData = await user.getUsersData(uids); usersData = usersData.filter(userData => userData && userData.groupTitleArray.includes(oldName)); - usersData.forEach(function (userData) { + usersData.forEach((userData) => { userData.newTitleArray = userData.groupTitleArray.map(oldTitle => (oldTitle === oldName ? newName : oldTitle)); }); @@ -242,7 +242,7 @@ module.exports = function (Groups) { async function updateNavigationItems(oldName, newName) { const navigation = require('../navigation/admin'); const navItems = await navigation.get(); - navItems.forEach(function (navItem) { + navItems.forEach((navItem) => { if (navItem && Array.isArray(navItem.groups) && navItem.groups.includes(oldName)) { navItem.groups.splice(navItem.groups.indexOf(oldName), 1, newName); } @@ -257,9 +257,9 @@ module.exports = function (Groups) { const data = await admin.get(); - data.areas.forEach(function (area) { + data.areas.forEach((area) => { area.widgets = area.data; - area.widgets.forEach(function (widget) { + area.widgets.forEach((widget) => { if (widget && widget.data && Array.isArray(widget.data.groups) && widget.data.groups.includes(oldName)) { widget.data.groups.splice(widget.data.groups.indexOf(oldName), 1, newName); } diff --git a/src/install.js b/src/install.js index 969d32c4c4..b802df977c 100644 --- a/src/install.js +++ b/src/install.js @@ -131,7 +131,7 @@ async function setupConfig() { const postgresQuestions = require('./database/postgres').questions; const allQuestions = questions.main.concat(questions.optional).concat(redisQuestions).concat(mongoQuestions).concat(postgresQuestions); - allQuestions.forEach(function (question) { + allQuestions.forEach((question) => { if (install.values.hasOwnProperty(question.name)) { config[question.name] = install.values[question.name]; } else if (question.hasOwnProperty('default')) { diff --git a/src/languages.js b/src/languages.js index ab471aea01..577db5e254 100644 --- a/src/languages.js +++ b/src/languages.js @@ -43,7 +43,7 @@ Languages.list = async function () { const codes = await Languages.listCodes(); - let languages = await Promise.all(codes.map(async function (folder) { + let languages = await Promise.all(codes.map(async (folder) => { try { const configPath = path.join(languagesPath, folder, 'language.json'); const file = await fs.promises.readFile(configPath, 'utf8'); diff --git a/src/logger.js b/src/logger.js index 6a1d549cb7..88e8abf577 100644 --- a/src/logger.js +++ b/src/logger.js @@ -87,7 +87,7 @@ Logger.open = function (value) { } if (stream) { - stream.on('error', function (err) { + stream.on('error', (err) => { winston.error(err.stack); }); } diff --git a/src/messaging/data.js b/src/messaging/data.js index b6efc27518..4486a4c82b 100644 --- a/src/messaging/data.js +++ b/src/messaging/data.js @@ -45,7 +45,7 @@ module.exports = function (Messaging) { let messages = await Messaging.getMessagesFields(mids, []); messages = await user.blocks.filter(uid, 'fromuid', messages); messages = messages - .map(function (msg, idx) { + .map((msg, idx) => { if (msg) { msg.messageId = parseInt(mids[idx], 10); msg.ip = undefined; @@ -59,7 +59,7 @@ module.exports = function (Messaging) { ['uid', 'username', 'userslug', 'picture', 'status', 'banned'] ); - messages.forEach(function (message, index) { + messages.forEach((message, index) => { message.fromUser = users[index]; message.fromUser.banned = !!message.fromUser.banned; message.fromUser.deleted = message.fromuid !== message.fromUser.uid && message.fromUser.uid === 0; @@ -88,7 +88,7 @@ module.exports = function (Messaging) { if (messages.length > 1) { // Add a spacer in between messages with time gaps between them - messages = messages.map(function (message, index) { + messages = messages.map((message, index) => { // Compare timestamps with the previous message, and check if a spacer needs to be added if (index > 0 && message.timestamp > messages[index - 1].timestamp + Messaging.newMessageCutoff) { // If it's been 5 minutes, this is a new set of messages diff --git a/src/messaging/delete.js b/src/messaging/delete.js index e23e20175d..341bafda6b 100644 --- a/src/messaging/delete.js +++ b/src/messaging/delete.js @@ -20,7 +20,7 @@ module.exports = function (Messaging) { Messaging.getMessagesData([mid], uid, roomId, true), ]); - uids.forEach(function (_uid) { + uids.forEach((_uid) => { if (parseInt(_uid, 10) !== parseInt(uid, 10)) { if (state === 1) { sockets.in(`uid_${_uid}`).emit('event:chats.delete', mid); diff --git a/src/messaging/edit.js b/src/messaging/edit.js index a5c43b769b..aa694f14c7 100644 --- a/src/messaging/edit.js +++ b/src/messaging/edit.js @@ -32,7 +32,7 @@ module.exports = function (Messaging) { Messaging.getMessagesData([mid], uid, roomId, true), ]); - uids.forEach(function (uid) { + uids.forEach((uid) => { sockets.in(`uid_${uid}`).emit('event:chats.edit', { messages: messages, }); diff --git a/src/messaging/index.js b/src/messaging/index.js index 8b0d0b57c1..793752c40f 100644 --- a/src/messaging/index.js +++ b/src/messaging/index.js @@ -36,13 +36,13 @@ Messaging.getMessages = async (params) => { if (!mids.length) { return []; } - mids.forEach(function (mid, index) { + mids.forEach((mid, index) => { indices[mid] = start + index; }); mids.reverse(); const messageData = await Messaging.getMessagesData(mids, params.uid, params.roomId, isNew); - messageData.forEach(function (messageData) { + messageData.forEach((messageData) => { messageData.index = indices[messageData.messageId.toString()]; messageData.isOwner = messageData.fromuid === parseInt(params.uid, 10); if (messageData.deleted && !messageData.isOwner) { @@ -106,21 +106,19 @@ Messaging.getRecentChats = async (callerUid, uid, start, stop) => { teasers: Promise.all(roomIds.map(async roomId => Messaging.getTeaser(uid, roomId))), }); - results.roomData.forEach(function (room, index) { + results.roomData.forEach((room, index) => { if (room) { room.users = results.users[index]; room.groupChat = room.hasOwnProperty('groupChat') ? room.groupChat : room.users.length > 2; room.unread = results.unread[index]; room.teaser = results.teasers[index]; - room.users.forEach(function (userData) { + room.users.forEach((userData) => { if (userData && parseInt(userData.uid, 10)) { userData.status = user.getStatus(userData); } }); - room.users = room.users.filter(function (user) { - return user && parseInt(user.uid, 10); - }); + room.users = room.users.filter(user => user && parseInt(user.uid, 10)); room.lastUser = room.users[0]; room.usernames = Messaging.generateUsernames(room.users, uid); @@ -254,9 +252,7 @@ Messaging.hasPrivateChat = async (uid, withUid) => { myRooms: db.getSortedSetRevRange(`uid:${uid}:chat:rooms`, 0, -1), theirRooms: db.getSortedSetRevRange(`uid:${withUid}:chat:rooms`, 0, -1), }); - const roomIds = results.myRooms.filter(function (roomId) { - return roomId && results.theirRooms.includes(roomId); - }); + const roomIds = results.myRooms.filter(roomId => roomId && results.theirRooms.includes(roomId)); if (!roomIds.length) { return 0; diff --git a/src/messaging/notifications.js b/src/messaging/notifications.js index 2e6c6467c4..748fd2799c 100644 --- a/src/messaging/notifications.js +++ b/src/messaging/notifications.js @@ -25,7 +25,7 @@ module.exports = function (Messaging) { } uids = data.uids; - uids.forEach(function (uid) { + uids.forEach((uid) => { data.self = parseInt(uid, 10) === parseInt(fromUid, 10) ? 1 : 0; Messaging.pushUnreadCount(uid); sockets.in(`uid_${uid}`).emit('event:chats.receive', data); @@ -45,7 +45,7 @@ module.exports = function (Messaging) { Messaging.notifyQueue[`${fromUid}:${roomId}`] = queueObj; } - queueObj.timeout = setTimeout(function () { + queueObj.timeout = setTimeout(() => { sendNotifications(fromUid, uids, roomId, queueObj.message); }, (parseFloat(meta.config.notificationSendDelay) || 60) * 1000); }; diff --git a/src/messaging/rooms.js b/src/messaging/rooms.js index ed322ff4a4..8eca129412 100644 --- a/src/messaging/rooms.js +++ b/src/messaging/rooms.js @@ -26,7 +26,7 @@ module.exports = function (Messaging) { }; function modifyRoomData(rooms) { - rooms.forEach(function (data) { + rooms.forEach((data) => { if (data) { data.roomName = data.roomName || ''; data.roomName = validator.escape(String(data.roomName)); @@ -170,7 +170,7 @@ module.exports = function (Messaging) { db.getObjectField(`chat:room:${roomId}`, 'owner'), ]); - return users.map(function (user) { + return users.map((user) => { user.isOwner = parseInt(user.uid, 10) === parseInt(ownerId, 10); return user; }); @@ -236,9 +236,7 @@ module.exports = function (Messaging) { var room = roomData; room.messages = messages; room.isOwner = parseInt(room.owner, 10) === parseInt(uid, 10); - room.users = users.filter(function (user) { - return user && parseInt(user.uid, 10) && parseInt(user.uid, 10) !== parseInt(uid, 10); - }); + room.users = users.filter(user => user && parseInt(user.uid, 10) && parseInt(user.uid, 10) !== parseInt(uid, 10)); room.canReply = canReply; room.groupChat = room.hasOwnProperty('groupChat') ? room.groupChat : users.length > 2; room.usernames = Messaging.generateUsernames(users, uid); diff --git a/src/meta/aliases.js b/src/meta/aliases.js index a8be48da3c..4224dc0c3d 100644 --- a/src/meta/aliases.js +++ b/src/meta/aliases.js @@ -23,16 +23,14 @@ exports.aliases = aliases; function buildTargets() { var length = 0; - var output = Object.keys(aliases).map(function (name) { + var output = Object.keys(aliases).map((name) => { var arr = aliases[name]; if (name.length > length) { length = name.length; } return [name, arr.join(', ')]; - }).map(function (tuple) { - return ` ${_.padEnd(`"${tuple[0]}"`, length + 2).magenta} | ${tuple[1]}`; - }).join('\n'); + }).map(tuple => ` ${_.padEnd(`"${tuple[0]}"`, length + 2).magenta} | ${tuple[1]}`).join('\n'); console.log( `\n\n Build targets:\n${ (`\n ${_.padEnd('Target', length + 2)} | Aliases`).green diff --git a/src/meta/blacklist.js b/src/meta/blacklist.js index 8fca8830d4..638795ae8c 100644 --- a/src/meta/blacklist.js +++ b/src/meta/blacklist.js @@ -64,7 +64,7 @@ Blacklist.test = async function (clientIp) { if ( !Blacklist._rules.ipv4.includes(clientIp) && // not explicitly specified in ipv4 list !Blacklist._rules.ipv6.includes(clientIp) && // not explicitly specified in ipv6 list - !Blacklist._rules.cidr.some(function (subnet) { + !Blacklist._rules.cidr.some((subnet) => { var cidr = ipaddr.parseCIDR(subnet); if (addr.kind() !== cidr[0].kind()) { return false; @@ -101,7 +101,7 @@ Blacklist.validate = function (rules) { // Filter out blank lines and lines starting with the hash character (comments) // Also trim inputs and remove inline comments - rules = rules.map(function (rule) { + rules = rules.map((rule) => { rule = rule.replace(inlineCommentMatch, '').trim(); return rule.length && !rule.startsWith('#') ? rule : null; }).filter(Boolean); @@ -112,7 +112,7 @@ Blacklist.validate = function (rules) { rules = uniqRules; // Filter out invalid rules - rules = rules.filter(function (rule) { + rules = rules.filter((rule) => { var addr; var isRange = false; try { diff --git a/src/meta/build.js b/src/meta/build.js index 2f0346afc2..9b3b7ea6fb 100644 --- a/src/meta/build.js +++ b/src/meta/build.js @@ -49,9 +49,9 @@ const targetHandlers = { }, }; -const aliasMap = Object.keys(aliases).reduce(function (prev, key) { +const aliasMap = Object.keys(aliases).reduce((prev, key) => { var arr = aliases[key]; - arr.forEach(function (alias) { + arr.forEach((alias) => { prev[alias] = key; }); prev[key] = key; @@ -75,9 +75,7 @@ async function beforeBuild(targets) { } } -const allTargets = Object.keys(targetHandlers).filter(function (name) { - return typeof targetHandlers[name] === 'function'; -}); +const allTargets = Object.keys(targetHandlers).filter(name => typeof targetHandlers[name] === 'function'); async function buildTargets(targets, parallel) { const length = Math.max.apply(Math, targets.map(name => name.length)); @@ -132,7 +130,7 @@ exports.build = async function (targets, options) { targets = targets // get full target name - .map(function (target) { + .map((target) => { target = target.toLowerCase().replace(/-/g, ''); if (!aliasMap[target]) { winston.warn(`[build] Unknown target: ${target}`); diff --git a/src/meta/configs.js b/src/meta/configs.js index e32d4b6ee8..d72caa2f46 100644 --- a/src/meta/configs.js +++ b/src/meta/configs.js @@ -21,7 +21,7 @@ Meta.config = {}; // called after data is loaded from db function deserialize(config) { const deserialized = {}; - Object.keys(config).forEach(function (key) { + Object.keys(config).forEach((key) => { const defaultType = typeof defaults[key]; const type = typeof config[key]; const number = parseFloat(config[key]); @@ -59,7 +59,7 @@ function deserialize(config) { // called before data is saved to db function serialize(config) { const serialized = {}; - Object.keys(config).forEach(function (key) { + Object.keys(config).forEach((key) => { const defaultType = typeof defaults[key]; const type = typeof config[key]; const number = parseFloat(config[key]); @@ -290,7 +290,7 @@ function updateLocalConfig(config) { Object.assign(Meta.config, config); } -pubsub.on('config:update', function onConfigReceived(config) { +pubsub.on('config:update', (config) => { if (typeof config === 'object' && Meta.config) { updateLocalConfig(config); } diff --git a/src/meta/css.js b/src/meta/css.js index d270856f6e..aa8d36b254 100644 --- a/src/meta/css.js +++ b/src/meta/css.js @@ -34,9 +34,7 @@ const buildImports = { '@import "../../public/less/mixins.less";', '@import "../../public/less/global.less";', '@import "../../public/less/modals.less";', - ].map(function (str) { - return str.replace(/\//g, path.sep); - }).join('\n')}`; + ].map(str => str.replace(/\//g, path.sep)).join('\n')}`; }, admin: function (source) { return `${source}\n${[ @@ -46,9 +44,7 @@ const buildImports = { '@import "../../public/less/jquery-ui.less";', '@import (inline) "../node_modules/@adactive/bootstrap-tagsinput/src/bootstrap-tagsinput.css";', '@import (inline) "../public/vendor/mdl/material.css";', - ].map(function (str) { - return str.replace(/\//g, path.sep); - }).join('\n')}`; + ].map(str => str.replace(/\//g, path.sep)).join('\n')}`; }, }; @@ -69,16 +65,16 @@ async function getImports(files, prefix, extension) { const pluginDirectories = []; let source = ''; - files.forEach(function (styleFile) { + files.forEach((styleFile) => { if (styleFile.endsWith(extension)) { source += `${prefix + path.sep + styleFile}";`; } else { pluginDirectories.push(styleFile); } }); - await Promise.all(pluginDirectories.map(async function (directory) { + await Promise.all(pluginDirectories.map(async (directory) => { const styleFiles = await file.walk(directory); - styleFiles.forEach(function (styleFile) { + styleFiles.forEach((styleFile) => { source += `${prefix + path.sep + styleFile}";`; }); })); diff --git a/src/meta/debugFork.js b/src/meta/debugFork.js index e3ccc68e0d..6756ade770 100644 --- a/src/meta/debugFork.js +++ b/src/meta/debugFork.js @@ -2,9 +2,7 @@ var fork = require('child_process').fork; -var debugArg = process.execArgv.find(function (arg) { - return /^--(debug|inspect)/.test(arg); -}); +var debugArg = process.execArgv.find(arg => /^--(debug|inspect)/.test(arg)); var debugging = !!debugArg; debugArg = debugArg ? debugArg.replace('-brk', '').split('=') : ['--debug', 5859]; diff --git a/src/meta/errors.js b/src/meta/errors.js index 763c736d5d..843051e310 100644 --- a/src/meta/errors.js +++ b/src/meta/errors.js @@ -11,9 +11,9 @@ const Errors = module.exports; let counters = {}; -new cronJob('0 * * * * *', function () { +new cronJob('0 * * * * *', (() => { Errors.writeData(); -}, null, true); +}), null, true); Errors.writeData = async function () { try { @@ -45,7 +45,7 @@ Errors.log404 = function (route) { Errors.get = async function (escape) { const data = await db.getSortedSetRevRangeWithScores('errors:404', 0, 199); - data.forEach(function (nfObject) { + data.forEach((nfObject) => { nfObject.value = escape ? validator.escape(String(nfObject.value || '')) : nfObject.value; }); return data; diff --git a/src/meta/index.js b/src/meta/index.js index 326cfb8bf7..a45a07475b 100644 --- a/src/meta/index.js +++ b/src/meta/index.js @@ -38,7 +38,7 @@ Meta.userOrGroupExists = async function (slug) { }; if (nconf.get('isPrimary')) { - pubsub.on('meta:restart', function (data) { + pubsub.on('meta:restart', (data) => { if (data.hostname !== os.hostname()) { restart(); } diff --git a/src/meta/js.js b/src/meta/js.js index 33f1bf059f..eaabb77b98 100644 --- a/src/meta/js.js +++ b/src/meta/js.js @@ -116,7 +116,7 @@ async function linkIfLinux(srcPath, destPath) { const basePath = path.resolve(__dirname, '../..'); async function minifyModules(modules, fork) { - const moduleDirs = modules.reduce(function (prev, mod) { + const moduleDirs = modules.reduce((prev, mod) => { const dir = path.resolve(path.dirname(mod.destPath)); if (!prev.includes(dir)) { prev.push(dir); @@ -126,7 +126,7 @@ async function minifyModules(modules, fork) { await Promise.all(moduleDirs.map(dir => mkdirp(dir))); - const filtered = modules.reduce(function (prev, mod) { + const filtered = modules.reduce((prev, mod) => { if (mod.srcPath.endsWith('.min.js') || path.dirname(mod.srcPath).endsWith('min')) { prev.skip.push(mod); } else { @@ -145,7 +145,7 @@ async function minifyModules(modules, fork) { async function linkModules() { const modules = JS.scripts.modules; - await Promise.all(Object.keys(modules).map(async function (relPath) { + await Promise.all(Object.keys(modules).map(async (relPath) => { const srcPath = path.join(__dirname, '../../', modules[relPath]); const destPath = path.join(__dirname, '../../build/public/src/modules', relPath); const [stats] = await Promise.all([ @@ -165,24 +165,20 @@ async function linkModules() { const moduleDirs = ['modules', 'admin', 'client']; async function getModuleList() { - let modules = Object.keys(JS.scripts.modules).map(function (relPath) { - return { - srcPath: path.join(__dirname, '../../', JS.scripts.modules[relPath]), - destPath: path.join(__dirname, '../../build/public/src/modules', relPath), - }; - }); + let modules = Object.keys(JS.scripts.modules).map(relPath => ({ + srcPath: path.join(__dirname, '../../', JS.scripts.modules[relPath]), + destPath: path.join(__dirname, '../../build/public/src/modules', relPath), + })); - const coreDirs = moduleDirs.map(function (dir) { - return { - srcPath: path.join(__dirname, '../../public/src', dir), - destPath: path.join(__dirname, '../../build/public/src', dir), - }; - }); + const coreDirs = moduleDirs.map(dir => ({ + srcPath: path.join(__dirname, '../../public/src', dir), + destPath: path.join(__dirname, '../../build/public/src', dir), + })); modules = modules.concat(coreDirs); const moduleFiles = []; - await Promise.all(modules.map(async function (module) { + await Promise.all(modules.map(async (module) => { const srcPath = module.srcPath; const destPath = module.destPath; @@ -196,16 +192,14 @@ async function getModuleList() { const mods = files.filter( filePath => path.extname(filePath) === '.js' - ).map(function (filePath) { - return { - srcPath: path.normalize(filePath), - destPath: path.join(destPath, path.relative(srcPath, filePath)), - }; - }); + ).map(filePath => ({ + srcPath: path.normalize(filePath), + destPath: path.join(destPath, path.relative(srcPath, filePath)), + })); moduleFiles.push(...mods); })); - moduleFiles.forEach(function (mod) { + moduleFiles.forEach((mod) => { mod.filename = path.relative(basePath, mod.srcPath).replace(/\\/g, '/'); }); return moduleFiles; @@ -265,7 +259,7 @@ async function requirejsOptimize(target) { ], client: [], }; - const optimizeAsync = util.promisify(function (config, cb) { + const optimizeAsync = util.promisify((config, cb) => { requirejs.optimize(config, () => cb(), err => cb(err)); }); @@ -282,7 +276,7 @@ async function requirejsOptimize(target) { JS.linkStatics = async function () { await rimrafAsync(path.join(__dirname, '../../build/public/plugins')); - await Promise.all(Object.keys(plugins.staticDirs).map(async function (mappedPath) { + await Promise.all(Object.keys(plugins.staticDirs).map(async (mappedPath) => { const sourceDir = plugins.staticDirs[mappedPath]; const destDir = path.join(__dirname, '../../build/public/plugins', mappedPath); @@ -297,7 +291,7 @@ async function getBundleScriptList(target) { if (target === 'admin') { target = 'acp'; } - let pluginScripts = plugins[`${target}Scripts`].filter(function (path) { + let pluginScripts = plugins[`${target}Scripts`].filter((path) => { if (path.endsWith('.js')) { return true; } @@ -306,7 +300,7 @@ async function getBundleScriptList(target) { return false; }); - await Promise.all(pluginDirectories.map(async function (directory) { + await Promise.all(pluginDirectories.map(async (directory) => { const scripts = await file.walk(directory); pluginScripts = pluginScripts.concat(scripts); })); @@ -319,7 +313,7 @@ async function getBundleScriptList(target) { scripts = scripts.concat(JS.scripts.admin); } - scripts = scripts.concat(pluginScripts).map(function (script) { + scripts = scripts.concat(pluginScripts).map((script) => { const srcPath = path.resolve(basePath, script).replace(/\\/g, '/'); return { srcPath: srcPath, diff --git a/src/meta/languages.js b/src/meta/languages.js index a1ab2e22bb..f6133a5e88 100644 --- a/src/meta/languages.js +++ b/src/meta/languages.js @@ -24,7 +24,7 @@ async function getTranslationMetadata() { let languages = []; let namespaces = []; - paths.forEach(function (p) { + paths.forEach((p) => { if (!p.endsWith('.json')) { return; } @@ -73,14 +73,12 @@ async function writeLanguageFile(language, namespace, translations) { async function buildTranslations(ref) { const namespaces = ref.namespaces; const languages = ref.languages; - const plugins = _.values(Plugins.pluginsData).filter(function (plugin) { - return typeof plugin.languages === 'string'; - }); + const plugins = _.values(Plugins.pluginsData).filter(plugin => typeof plugin.languages === 'string'); const promises = []; - namespaces.forEach(function (namespace) { - languages.forEach(function (language) { + namespaces.forEach((namespace) => { + languages.forEach((language) => { promises.push(buildNamespaceLanguage(language, namespace, plugins)); }); }); diff --git a/src/meta/minifier.js b/src/meta/minifier.js index 10a383be3a..0d27a602dd 100644 --- a/src/meta/minifier.js +++ b/src/meta/minifier.js @@ -37,7 +37,7 @@ Object.defineProperty(Minifier, 'maxThreads', { Minifier.maxThreads = os.cpus().length - 1; Minifier.killAll = function () { - pool.forEach(function (child) { + pool.forEach((child) => { child.kill('SIGTERM'); }); @@ -76,7 +76,7 @@ function removeChild(proc) { function forkAction(action, callback) { var proc = getChild(); - proc.on('message', function (message) { + proc.on('message', (message) => { freeChild(proc); if (message.type === 'error') { @@ -87,7 +87,7 @@ function forkAction(action, callback) { callback(null, message.result); } }); - proc.on('error', function (err) { + proc.on('error', (err) => { proc.kill(); removeChild(proc); callback(err); @@ -102,7 +102,7 @@ function forkAction(action, callback) { var actions = {}; if (process.env.minifier_child) { - process.on('message', function (message) { + process.on('message', (message) => { if (message.type === 'action') { var action = message.action; if (typeof actions[action.act] !== 'function') { @@ -113,7 +113,7 @@ if (process.env.minifier_child) { return; } - actions[action.act](action, function (err, result) { + actions[action.act](action, (err, result) => { if (err) { process.send({ type: 'error', @@ -144,15 +144,15 @@ function executeAction(action, fork, callback) { function concat(data, callback) { if (data.files && data.files.length) { - async.mapLimit(data.files, 1000, function (ref, next) { - fs.readFile(ref.srcPath, 'utf8', function (err, file) { + async.mapLimit(data.files, 1000, (ref, next) => { + fs.readFile(ref.srcPath, 'utf8', (err, file) => { if (err) { return next(err); } next(null, file); }); - }, function (err, files) { + }, (err, files) => { if (err) { return callback(err); } @@ -169,8 +169,8 @@ function concat(data, callback) { actions.concat = concat; function minifyJS_batch(data, callback) { - async.eachLimit(data.files, 100, function (fileObj, next) { - fs.readFile(fileObj.srcPath, 'utf8', function (err, source) { + async.eachLimit(data.files, 100, (fileObj, next) => { + fs.readFile(fileObj.srcPath, 'utf8', (err, source) => { if (err) { return next(err); } @@ -193,8 +193,8 @@ function minifyJS_batch(data, callback) { actions.minifyJS_batch = minifyJS_batch; function minifyJS(data, callback) { - async.mapLimit(data.files, 1000, function (fileObj, next) { - fs.readFile(fileObj.srcPath, 'utf8', function (err, source) { + async.mapLimit(data.files, 1000, (fileObj, next) => { + fs.readFile(fileObj.srcPath, 'utf8', (err, source) => { if (err) { return next(err); } @@ -205,7 +205,7 @@ function minifyJS(data, callback) { source: source, }); }); - }, function (err, filesToMinify) { + }, (err, filesToMinify) => { if (err) { return callback(err); } @@ -221,7 +221,7 @@ actions.minifyJS = minifyJS; function minifyAndSave(data, callback) { var scripts = {}; - data.files.forEach(function (ref) { + data.files.forEach((ref) => { if (!ref) { return; } @@ -269,7 +269,7 @@ function buildCSS(data, callback) { less.render(data.source, { paths: data.paths, javascriptEnabled: true, - }, function (err, lessOutput) { + }, (err, lessOutput) => { if (err) { // display less parser errors properly return callback(new Error(String(err))); @@ -282,9 +282,9 @@ function buildCSS(data, callback) { }), ] : [autoprefixer]).process(lessOutput.css, { from: undefined, - }).then(function (result) { + }).then((result) => { process.nextTick(callback, null, { code: result.css }); - }).catch(function (err) { + }).catch((err) => { process.nextTick(callback, err); }); }); diff --git a/src/meta/settings.js b/src/meta/settings.js index e001f4cad4..4936f9348c 100644 --- a/src/meta/settings.js +++ b/src/meta/settings.js @@ -16,7 +16,7 @@ Settings.get = async function (hash) { let data = await db.getObject(`settings:${hash}`) || {}; const sortedLists = await db.getSetMembers(`settings:${hash}:sorted-lists`); - await Promise.all(sortedLists.map(async function (list) { + await Promise.all(sortedLists.map(async (list) => { const members = await db.getSortedSetRange(`settings:${hash}:sorted-list:${list}`, 0, -1) || []; const keys = []; @@ -26,7 +26,7 @@ Settings.get = async function (hash) { } const objects = await db.getObjects(keys); - objects.forEach(function (obj) { + objects.forEach((obj) => { data[list].push(obj); }); })); @@ -62,7 +62,7 @@ Settings.set = async function (hash, values, quiet) { await db.setRemove(`settings:${hash}:sorted-lists`, sortedLists.filter(list => !sortedListData[list].length)); await db.setAdd(`settings:${hash}:sorted-lists`, sortedLists); - await Promise.all(sortedLists.map(async function (list) { + await Promise.all(sortedLists.map(async (list) => { const numItems = await db.sortedSetCard(`settings:${hash}:sorted-list:${list}`); const deleteKeys = [`settings:${hash}:sorted-list:${list}`]; for (let x = 0; x < numItems; x++) { @@ -72,9 +72,9 @@ Settings.set = async function (hash, values, quiet) { })); const ops = []; - sortedLists.forEach(function (list) { + sortedLists.forEach((list) => { const arr = sortedListData[list]; - arr.forEach(function (data, order) { + arr.forEach((data, order) => { ops.push(db.sortedSetAdd(`settings:${hash}:sorted-list:${list}`, order, order)); ops.push(db.setObject(`settings:${hash}:sorted-list:${list}:${order}`, data)); }); @@ -108,7 +108,7 @@ Settings.setOnEmpty = async function (hash, values) { const settings = await Settings.get(hash) || {}; const empty = {}; - Object.keys(values).forEach(function (key) { + Object.keys(values).forEach((key) => { if (!settings.hasOwnProperty(key)) { empty[key] = values[key]; } diff --git a/src/meta/tags.js b/src/meta/tags.js index 2636bc5f9e..7d0a50c024 100644 --- a/src/meta/tags.js +++ b/src/meta/tags.js @@ -144,7 +144,7 @@ Tags.parse = async (req, data, meta, link) => { links: plugins.hooks.fire('filter:meta.getLinkTags', { req: req, data: data, links: defaultLinks }), }); - meta = results.tags.tags.concat(meta || []).map(function (tag) { + meta = results.tags.tags.concat(meta || []).map((tag) => { if (!tag || typeof tag.content !== 'string') { winston.warn('Invalid meta tag. ', tag); return tag; @@ -175,7 +175,7 @@ Tags.parse = async (req, data, meta, link) => { function addIfNotExists(meta, keyName, tagName, value) { var exists = false; - meta.forEach(function (tag) { + meta.forEach((tag) => { if (tag[keyName] === tagName) { exists = true; } diff --git a/src/meta/templates.js b/src/meta/templates.js index 44ba0f9bab..8948115982 100644 --- a/src/meta/templates.js +++ b/src/meta/templates.js @@ -46,7 +46,7 @@ async function processImports(paths, templatePath, source) { Templates.processImports = processImports; async function getTemplateDirs(activePlugins) { - const pluginTemplates = activePlugins.map(function (id) { + const pluginTemplates = activePlugins.map((id) => { if (themeNamePattern.test(id)) { return nconf.get('theme_templates_path'); } @@ -83,20 +83,16 @@ async function getTemplateDirs(activePlugins) { async function getTemplateFiles(dirs) { const buckets = await Promise.all(dirs.map(async (dir) => { let files = await file.walk(dir); - files = files.filter(function (path) { - return path.endsWith('.tpl'); - }).map(function (file) { - return { - name: path.relative(dir, file).replace(/\\/g, '/'), - path: file, - }; - }); + files = files.filter(path => path.endsWith('.tpl')).map(file => ({ + name: path.relative(dir, file).replace(/\\/g, '/'), + path: file, + })); return files; })); var dict = {}; - buckets.forEach(function (files) { - files.forEach(function (file) { + buckets.forEach((files) => { + files.forEach((file) => { dict[file.name] = file.path; }); }); @@ -106,7 +102,7 @@ async function getTemplateFiles(dirs) { async function compileTemplate(filename, source) { let paths = await file.walk(viewsPath); - paths = _.fromPairs(paths.map(function (p) { + paths = _.fromPairs(paths.map((p) => { var relative = path.relative(viewsPath, p).replace(/\\/g, '/'); return [relative, p]; })); diff --git a/src/meta/themes.js b/src/meta/themes.js index d20cd77af4..3a4865a1cd 100644 --- a/src/meta/themes.js +++ b/src/meta/themes.js @@ -145,9 +145,7 @@ Themes.setupPaths = async () => { winston.info(`[themes] Using theme ${themeId}`); } - var themeObj = data.themesData.find(function (themeObj) { - return themeObj.id === themeId; - }); + var themeObj = data.themesData.find(themeObj => themeObj.id === themeId); if (!themeObj) { throw new Error('[[error:theme-not-found]]'); diff --git a/src/middleware/admin.js b/src/middleware/admin.js index 28100dbbb3..024f8aac25 100644 --- a/src/middleware/admin.js +++ b/src/middleware/admin.js @@ -20,7 +20,7 @@ var controllers = { const middleware = module.exports; -middleware.buildHeader = helpers.try(async function (req, res, next) { +middleware.buildHeader = helpers.try(async (req, res, next) => { res.locals.renderAdminHeader = true; res.locals.config = await controllers.api.loadConfig(req); next(); @@ -48,7 +48,7 @@ middleware.renderHeader = async (req, res, data) => { userData.privileges = results.privileges; var acpPath = req.path.slice(1).split('/'); - acpPath.forEach(function (path, i) { + acpPath.forEach((path, i) => { acpPath[i] = path.charAt(0).toUpperCase() + path.slice(1); }); acpPath = acpPath.join(' > '); @@ -90,9 +90,7 @@ middleware.renderHeader = async (req, res, data) => { async function getAdminScripts() { const scripts = await plugins.hooks.fire('filter:admin.scripts.get', []); - return scripts.map(function (script) { - return { src: script }; - }); + return scripts.map(script => ({ src: script })); } async function getLatestVersion() { diff --git a/src/middleware/header.js b/src/middleware/header.js index 7157c831d9..677cd11eb0 100644 --- a/src/middleware/header.js +++ b/src/middleware/header.js @@ -29,7 +29,7 @@ const middleware = module.exports; const relative_path = nconf.get('relative_path'); -middleware.buildHeader = helpers.try(async function buildHeader(req, res, next) { +middleware.buildHeader = helpers.try(async (req, res, next) => { res.locals.renderHeader = true; res.locals.isAPI = false; const [config, canLoginIfBanned] = await Promise.all([ @@ -184,14 +184,14 @@ async function appendUnreadCounts({ uid, navigation, unreadData }) { flags: results.unreadFlagCount || 0, }; - Object.keys(unreadCount).forEach(function (key) { + Object.keys(unreadCount).forEach((key) => { if (unreadCount[key] > 99) { unreadCount[key] = '99+'; } }); const tidsByFilter = results.unreadData.tidsByFilter; - navigation = navigation.map(function (item) { + navigation = navigation.map((item) => { function modifyNavItem(item, route, filter, content) { if (item && item.originalRoute === route) { unreadData[filter] = _.zipObject(tidsByFilter[filter], tidsByFilter[filter].map(() => true)); @@ -228,9 +228,7 @@ middleware.renderFooter = async function renderFooter(req, res, templateValues) const scripts = await plugins.hooks.fire('filter:scripts.get', []); - data.templateValues.scripts = scripts.map(function (script) { - return { src: script }; - }); + data.templateValues.scripts = scripts.map(script => ({ src: script })); data.templateValues.useCustomJS = meta.config.useCustomJS; data.templateValues.customJS = data.templateValues.useCustomJS ? meta.config.customJS : ''; @@ -244,7 +242,7 @@ function modifyTitle(obj) { obj.browserTitle = title; if (obj.metaTags) { - obj.metaTags.forEach(function (tag, i) { + obj.metaTags.forEach((tag, i) => { if (tag.property === 'og:title') { obj.metaTags[i].content = title; } diff --git a/src/middleware/headers.js b/src/middleware/headers.js index f68c371d2d..6d46e8f21a 100644 --- a/src/middleware/headers.js +++ b/src/middleware/headers.js @@ -9,7 +9,7 @@ const languages = require('../languages'); const helpers = require('./helpers'); module.exports = function (middleware) { - middleware.addHeaders = helpers.try(function addHeaders(req, res, next) { + middleware.addHeaders = helpers.try((req, res, next) => { const headers = { 'X-Powered-By': encodeURI(meta.config['powered-by'] || 'NodeBB'), 'Access-Control-Allow-Methods': encodeURI(meta.config['access-control-allow-methods'] || ''), @@ -28,9 +28,7 @@ module.exports = function (middleware) { if (meta.config['access-control-allow-origin']) { let origins = meta.config['access-control-allow-origin'].split(','); - origins = origins.map(function (origin) { - return origin && origin.trim(); - }); + origins = origins.map(origin => origin && origin.trim()); if (origins.includes(req.get('origin'))) { headers['Access-Control-Allow-Origin'] = encodeURI(req.get('origin')); @@ -40,7 +38,7 @@ module.exports = function (middleware) { if (meta.config['access-control-allow-origin-regex']) { let originsRegex = meta.config['access-control-allow-origin-regex'].split(','); - originsRegex = originsRegex.map(function (origin) { + originsRegex = originsRegex.map((origin) => { try { origin = new RegExp(origin.trim()); } catch (err) { @@ -50,7 +48,7 @@ module.exports = function (middleware) { return origin; }); - originsRegex.forEach(function (regex) { + originsRegex.forEach((regex) => { if (regex && regex.test(req.get('origin'))) { headers['Access-Control-Allow-Origin'] = encodeURI(req.get('origin')); headers.Vary = headers.Vary ? `${headers.Vary}, Origin` : 'Origin'; @@ -75,7 +73,7 @@ module.exports = function (middleware) { next(); }); - middleware.autoLocale = helpers.try(async function autoLocale(req, res, next) { + middleware.autoLocale = helpers.try(async (req, res, next) => { let langs; if (req.query.lang) { langs = await listCodes(); diff --git a/src/middleware/index.js b/src/middleware/index.js index 7571d3fca2..203f84454f 100644 --- a/src/middleware/index.js +++ b/src/middleware/index.js @@ -73,7 +73,7 @@ middleware.stripLeadingSlashes = function stripLeadingSlashes(req, res, next) { next(); }; -middleware.pageView = helpers.try(async function pageView(req, res, next) { +middleware.pageView = helpers.try(async (req, res, next) => { if (req.loggedIn) { await Promise.all([ user.updateOnlineUsers(req.uid), @@ -85,9 +85,9 @@ middleware.pageView = helpers.try(async function pageView(req, res, next) { plugins.hooks.fire('action:middleware.pageView', { req: req }); }); -middleware.pluginHooks = helpers.try(async function pluginHooks(req, res, next) { +middleware.pluginHooks = helpers.try(async (req, res, next) => { // TODO: Deprecate in v2.0 - await async.each(plugins.loadedHooks['filter:router.page'] || [], function (hookObj, next) { + await async.each(plugins.loadedHooks['filter:router.page'] || [], (hookObj, next) => { hookObj.method(req, res, next); }); @@ -130,7 +130,7 @@ middleware.routeTouchIcon = function routeTouchIcon(req, res) { }); }; -middleware.privateTagListing = helpers.try(async function privateTagListing(req, res, next) { +middleware.privateTagListing = helpers.try(async (req, res, next) => { const canView = await privileges.global.can('view:tags', req.uid); if (!canView) { return controllers.helpers.notAllowed(req, res); @@ -138,11 +138,11 @@ middleware.privateTagListing = helpers.try(async function privateTagListing(req, next(); }); -middleware.exposeGroupName = helpers.try(async function exposeGroupName(req, res, next) { +middleware.exposeGroupName = helpers.try(async (req, res, next) => { await expose('groupName', groups.getGroupNameByGroupSlug, 'slug', req, res, next); }); -middleware.exposeUid = helpers.try(async function exposeUid(req, res, next) { +middleware.exposeUid = helpers.try(async (req, res, next) => { await expose('uid', user.getUidByUserslug, 'userslug', req, res, next); }); @@ -201,7 +201,7 @@ middleware.delayLoading = function delayLoading(req, res, next) { setTimeout(next, 1000); }; -middleware.buildSkinAsset = helpers.try(async function buildSkinAsset(req, res, next) { +middleware.buildSkinAsset = helpers.try(async (req, res, next) => { // If this middleware is reached, a skin was requested, so it is built on-demand const target = path.basename(req.originalUrl).match(/(client-[a-z]+)/); if (!target) { @@ -225,7 +225,7 @@ middleware.trimUploadTimestamps = function trimUploadTimestamps(req, res, next) next(); }; -middleware.validateAuth = helpers.try(async function validateAuth(req, res, next) { +middleware.validateAuth = helpers.try(async (req, res, next) => { try { await plugins.hooks.fire('static:auth.validate', { user: res.locals.user, diff --git a/src/middleware/maintenance.js b/src/middleware/maintenance.js index 2c7f4b9f0c..46fb05dcae 100644 --- a/src/middleware/maintenance.js +++ b/src/middleware/maintenance.js @@ -7,7 +7,7 @@ const user = require('../user'); const helpers = require('./helpers'); module.exports = function (middleware) { - middleware.maintenanceMode = helpers.try(async function maintenanceMode(req, res, next) { + middleware.maintenanceMode = helpers.try(async (req, res, next) => { if (!meta.config.maintenanceMode) { return next(); } diff --git a/src/middleware/render.js b/src/middleware/render.js index 36c098f3fc..ace5e9f256 100644 --- a/src/middleware/render.js +++ b/src/middleware/render.js @@ -85,8 +85,8 @@ module.exports = function (middleware) { }; async function renderContent(render, tpl, req, res, options) { - return new Promise(function (resolve, reject) { - render.call(res, tpl, options, async function (err, str) { + return new Promise((resolve, reject) => { + render.call(res, tpl, options, async (err, str) => { if (err) reject(err); else resolve(await translate(str, getLang(req, res))); }); @@ -121,7 +121,7 @@ module.exports = function (middleware) { function buildBodyClass(req, res, templateData) { const clean = req.path.replace(/^\/api/, '').replace(/^\/|\/$/g, ''); const parts = clean.split('/').slice(0, 3); - parts.forEach(function (p, index) { + parts.forEach((p, index) => { try { p = slugify(decodeURIComponent(p)); } catch (err) { @@ -137,7 +137,7 @@ module.exports = function (middleware) { parts.push(`page-topic-category-${slugify(templateData.category.name)}`); } if (templateData.breadcrumbs) { - templateData.breadcrumbs.forEach(function (crumb) { + templateData.breadcrumbs.forEach((crumb) => { if (crumb.hasOwnProperty('cid')) { parts.push(`parent-category-${crumb.cid}`); } diff --git a/src/middleware/user.js b/src/middleware/user.js index f6e6878bc7..1df25e7995 100644 --- a/src/middleware/user.js +++ b/src/middleware/user.js @@ -82,7 +82,7 @@ module.exports = function (middleware) { return !res.headersSent; } - middleware.authenticate = helpers.try(async function middlewareAuthenticate(req, res, next) { + middleware.authenticate = helpers.try(async (req, res, next) => { if (!await authenticate(req, res)) { return; } @@ -92,18 +92,18 @@ module.exports = function (middleware) { next(); }); - middleware.authenticateOrGuest = helpers.try(async function authenticateOrGuest(req, res, next) { + middleware.authenticateOrGuest = helpers.try(async (req, res, next) => { if (!await authenticate(req, res)) { return; } next(); }); - middleware.ensureSelfOrGlobalPrivilege = helpers.try(async function ensureSelfOrGlobalPrivilege(req, res, next) { + middleware.ensureSelfOrGlobalPrivilege = helpers.try(async (req, res, next) => { await ensureSelfOrMethod(user.isAdminOrGlobalMod, req, res, next); }); - middleware.ensureSelfOrPrivileged = helpers.try(async function ensureSelfOrPrivileged(req, res, next) { + middleware.ensureSelfOrPrivileged = helpers.try(async (req, res, next) => { await ensureSelfOrMethod(user.isPrivileged, req, res, next); }); @@ -126,7 +126,7 @@ module.exports = function (middleware) { return next(); } - middleware.canViewUsers = helpers.try(async function canViewUsers(req, res, next) { + middleware.canViewUsers = helpers.try(async (req, res, next) => { if (parseInt(res.locals.uid, 10) === req.uid) { return next(); } @@ -137,7 +137,7 @@ module.exports = function (middleware) { controllers.helpers.notAllowed(req, res); }); - middleware.canViewGroups = helpers.try(async function canViewGroups(req, res, next) { + middleware.canViewGroups = helpers.try(async (req, res, next) => { const canView = await privileges.global.can('view:groups', req.uid); if (canView) { return next(); @@ -145,7 +145,7 @@ module.exports = function (middleware) { controllers.helpers.notAllowed(req, res); }); - middleware.checkAccountPermissions = helpers.try(async function checkAccountPermissions(req, res, next) { + middleware.checkAccountPermissions = helpers.try(async (req, res, next) => { // This middleware ensures that only the requested user and admins can pass if (!await authenticate(req, res)) { return; @@ -168,7 +168,7 @@ module.exports = function (middleware) { controllers.helpers.notAllowed(req, res); }); - middleware.redirectToAccountIfLoggedIn = helpers.try(async function redirectToAccountIfLoggedIn(req, res, next) { + middleware.redirectToAccountIfLoggedIn = helpers.try(async (req, res, next) => { if (req.session.forceLogin || req.uid <= 0) { return next(); } @@ -176,7 +176,7 @@ module.exports = function (middleware) { controllers.helpers.redirect(res, `/user/${userslug}`); }); - middleware.redirectUidToUserslug = helpers.try(async function redirectUidToUserslug(req, res, next) { + middleware.redirectUidToUserslug = helpers.try(async (req, res, next) => { const uid = parseInt(req.params.uid, 10); if (uid <= 0) { return next(); @@ -187,11 +187,11 @@ module.exports = function (middleware) { } const path = req.path.replace(/^\/api/, '') .replace('uid', 'user') - .replace(uid, function () { return userslug; }); + .replace(uid, () => userslug); controllers.helpers.redirect(res, path); }); - middleware.redirectMeToUserslug = helpers.try(async function redirectMeToUserslug(req, res) { + middleware.redirectMeToUserslug = helpers.try(async (req, res) => { const userslug = await user.getUserField(req.uid, 'userslug'); if (!userslug) { return controllers.helpers.notAllowed(req, res); @@ -200,7 +200,7 @@ module.exports = function (middleware) { controllers.helpers.redirect(res, path); }); - middleware.isAdmin = helpers.try(async function isAdmin(req, res, next) { + middleware.isAdmin = helpers.try(async (req, res, next) => { // TODO: Remove in v1.16.0 winston.warn('[middleware] middleware.isAdmin deprecated, use middleware.admin.checkPrivileges instead'); diff --git a/src/navigation/admin.js b/src/navigation/admin.js index 04ecd7bc43..bbef6e9da1 100644 --- a/src/navigation/admin.js +++ b/src/navigation/admin.js @@ -9,13 +9,13 @@ const pubsub = require('../pubsub'); const admin = module.exports; let cache = null; -pubsub.on('admin:navigation:save', function () { +pubsub.on('admin:navigation:save', () => { cache = null; }); admin.save = async function (data) { const order = Object.keys(data); - const items = data.map(function (item, index) { + const items = data.map((item, index) => { item.order = order[index]; return JSON.stringify(item); }); @@ -40,7 +40,7 @@ admin.escapeFields = navItems => toggleEscape(navItems, true); admin.unescapeFields = navItems => toggleEscape(navItems, false); function toggleEscape(navItems, flag) { - navItems.forEach(function (item) { + navItems.forEach((item) => { if (item) { fieldsToEscape.forEach((field) => { if (item.hasOwnProperty(field)) { @@ -56,7 +56,7 @@ admin.get = async function () { return cache.map(item => ({ ...item })); } const data = await db.getSortedSetRange('navigation:enabled', 0, -1); - cache = data.map(function (item) { + cache = data.map((item) => { item = JSON.parse(item); item.groups = item.groups || []; if (item.groups && !Array.isArray(item.groups)) { @@ -70,7 +70,7 @@ admin.get = async function () { }; async function getAvailable() { - const core = require('../../install/data/navigation.json').map(function (item) { + const core = require('../../install/data/navigation.json').map((item) => { item.core = true; item.id = item.id || ''; item.properties = item.properties || { targetBlank: false }; diff --git a/src/navigation/index.js b/src/navigation/index.js index a581508367..1867c3396e 100644 --- a/src/navigation/index.js +++ b/src/navigation/index.js @@ -12,7 +12,7 @@ const relative_path = nconf.get('relative_path'); navigation.get = async function (uid) { let data = await admin.get(); - data = data.filter(item => item && item.enabled).map(function (item) { + data = data.filter(item => item && item.enabled).map((item) => { item.originalRoute = validator.unescape(item.route); if (!item.route.startsWith('http')) { @@ -22,7 +22,7 @@ navigation.get = async function (uid) { return item; }); - const pass = await Promise.all(data.map(async function (navItem) { + const pass = await Promise.all(data.map(async (navItem) => { if (!navItem.groups.length) { return true; } diff --git a/src/notifications.js b/src/notifications.js index f7d5a4c49a..ec29117017 100644 --- a/src/notifications.js +++ b/src/notifications.js @@ -67,7 +67,7 @@ Notifications.getMultiple = async function (nids) { const userKeys = notifications.map(n => n && n.from); const usersData = await User.getUsersFields(userKeys, ['username', 'userslug', 'picture']); - notifications.forEach(function (notification, index) { + notifications.forEach((notification, index) => { if (notification) { if (notification.path && !notification.path.startsWith('http')) { notification.path = nconf.get('relative_path') + notification.path; @@ -139,10 +139,10 @@ Notifications.push = async function (notification, uids) { return; } - setTimeout(function () { - batch.processArray(uids, async function (uids) { + setTimeout(() => { + batch.processArray(uids, async (uids) => { await pushToUids(uids, notification); - }, { interval: 1000 }, function (err) { + }, { interval: 1000 }, (err) => { if (err) { winston.error(err.stack); } @@ -164,7 +164,7 @@ async function pushToUids(uids, notification) { await db.sortedSetsRemoveRangeByScore(readKeys, '-inf', oneWeekAgo); const websockets = require('./socket.io'); if (websockets.server) { - uids.forEach(function (uid) { + uids.forEach((uid) => { websockets.in(`uid_${uid}`).emit('event:new_notification', notification); }); } @@ -198,7 +198,7 @@ async function pushToUids(uids, notification) { const uidsToNotify = []; const uidsToEmail = []; const usersSettings = await User.getMultipleUserSettings(uids); - usersSettings.forEach(function (userSettings) { + usersSettings.forEach((userSettings) => { const setting = userSettings[`notificationType_${notification.type}`] || 'notification'; if (setting === 'notification' || setting === 'notificationemail') { @@ -326,7 +326,7 @@ Notifications.prune = async function () { db.deleteAll(nids.map(nid => `notifications:${nid}`)), ]); - await batch.processSortedSet('users:joindate', async function (uids) { + await batch.processSortedSet('users:joindate', async (uids) => { const unread = uids.map(uid => `uid:${uid}:notifications:unread`); const read = uids.map(uid => `uid:${uid}:notifications:read`); await db.sortedSetsRemoveRangeByScore(unread.concat(read), '-inf', cutoffTime); @@ -350,14 +350,14 @@ Notifications.merge = async function (notifications) { 'post-queue', ]; - notifications = mergeIds.reduce(function (notifications, mergeId) { + notifications = mergeIds.reduce((notifications, mergeId) => { const isolated = notifications.filter(n => n && n.hasOwnProperty('mergeId') && n.mergeId.split('|')[0] === mergeId); if (isolated.length <= 1) { return notifications; // Nothing to merge } // Each isolated mergeId may have multiple differentiators, so process each separately - const differentiators = isolated.reduce(function (cur, next) { + const differentiators = isolated.reduce((cur, next) => { const differentiator = next.mergeId.split('|')[1] || 0; if (!cur.includes(differentiator)) { cur.push(differentiator); @@ -366,7 +366,7 @@ Notifications.merge = async function (notifications) { return cur; }, []); - differentiators.forEach(function (differentiator) { + differentiators.forEach((differentiator) => { let set; if (differentiator === 0 && differentiators.length === 1) { set = isolated; @@ -407,7 +407,7 @@ Notifications.merge = async function (notifications) { } // Filter out duplicates - notifications = notifications.filter(function (notifObj, idx) { + notifications = notifications.filter((notifObj, idx) => { if (!notifObj || !notifObj.mergeId) { return true; } diff --git a/src/pagination.js b/src/pagination.js index 291def4626..89251d82de 100644 --- a/src/pagination.js +++ b/src/pagination.js @@ -34,15 +34,13 @@ pagination.create = function (currentPage, pageCount, queryObj) { pagesToShow.push(startPage + i); } - pagesToShow = _.uniq(pagesToShow).filter(page => page > 0 && page <= pageCount).sort(function (a, b) { - return a - b; - }); + pagesToShow = _.uniq(pagesToShow).filter(page => page > 0 && page <= pageCount).sort((a, b) => a - b); queryObj = { ...(queryObj || {}) }; delete queryObj._; - var pages = pagesToShow.map(function (page) { + var pages = pagesToShow.map((page) => { queryObj.page = page; return { page: page, active: page === currentPage, qs: qs.stringify(queryObj) }; }); diff --git a/src/password.js b/src/password.js index d3fa3dae65..727528a3a8 100644 --- a/src/password.js +++ b/src/password.js @@ -11,7 +11,7 @@ const fork = require('./meta/debugFork'); function forkChild(message, callback) { const child = fork(path.join(__dirname, 'password')); - child.on('message', function (msg) { + child.on('message', (msg) => { callback(msg.err ? new Error(msg.err) : null, msg.result); }); @@ -45,7 +45,7 @@ async function getFakeHash() { } // child process -process.on('message', function (msg) { +process.on('message', (msg) => { if (msg.type === 'hash') { tryMethod(hashPassword, msg); } else if (msg.type === 'compare') { diff --git a/src/plugins/data.js b/src/plugins/data.js index 65844c0da3..59f54e5671 100644 --- a/src/plugins/data.js +++ b/src/plugins/data.js @@ -189,7 +189,7 @@ Data.getModules = async function getModules(pluginData) { if (Array.isArray(pluginModules)) { var strip = parseInt(pluginData.modulesStrip, 10) || 0; - pluginModules = pluginModules.reduce(function (prev, modulePath) { + pluginModules = pluginModules.reduce((prev, modulePath) => { var key; if (strip) { key = modulePath.replace(new RegExp(`.?(/[^/]+){${strip}}/`), ''); @@ -228,7 +228,7 @@ Data.getLanguageData = async function getLanguageData(pluginData) { const namespaces = []; const languages = []; - filepaths.forEach(function (p) { + filepaths.forEach((p) => { const rel = path.relative(pathToFolder, p).split(/[/\\]/); const language = rel.shift().replace('_', '-').replace('@', '-x-'); const namespace = rel.join('/').replace(/\.json$/, ''); diff --git a/src/plugins/hooks.js b/src/plugins/hooks.js index 074954ed63..12d9f5b3dc 100644 --- a/src/plugins/hooks.js +++ b/src/plugins/hooks.js @@ -55,12 +55,12 @@ Hooks.register = function (id, data) { if (Array.isArray(data.method) && data.method.every(method => typeof method === 'function' || typeof method === 'string')) { // Go go gadget recursion! - data.method.forEach(function (method) { + data.method.forEach((method) => { const singularData = { ...data, method: method }; Hooks.register(id, singularData); }); } else if (typeof data.method === 'string' && data.method.length > 0) { - const method = data.method.split('.').reduce(function (memo, prop) { + const method = data.method.split('.').reduce((memo, prop) => { if (memo && memo[prop]) { return memo[prop]; } @@ -81,9 +81,7 @@ Hooks.register = function (id, data) { Hooks.unregister = function (id, hook, method) { var hooks = plugins.loadedHooks[hook] || []; - plugins.loadedHooks[hook] = hooks.filter(function (hookData) { - return hookData && hookData.id !== id && hookData.method !== method; - }); + plugins.loadedHooks[hook] = hooks.filter(hookData => hookData && hookData.id !== id && hookData.method !== method); }; Hooks.fire = async function (hook, params) { @@ -116,7 +114,7 @@ async function fireFilterHook(hook, hookList, params) { return params; } - return await async.reduce(hookList, params, function (params, hookObj, next) { + return await async.reduce(hookList, params, (params, hookObj, next) => { if (typeof hookObj.method !== 'function') { if (global.env === 'development') { winston.warn(`[plugins] Expected method for hook '${hook}' in plugin '${hookObj.id}' not found, skipping.`); @@ -155,13 +153,13 @@ async function fireStaticHook(hook, hookList, params) { } // don't bubble errors from these hooks, so bad plugins don't stop startup const noErrorHooks = ['static:app.load', 'static:assets.prepare', 'static:app.preload']; - await async.each(hookList, function (hookObj, next) { + await async.each(hookList, (hookObj, next) => { if (typeof hookObj.method !== 'function') { return next(); } let timedOut = false; - const timeoutId = setTimeout(function () { + const timeoutId = setTimeout(() => { winston.warn(`[plugins] Callback timed out, hook '${hook}' in plugin '${hookObj.id}'`); timedOut = true; next(); diff --git a/src/plugins/index.js b/src/plugins/index.js index 85277fbdc5..1022566239 100644 --- a/src/plugins/index.js +++ b/src/plugins/index.js @@ -147,7 +147,7 @@ Plugins.reload = async function () { meta.configs.registerHooks(); // Lower priority runs earlier - Object.keys(Plugins.loadedHooks).forEach(function (hook) { + Object.keys(Plugins.loadedHooks).forEach((hook) => { Plugins.loadedHooks[hook].sort((a, b) => a.priority - b.priority); }); @@ -200,7 +200,7 @@ Plugins.normalise = async function (apiReturn) { const pluginMap = {}; const dependencies = require(paths.currentPackage).dependencies; apiReturn = Array.isArray(apiReturn) ? apiReturn : []; - apiReturn.forEach(function (packageData) { + apiReturn.forEach((packageData) => { packageData.id = packageData.name; packageData.installed = false; packageData.active = false; @@ -211,7 +211,7 @@ Plugins.normalise = async function (apiReturn) { let installedPlugins = await Plugins.showInstalled(); installedPlugins = installedPlugins.filter(plugin => plugin && !plugin.system); - installedPlugins.forEach(function (plugin) { + installedPlugins.forEach((plugin) => { // If it errored out because a package.json or plugin.json couldn't be read, no need to do this stuff if (plugin.error) { pluginMap[plugin.id] = pluginMap[plugin.id] || {}; @@ -250,7 +250,7 @@ Plugins.normalise = async function (apiReturn) { } } - pluginArray.sort(function (a, b) { + pluginArray.sort((a, b) => { if (a.name > b.name) { return 1; } else if (a.name < b.name) { @@ -290,12 +290,12 @@ Plugins.showInstalled = async function () { async function findNodeBBModules(dirs) { const pluginPaths = []; - await async.each(dirs, function (dirname, next) { + await async.each(dirs, (dirname, next) => { var dirPath = path.join(Plugins.nodeModulesPath, dirname); async.waterfall([ function (cb) { - fs.stat(dirPath, function (err, stats) { + fs.stat(dirPath, (err, stats) => { if (err && err.code !== 'ENOENT') { return cb(err); } @@ -315,13 +315,13 @@ async function findNodeBBModules(dirs) { }); }, function (subdirs, cb) { - async.each(subdirs, function (subdir, next) { + async.each(subdirs, (subdir, next) => { if (!pluginNamePattern.test(subdir)) { return next(); } var subdirPath = path.join(dirPath, subdir); - fs.stat(subdirPath, function (err, stats) { + fs.stat(subdirPath, (err, stats) => { if (err && err.code !== 'ENOENT') { return next(err); } diff --git a/src/plugins/install.js b/src/plugins/install.js index 57419b07df..b6a7726b9e 100644 --- a/src/plugins/install.js +++ b/src/plugins/install.js @@ -43,13 +43,13 @@ if (process.platform === 'win32') { module.exports = function (Plugins) { if (nconf.get('isPrimary')) { - pubsub.on('plugins:toggleInstall', function (data) { + pubsub.on('plugins:toggleInstall', (data) => { if (data.hostname !== os.hostname()) { toggleInstall(data.id, data.version); } }); - pubsub.on('plugins:upgrade', function (data) { + pubsub.on('plugins:upgrade', (data) => { if (data.hostname !== os.hostname()) { upgrade(data.id, data.version); } @@ -110,7 +110,7 @@ module.exports = function (Plugins) { packageManagerCommands[packageManager][command], pkgName + (command === 'install' ? `@${version}` : ''), '--save', - ], function (err, stdout) { + ], (err, stdout) => { if (err) { return callback(err); } diff --git a/src/plugins/load.js b/src/plugins/load.js index 90858757a9..f9a0f04880 100644 --- a/src/plugins/load.js +++ b/src/plugins/load.js @@ -44,7 +44,7 @@ module.exports = function (Plugins) { var methods = {}; if (Array.isArray(fields)) { - fields.forEach(function (field) { + fields.forEach((field) => { methods[field] = handlers[field]; }); } else { diff --git a/src/plugins/usage.js b/src/plugins/usage.js index 64117f3daa..b9a6757361 100644 --- a/src/plugins/usage.js +++ b/src/plugins/usage.js @@ -12,9 +12,9 @@ const meta = require('../meta'); module.exports = function (Plugins) { Plugins.startJobs = function () { - new cronJob('0 0 0 * * *', function () { + new cronJob('0 0 0 * * *', (() => { Plugins.submitUsageData(); - }, null, true); + }), null, true); }; Plugins.submitUsageData = function () { @@ -31,7 +31,7 @@ module.exports = function (Plugins) { plugins: Plugins.loadedPlugins, }, timeout: 5000, - }, function (err, res, body) { + }, (err, res, body) => { if (err) { return winston.error(err.stack); } diff --git a/src/posts/edit.js b/src/posts/edit.js index 69e64a63b8..8d8c1bc3df 100644 --- a/src/posts/edit.js +++ b/src/posts/edit.js @@ -15,7 +15,7 @@ const slugify = require('../slugify'); const translator = require('../translator'); module.exports = function (Posts) { - pubsub.on('post:edit', function (pid) { + pubsub.on('post:edit', (pid) => { require('./cache').del(pid); }); diff --git a/src/posts/summary.js b/src/posts/summary.js index 6a0bda8c2b..5f1b708f9d 100644 --- a/src/posts/summary.js +++ b/src/posts/summary.js @@ -38,7 +38,7 @@ module.exports = function (Posts) { const tidToTopic = toObject('tid', topicsAndCategories.topics); const cidToCategory = toObject('cid', topicsAndCategories.categories); - posts.forEach(function (post) { + posts.forEach((post) => { // If the post author isn't represented in the retrieved users' data, then it means they were deleted, assume guest. if (!uidToUser.hasOwnProperty(post.uid)) { post.uid = 0; diff --git a/src/posts/topics.js b/src/posts/topics.js index 7fc5d1ec50..1bd13deb36 100644 --- a/src/posts/topics.js +++ b/src/posts/topics.js @@ -37,7 +37,7 @@ module.exports = function (Posts) { topics.getTopicsFields(tids, ['slug']), ]); - const paths = pids.map(function (pid, index) { + const paths = pids.map((pid, index) => { const slug = topicData[index] ? topicData[index].slug : null; const postIndex = utils.isNumber(indices[index]) ? parseInt(indices[index], 10) + 1 : null; diff --git a/src/posts/uploads.js b/src/posts/uploads.js index 397e8b33a1..9cc827d6a5 100644 --- a/src/posts/uploads.js +++ b/src/posts/uploads.js @@ -128,7 +128,7 @@ module.exports = function (Posts) { const type = mime.getType(fileName); return type && type.match(/image./); }); - await Promise.all(filePaths.map(async function (fileName) { + await Promise.all(filePaths.map(async (fileName) => { try { const size = await image.size(path.join(pathPrefix, fileName)); winston.verbose(`[posts/uploads/${fileName}] Saving size`); diff --git a/src/posts/user.js b/src/posts/user.js index d880c01f89..e5de646ed8 100644 --- a/src/posts/user.js +++ b/src/posts/user.js @@ -22,7 +22,7 @@ module.exports = function (Posts) { const groupsMap = await getGroupsMap(userData); - userData.forEach(function (userData, index) { + userData.forEach((userData, index) => { userData.signature = validator.escape(String(userData.signature || '')); userData.fullname = userSettings[index].showfullname ? validator.escape(String(userData.fullname || '')) : undefined; userData.selectedGroups = []; @@ -32,7 +32,7 @@ module.exports = function (Posts) { } }); - return await Promise.all(userData.map(async function (userData) { + return await Promise.all(userData.map(async (userData) => { const [isMemberOfGroups, signature, customProfileInfo] = await Promise.all([ checkGroupMembership(userData.uid, userData.groupTitleArray), parseSignature(userData, uid, canUseSignature), @@ -40,7 +40,7 @@ module.exports = function (Posts) { ]); if (isMemberOfGroups && userData.groupTitleArray) { - userData.groupTitleArray.forEach(function (userGroup, index) { + userData.groupTitleArray.forEach((userGroup, index) => { if (isMemberOfGroups[index] && groupsMap[userGroup]) { userData.selectedGroups.push(groupsMap[userGroup]); } @@ -72,7 +72,7 @@ module.exports = function (Posts) { const groupTitles = _.uniq(_.flatten(userData.map(u => u && u.groupTitleArray))); const groupsMap = {}; const groupsData = await groups.getGroupsData(groupTitles); - groupsData.forEach(function (group) { + groupsData.forEach((group) => { if (group && group.userTitleEnabled && !group.hidden) { groupsMap[group.name] = { name: group.name, @@ -174,7 +174,7 @@ module.exports = function (Posts) { }; async function reduceCounters(postsByUser) { - await async.eachOfSeries(postsByUser, async function (posts, uid) { + await async.eachOfSeries(postsByUser, async (posts, uid) => { const repChange = posts.reduce((acc, val) => acc + val.votes, 0); await Promise.all([ user.incrementUserPostCountBy(uid, -posts.length), @@ -185,10 +185,10 @@ module.exports = function (Posts) { async function updateTopicPosters(postData, toUid) { const postsByTopic = _.groupBy(postData, p => parseInt(p.tid, 10)); - await async.eachOf(postsByTopic, async function (posts, tid) { + await async.eachOf(postsByTopic, async (posts, tid) => { const postsByUser = _.groupBy(posts, p => parseInt(p.uid, 10)); await db.sortedSetIncrBy(`tid:${tid}:posters`, posts.length, toUid); - await async.eachOf(postsByUser, async function (posts, uid) { + await async.eachOf(postsByUser, async (posts, uid) => { await db.sortedSetIncrBy(`tid:${tid}:posters`, -posts.length, uid); }); }); @@ -235,7 +235,7 @@ module.exports = function (Posts) { } async function reduceTopicCounts(postsByUser) { - await async.eachSeries(Object.keys(postsByUser), async function (uid) { + await async.eachSeries(Object.keys(postsByUser), async (uid) => { const posts = postsByUser[uid]; const exists = await user.exists(uid); if (exists) { diff --git a/src/prestart.js b/src/prestart.js index 7d4bc32092..6b56b773ff 100644 --- a/src/prestart.js +++ b/src/prestart.js @@ -62,7 +62,7 @@ function loadConfig(configFile) { // Explicitly cast as Bool, loader.js passes in isCluster as string 'true'/'false' var castAsBool = ['isCluster', 'isPrimary', 'jobsDisabled']; nconf.stores.env.readOnly = false; - castAsBool.forEach(function (prop) { + castAsBool.forEach((prop) => { var value = nconf.get(prop); if (value !== undefined) { nconf.set(prop, typeof value === 'boolean' ? value : String(value).toLowerCase() === 'true'); diff --git a/src/privileges/categories.js b/src/privileges/categories.js index 8c541e7c1a..b322b3bfa0 100644 --- a/src/privileges/categories.js +++ b/src/privileges/categories.js @@ -170,7 +170,7 @@ module.exports = function (privileges) { privileges.categories.userPrivileges = async function (cid, uid) { const tasks = {}; - privileges.userPrivilegeList.forEach(function (privilege) { + privileges.userPrivilegeList.forEach((privilege) => { tasks[privilege] = groups.isMember(uid, `cid:${cid}:privileges:${privilege}`); }); return await utils.promiseParallel(tasks); @@ -178,7 +178,7 @@ module.exports = function (privileges) { privileges.categories.groupPrivileges = async function (cid, groupName) { const tasks = {}; - privileges.groupPrivilegeList.forEach(function (privilege) { + privileges.groupPrivilegeList.forEach((privilege) => { tasks[privilege] = groups.isMember(groupName, `cid:${cid}:privileges:${privilege}`); }); return await utils.promiseParallel(tasks); diff --git a/src/privileges/global.js b/src/privileges/global.js index fe39dc11a2..7c0e1b369b 100644 --- a/src/privileges/global.js +++ b/src/privileges/global.js @@ -117,7 +117,7 @@ module.exports = function (privileges) { privileges.global.userPrivileges = async function (uid) { const tasks = {}; - privileges.global.userPrivilegeList.forEach(function (privilege) { + privileges.global.userPrivilegeList.forEach((privilege) => { tasks[privilege] = groups.isMember(uid, `cid:0:privileges:${privilege}`); }); return await utils.promiseParallel(tasks); @@ -125,7 +125,7 @@ module.exports = function (privileges) { privileges.global.groupPrivileges = async function (groupName) { const tasks = {}; - privileges.global.groupPrivilegeList.forEach(function (privilege) { + privileges.global.groupPrivilegeList.forEach((privilege) => { tasks[privilege] = groups.isMember(groupName, `cid:0:privileges:${privilege}`); }); return await utils.promiseParallel(tasks); diff --git a/src/privileges/helpers.js b/src/privileges/helpers.js index 4aaf1c72c1..25333e5336 100644 --- a/src/privileges/helpers.js +++ b/src/privileges/helpers.js @@ -105,14 +105,12 @@ async function isSystemGroupAllowedToPrivileges(privileges, uid, cid) { helpers.getUserPrivileges = async function (cid, userPrivileges) { let memberSets = await groups.getMembersOfGroups(userPrivileges.map(privilege => `cid:${cid}:privileges:${privilege}`)); - memberSets = memberSets.map(function (set) { - return set.map(uid => parseInt(uid, 10)); - }); + memberSets = memberSets.map(set => set.map(uid => parseInt(uid, 10))); const members = _.uniq(_.flatten(memberSets)); const memberData = await user.getUsersFields(members, ['picture', 'username', 'banned']); - memberData.forEach(function (member) { + memberData.forEach((member) => { member.privileges = {}; for (var x = 0, numPrivs = userPrivileges.length; x < numPrivs; x += 1) { member.privileges[userPrivileges[x]] = memberSets[x].includes(parseInt(member.uid, 10)); @@ -144,7 +142,7 @@ helpers.getGroupPrivileges = async function (cid, groupPrivileges) { groupNames.splice(adminIndex, 1); } const groupData = await groups.getGroupsFields(groupNames, ['private', 'system']); - const memberData = groupNames.map(function (member, index) { + const memberData = groupNames.map((member, index) => { const memberPrivs = {}; for (var x = 0, numPrivs = groupPrivileges.length; x < numPrivs; x += 1) { diff --git a/src/privileges/posts.js b/src/privileges/posts.js index 5534d7c822..807de31277 100644 --- a/src/privileges/posts.js +++ b/src/privileges/posts.js @@ -40,7 +40,7 @@ module.exports = function (privileges) { privData['posts:history'] = _.zipObject(uniqueCids, results['posts:history']); privData['posts:view_deleted'] = _.zipObject(uniqueCids, results['posts:view_deleted']); - const privileges = cids.map(function (cid, i) { + const privileges = cids.map((cid, i) => { const isAdminOrMod = results.isAdmin || isModerator[cid]; const editable = (privData['posts:edit'][cid] && (results.isOwner[i] || results.isModerator)) || results.isAdmin; const viewDeletedPosts = results.isOwner[i] || privData['posts:view_deleted'][cid] || results.isAdmin; @@ -77,7 +77,7 @@ module.exports = function (privileges) { const tidToTopic = _.zipObject(tids, topicData); - let cids = postData.map(function (post, index) { + let cids = postData.map((post, index) => { if (post) { post.pid = pids[index]; post.topic = tidToTopic[post.tid]; @@ -88,18 +88,14 @@ module.exports = function (privileges) { cids = _.uniq(cids); const results = await privileges.categories.getBase(privilege, cids, uid); - const allowedCids = cids.filter(function (cid, index) { - return !results.categories[index].disabled && - (results.allowedTo[index] || results.isAdmin); - }); + const allowedCids = cids.filter((cid, index) => !results.categories[index].disabled && + (results.allowedTo[index] || results.isAdmin)); const cidsSet = new Set(allowedCids); const canViewDeleted = _.zipObject(cids, results.view_deleted); - pids = postData.filter(function (post) { - return post.topic && cidsSet.has(post.topic.cid) && - ((!post.topic.deleted && !post.deleted) || canViewDeleted[post.topic.cid] || results.isAdmin); - }).map(post => post.pid); + pids = postData.filter(post => post.topic && cidsSet.has(post.topic.cid) && + ((!post.topic.deleted && !post.deleted) || canViewDeleted[post.topic.cid] || results.isAdmin)).map(post => post.pid); const data = await plugins.hooks.fire('filter:privileges.posts.filter', { privilege: privilege, diff --git a/src/privileges/topics.js b/src/privileges/topics.js index 5731f51e5c..00945d8977 100644 --- a/src/privileges/topics.js +++ b/src/privileges/topics.js @@ -98,10 +98,8 @@ module.exports = function (privileges) { helpers.isUsersAllowedTo(privilege, uids, topicData.cid), user.isAdministrator(uids), ]); - return uids.filter(function (uid, index) { - return !disabled && - ((allowedTo[index] && !topicData.deleted) || isAdmins[index]); - }); + return uids.filter((uid, index) => !disabled && + ((allowedTo[index] && !topicData.deleted) || isAdmins[index])); }; privileges.topics.canPurge = async function (tid, uid) { diff --git a/src/promisify.js b/src/promisify.js index b795c17c35..0552a24eeb 100644 --- a/src/promisify.js +++ b/src/promisify.js @@ -22,7 +22,7 @@ module.exports = function (theModule, ignoreKeys) { } const keys = Object.keys(module); - keys.forEach(function (key) { + keys.forEach((key) => { if (ignoreKeys.includes(key)) { return; } @@ -40,9 +40,7 @@ module.exports = function (theModule, ignoreKeys) { return async function wrapperCallback(...args) { if (arguments.length && typeof arguments[arguments.length - 1] === 'function') { const cb = args.pop(); - args.push(function (err, res) { - return res !== undefined ? cb(err, res) : cb(err); - }); + args.push((err, res) => (res !== undefined ? cb(err, res) : cb(err))); return callbackFn.apply(null, args); } return origFn.apply(null, arguments); diff --git a/src/pubsub.js b/src/pubsub.js index 19c73aaaba..95e07d0f81 100644 --- a/src/pubsub.js +++ b/src/pubsub.js @@ -38,7 +38,7 @@ function get() { data: data, }); }; - process.on('message', function (message) { + process.on('message', (message) => { if (message && typeof message === 'object' && message.action === 'pubsub') { singleHost.emit(message.event, message.data); } diff --git a/src/rewards/admin.js b/src/rewards/admin.js index 48ba9e6b78..15a0c9fcc8 100644 --- a/src/rewards/admin.js +++ b/src/rewards/admin.js @@ -48,7 +48,7 @@ async function saveConditions(data) { await db.delete('conditions:active'); const conditions = []; - data.forEach(function (reward) { + data.forEach((reward) => { conditions.push(reward.condition); rewardsPerCondition[reward.condition] = rewardsPerCondition[reward.condition] || []; rewardsPerCondition[reward.condition].push(reward.id); diff --git a/src/rewards/index.js b/src/rewards/index.js index 9468ff8696..b4c9f8418f 100644 --- a/src/rewards/index.js +++ b/src/rewards/index.js @@ -37,11 +37,11 @@ async function filterCompletedRewards(uid, rewards) { const data = await db.getSortedSetRangeByScoreWithScores(`uid:${uid}:rewards`, 0, -1, 1, '+inf'); const userRewards = {}; - data.forEach(function (obj) { + data.forEach((obj) => { userRewards[obj.value] = parseInt(obj.score, 10); }); - return rewards.filter(function (reward) { + return rewards.filter((reward) => { if (!reward) { return false; } diff --git a/src/routes/accounts.js b/src/routes/accounts.js index 45d147f712..81bbbd88e2 100644 --- a/src/routes/accounts.js +++ b/src/routes/accounts.js @@ -34,7 +34,7 @@ module.exports = function (app, middleware, controllers) { setupPageRoute(app, '/user/:userslug/edit/username', middleware, accountMiddlewares, controllers.accounts.edit.username); setupPageRoute(app, '/user/:userslug/edit/email', middleware, accountMiddlewares, controllers.accounts.edit.email); setupPageRoute(app, '/user/:userslug/edit/password', middleware, accountMiddlewares, controllers.accounts.edit.password); - app.use('/.well-known/change-password', function (req, res) { + app.use('/.well-known/change-password', (req, res) => { res.redirect('/me/edit/password'); }); setupPageRoute(app, '/user/:userslug/info', middleware, accountMiddlewares, controllers.accounts.info.get); @@ -43,7 +43,7 @@ module.exports = function (app, middleware, controllers) { setupPageRoute(app, '/user/:userslug/consent', middleware, accountMiddlewares, controllers.accounts.consent.get); setupPageRoute(app, '/user/:userslug/blocks', middleware, accountMiddlewares, controllers.accounts.blocks.getBlocks); setupPageRoute(app, '/user/:userslug/sessions', middleware, accountMiddlewares, controllers.accounts.sessions.get); - app.delete('/api/user/:userslug/session/:uuid', [middleware.exposeUid], function (req, res, next) { + app.delete('/api/user/:userslug/session/:uuid', [middleware.exposeUid], (req, res, next) => { // TODO: Remove this entire route in v1.16.0 winston.warn('[router] `/api/user/:userslug/session/:uuid` has been deprecated, use `DELETE /api/v3/users/:uid/sessions/:uuid` or `DELETE /api/v3/users/bySlug/:userslug/sessions/:uuid` instead'); if (!res.locals.uid) { diff --git a/src/routes/authentication.js b/src/routes/authentication.js index 914bf10485..bef61ba9d5 100644 --- a/src/routes/authentication.js +++ b/src/routes/authentication.js @@ -17,15 +17,15 @@ var Auth = module.exports; Auth.initialize = function (app, middleware) { const passportInitMiddleware = passport.initialize(); - app.use(function passportInitialize(req, res, next) { + app.use((req, res, next) => { passportInitMiddleware(req, res, next); }); const passportSessionMiddleware = passport.session(); - app.use(function passportSession(req, res, next) { + app.use((req, res, next) => { passportSessionMiddleware(req, res, next); }); - app.use(function (req, res, next) { + app.use((req, res, next) => { Auth.setAuthVars(req, res); next(); }); @@ -96,9 +96,9 @@ Auth.reloadRoutes = async function (params) { winston.error(`[authentication] ${err.stack}`); } loginStrategies = loginStrategies || []; - loginStrategies.forEach(function (strategy) { + loginStrategies.forEach((strategy) => { if (strategy.url) { - router.get(strategy.url, Auth.middleware.applyCSRF, async function (req, res, next) { + router.get(strategy.url, Auth.middleware.applyCSRF, async (req, res, next) => { let opts = { scope: strategy.scope, prompt: strategy.prompt || undefined, @@ -116,21 +116,21 @@ Auth.reloadRoutes = async function (params) { }); } - router[strategy.callbackMethod || 'get'](strategy.callbackURL, function (req, res, next) { + router[strategy.callbackMethod || 'get'](strategy.callbackURL, (req, res, next) => { // Ensure the passed-back state value is identical to the saved ssoState (unless explicitly skipped) if (strategy.checkState === false) { return next(); } next(req.query.state !== req.session.ssoState ? new Error('[[error:csrf-invalid]]') : null); - }, function (req, res, next) { + }, (req, res, next) => { // Trigger registration interstitial checks req.session.registration = req.session.registration || {}; // save returnTo for later usage in /register/complete // passport seems to remove `req.session.returnTo` after it redirects req.session.registration.returnTo = req.session.returnTo; - passport.authenticate(strategy.name, function (err, user) { + passport.authenticate(strategy.name, (err, user) => { if (err) { delete req.session.registration; return next(err); @@ -151,7 +151,7 @@ Auth.reloadRoutes = async function (params) { async.waterfall([ async.apply(req.login.bind(req), res.locals.user), async.apply(controllers.authentication.onSuccessfulLogin, req, req.uid), - ], function (err) { + ], (err) => { if (err) { return next(err); } @@ -172,11 +172,11 @@ Auth.reloadRoutes = async function (params) { router.post('/logout', Auth.middleware.applyCSRF, controllers.authentication.logout); }; -passport.serializeUser(function (user, done) { +passport.serializeUser((user, done) => { done(null, user.uid); }); -passport.deserializeUser(function (uid, done) { +passport.deserializeUser((uid, done) => { done(null, { uid: uid, }); diff --git a/src/routes/debug.js b/src/routes/debug.js index dd730410d6..23900aee6c 100644 --- a/src/routes/debug.js +++ b/src/routes/debug.js @@ -9,7 +9,7 @@ const path = require('path'); module.exports = function (app) { var router = express.Router(); - router.get('/test', function (req, res) { + router.get('/test', (req, res) => { res.redirect(404); }); diff --git a/src/routes/feeds.js b/src/routes/feeds.js index fc27a35910..4bdbd31bd1 100644 --- a/src/routes/feeds.js +++ b/src/routes/feeds.js @@ -95,7 +95,7 @@ async function generateForTopic(req, res) { feed.pubDate = new Date(parseInt(topicData.posts[0].timestamp, 10)).toUTCString(); } const replies = topicData.posts.slice(1); - replies.forEach(function (postData) { + replies.forEach((postData) => { if (!postData.deleted) { const dateStamp = new Date(parseInt(parseInt(postData.edited, 10) === 0 ? postData.timestamp : postData.edited, 10)).toUTCString(); @@ -361,7 +361,7 @@ function generateForPostsFeed(feedOptions, posts) { feed.pubDate = new Date(parseInt(posts[0].timestamp, 10)).toUTCString(); } - posts.forEach(function (postData) { + posts.forEach((postData) => { feed.item({ title: postData.topic ? postData.topic.title : '', description: postData.content, diff --git a/src/routes/index.js b/src/routes/index.js index 3b6e6db0ee..1840e1b930 100644 --- a/src/routes/index.js +++ b/src/routes/index.js @@ -157,15 +157,15 @@ function addCoreRoutes(app, router, middleware) { statics.unshift({ route: '/assets/uploads', path: nconf.get('upload_path') }); } - statics.forEach(function (obj) { + statics.forEach((obj) => { app.use(relativePath + obj.route, middleware.trimUploadTimestamps, express.static(obj.path, staticOptions)); }); - app.use(`${relativePath}/uploads`, function (req, res) { + app.use(`${relativePath}/uploads`, (req, res) => { res.redirect(`${relativePath}/assets/uploads${req.path}?${meta.config['cache-buster']}`); }); // Skins - meta.css.supportedSkins.forEach(function (skin) { + meta.css.supportedSkins.forEach((skin) => { app.use(`${relativePath}/assets/client-${skin}.css`, middleware.buildSkinAsset); }); diff --git a/src/routes/meta.js b/src/routes/meta.js index 39c95f8dbb..9c633bb125 100644 --- a/src/routes/meta.js +++ b/src/routes/meta.js @@ -12,7 +12,7 @@ module.exports = function (app, middleware, controllers) { app.get('/manifest.webmanifest', controllers.manifest); app.get('/css/previews/:theme', controllers.admin.themes.get); app.get('/osd.xml', controllers.osd.handle); - app.get('/service-worker.js', function (req, res) { + app.get('/service-worker.js', (req, res) => { res.status(200).type('application/javascript').set('Service-Worker-Allowed', `${nconf.get('relative_path')}/`).sendFile(path.join(__dirname, '../../public/src/service-worker.js')); }); }; diff --git a/src/routes/write/index.js b/src/routes/write/index.js index 3c80fdf641..fd530cbe56 100644 --- a/src/routes/write/index.js +++ b/src/routes/write/index.js @@ -21,7 +21,7 @@ Write.reload = async (params) => { }, }); - router.use('/api/v3', function (req, res, next) { + router.use('/api/v3', (req, res, next) => { // Require https if configured so if (apiSettings.requireHttps === 'on') { res.set('Upgrade', 'TLS/1.0, HTTP/1.1'); diff --git a/src/search.js b/src/search.js index cda83a9c7c..86e1f056e9 100644 --- a/src/search.js +++ b/src/search.js @@ -129,7 +129,7 @@ async function getMatchedPosts(pids, data) { const tidToTopic = _.zipObject(tids, topics); const uidToUser = _.zipObject(uids, users); - postsData.forEach(function (post) { + postsData.forEach((post) => { if (topics && tidToTopic[post.tid]) { post.topic = tidToTopic[post.tid]; if (post.topic && post.topic.category) { @@ -161,7 +161,7 @@ async function getTopics(tids, data) { ]); const cidToCategory = _.zipObject(cids, categories); - topicsData.forEach(function (topic, index) { + topicsData.forEach((topic, index) => { if (topic && categories && cidToCategory[topic.cid]) { topic.category = cidToCategory[topic.cid]; } @@ -220,7 +220,7 @@ function filterByTimerange(posts, timeRange, timeFilter) { function filterByTags(posts, hasTags) { if (Array.isArray(hasTags) && hasTags.length) { - posts = posts.filter(function (post) { + posts = posts.filter((post) => { var hasAllTags = false; if (post && post.topic && Array.isArray(post.topic.tags) && post.topic.tags.length) { hasAllTags = hasTags.every(tag => post.topic.tags.includes(tag)); @@ -253,7 +253,7 @@ function sortPosts(posts, data) { if (isNumeric) { posts.sort((p1, p2) => direction * (p2[fields[0]][fields[1]] - p1[fields[0]][fields[1]])); } else { - posts.sort(function (p1, p2) { + posts.sort((p1, p2) => { if (p1[fields[0]][fields[1]] > p2[fields[0]][fields[1]]) { return direction; } else if (p1[fields[0]][fields[1]] < p2[fields[0]][fields[1]]) { diff --git a/src/settings.js b/src/settings.js index eacefe24cb..11c33cf788 100644 --- a/src/settings.js +++ b/src/settings.js @@ -78,7 +78,7 @@ function Settings(hash, version, defCfg, callback, forceUpdate, reset) { this.checkStructure(callback, forceUpdate); }); } - pubsub.on(`action:settings.set.${hash}`, function (data) { + pubsub.on(`action:settings.set.${hash}`, (data) => { try { self.cfg._ = JSON.parse(data._); } catch (err) {} @@ -96,7 +96,7 @@ Settings.prototype.version = '0.0.0'; */ Settings.prototype.sync = function (callback) { var _this = this; - meta.settings.get(this.hash, function (err, settings) { + meta.settings.get(this.hash, (err, settings) => { try { if (settings._) { settings._ = JSON.parse(settings._); diff --git a/src/sitemap.js b/src/sitemap.js index 43379e682b..3c3b1a1352 100644 --- a/src/sitemap.js +++ b/src/sitemap.js @@ -72,7 +72,7 @@ sitemap.getCategories = async function () { const categoryUrls = []; const categoriesData = await categories.getCategoriesByPrivilege('categories:cid', 0, 'find'); - categoriesData.forEach(function (category) { + categoriesData.forEach((category) => { if (category) { categoryUrls.push({ url: `${nconf.get('relative_path')}/category/${category.slug}`, @@ -109,7 +109,7 @@ sitemap.getTopicPage = async function (page) { tids = await privileges.topics.filterTids('topics:read', tids, 0); const topicData = await topics.getTopicsFields(tids, ['tid', 'title', 'slug', 'lastposttime']); - topicData.forEach(function (topic) { + topicData.forEach((topic) => { if (topic) { topicUrls.push({ url: `${nconf.get('relative_path')}/topic/${topic.slug}`, diff --git a/src/social.js b/src/social.js index 802fa3e754..1ecc9465c1 100644 --- a/src/social.js +++ b/src/social.js @@ -26,7 +26,7 @@ social.getPostSharing = async function () { ]; networks = await plugins.hooks.fire('filter:social.posts', networks); const activated = await db.getSetMembers('social:posts.activated'); - networks.forEach(function (network) { + networks.forEach((network) => { network.activated = activated.includes(network.id); }); diff --git a/src/socket.io/admin/analytics.js b/src/socket.io/admin/analytics.js index 533e7f2e32..051b8bb282 100644 --- a/src/socket.io/admin/analytics.js +++ b/src/socket.io/admin/analytics.js @@ -39,8 +39,8 @@ Analytics.get = function (socket, data, callback) { summary: function (next) { analytics.getSummary(next); }, - }, function (err, data) { - data.pastDay = data.pageviews.reduce(function (a, b) { return parseInt(a, 10) + parseInt(b, 10); }); + }, (err, data) => { + data.pastDay = data.pageviews.reduce((a, b) => parseInt(a, 10) + parseInt(b, 10)); data.pageviews[data.pageviews.length - 1] = parseInt(data.pageviews[data.pageviews.length - 1], 10) + analytics.getUnwrittenPageviews(); callback(err, data); }); diff --git a/src/socket.io/admin/config.js b/src/socket.io/admin/config.js index 69fe3318d3..f22bcd0609 100644 --- a/src/socket.io/admin/config.js +++ b/src/socket.io/admin/config.js @@ -25,7 +25,7 @@ Config.setMultiple = async function (socket, data) { const changes = {}; const newData = meta.configs.serialize(data); const oldData = meta.configs.serialize(meta.config); - Object.keys(newData).forEach(function (key) { + Object.keys(newData).forEach((key) => { if (newData[key] !== oldData[key]) { changes[key] = newData[key]; changes[`${key}_old`] = meta.config[key]; diff --git a/src/socket.io/admin/rooms.js b/src/socket.io/admin/rooms.js index a3c197c657..57782b8fa3 100644 --- a/src/socket.io/admin/rooms.js +++ b/src/socket.io/admin/rooms.js @@ -15,7 +15,7 @@ const SocketRooms = module.exports; SocketRooms.stats = stats; SocketRooms.totals = totals; -pubsub.on('sync:stats:start', function () { +pubsub.on('sync:stats:start', () => { const stats = SocketRooms.getLocalStats(); pubsub.publish('sync:stats:end', { stats: stats, @@ -23,11 +23,11 @@ pubsub.on('sync:stats:start', function () { }); }); -pubsub.on('sync:stats:end', function (data) { +pubsub.on('sync:stats:end', (data) => { stats[data.id] = data.stats; }); -pubsub.on('sync:stats:guests', function (eventId) { +pubsub.on('sync:stats:guests', (eventId) => { const Sockets = require('../index'); const guestCount = Sockets.getCountInRoom('online_guests'); pubsub.publish(eventId, guestCount); @@ -36,13 +36,13 @@ pubsub.on('sync:stats:guests', function (eventId) { SocketRooms.getTotalGuestCount = function (callback) { var count = 0; var eventId = `sync:stats:guests:end:${utils.generateUUID()}`; - pubsub.on(eventId, function (guestCount) { + pubsub.on(eventId, (guestCount) => { count += guestCount; }); pubsub.publish('sync:stats:guests', eventId); - setTimeout(function () { + setTimeout(() => { pubsub.removeAllListeners(eventId); callback(null, count); }, 100); @@ -75,7 +75,7 @@ SocketRooms.getAll = async function () { totals.users.topics += stats[instance].users.topics; totals.users.category += stats[instance].users.category; - stats[instance].topics.forEach(function (topic) { + stats[instance].topics.forEach((topic) => { totals.topics[topic.tid] = totals.topics[topic.tid] || { count: 0, tid: topic.tid }; totals.topics[topic.tid].count += topic.count; }); @@ -83,7 +83,7 @@ SocketRooms.getAll = async function () { } var topTenTopics = []; - Object.keys(totals.topics).forEach(function (tid) { + Object.keys(totals.topics).forEach((tid) => { topTenTopics.push({ tid: tid, count: totals.topics[tid].count || 0 }); }); @@ -92,7 +92,7 @@ SocketRooms.getAll = async function () { var topTenTids = topTenTopics.map(topic => topic.tid); const titles = await topics.getTopicsFields(topTenTids, ['title']); - totals.topTenTopics = topTenTopics.map(function (topic, index) { + totals.topTenTopics = topTenTopics.map((topic, index) => { topic.title = titles[index].title; return topic; }); diff --git a/src/socket.io/admin/user.js b/src/socket.io/admin/user.js index 32d130ca4f..3609f4b55e 100644 --- a/src/socket.io/admin/user.js +++ b/src/socket.io/admin/user.js @@ -87,7 +87,7 @@ User.sendValidationEmail = async function (socket, uids) { const failed = []; - await async.eachLimit(uids, 50, async function (uid) { + await async.eachLimit(uids, 50, async (uid) => { await user.email.sendValidationEmail(uid, { force: true }).catch((err) => { winston.error(`[user.create] Validation email failed to send\n[emailer.send] ${err.stack}`); failed.push(uid); @@ -106,7 +106,7 @@ User.sendPasswordResetEmail = async function (socket, uids) { uids = uids.filter(uid => parseInt(uid, 10)); - await Promise.all(uids.map(async function (uid) { + await Promise.all(uids.map(async (uid) => { const userData = await user.getUserFields(uid, ['email', 'username']); if (!userData.email) { throw new Error(`[[error:user-doesnt-have-email, ${userData.username}]]`); @@ -170,7 +170,7 @@ User.exportUsersCSV = async function (socket) { uid: socket.uid, ip: socket.ip, }); - setTimeout(async function () { + setTimeout(async () => { try { await user.exportUsersCSV(); socket.emit('event:export-users-csv'); diff --git a/src/socket.io/categories.js b/src/socket.io/categories.js index b9121d2d9b..0bafd95055 100644 --- a/src/socket.io/categories.js +++ b/src/socket.io/categories.js @@ -108,7 +108,7 @@ SocketCategories.setWatchState = async function (socket, data) { if (!data || !data.cid || !data.state) { throw new Error('[[error:invalid-data]]'); } - return await ignoreOrWatch(async function (uid, cids) { + return await ignoreOrWatch(async (uid, cids) => { await user.setCategoryWatchState(uid, cids, categories.watchStates[data.state]); }, socket, data); }; diff --git a/src/socket.io/categories/search.js b/src/socket.io/categories/search.js index 9dc67c89ad..c7b8a276ab 100644 --- a/src/socket.io/categories/search.js +++ b/src/socket.io/categories/search.js @@ -34,7 +34,7 @@ module.exports = function (SocketCategories) { let categoriesData = categories.buildForSelectCategories(visibleCategories, ['disabledClass'], data.parentCid); categoriesData = categoriesData.slice(0, 200); - categoriesData.forEach(function (category) { + categoriesData.forEach((category) => { category.selected = data.selectedCids ? data.selectedCids.includes(category.cid) : false; if (matchedCids.includes(category.cid)) { category.match = true; diff --git a/src/socket.io/flags.js b/src/socket.io/flags.js index 7039903f8d..c63d3511a0 100644 --- a/src/socket.io/flags.js +++ b/src/socket.io/flags.js @@ -35,7 +35,7 @@ SocketFlags.update = async function (socket, data) { } let payload = {}; // Translate form data into object - payload = data.data.reduce(function (memo, cur) { + payload = data.data.reduce((memo, cur) => { memo[cur.name] = cur.value; return memo; }, payload); diff --git a/src/socket.io/helpers.js b/src/socket.io/helpers.js index 181e3fca91..6801cf91e8 100644 --- a/src/socket.io/helpers.js +++ b/src/socket.io/helpers.js @@ -27,7 +27,7 @@ SocketHelpers.setDefaultPostData = function (data, socket) { SocketHelpers.notifyNew = async function (uid, type, result) { let uids = await user.getUidsFromSet('users:online', 0, -1); uids = uids.filter(toUid => parseInt(toUid, 10) !== uid); - await batch.processArray(uids, async function (uids) { + await batch.processArray(uids, async (uids) => { await notifyUids(uid, uids, type, result); }, { interval: 1000, @@ -52,7 +52,7 @@ async function notifyUids(uid, uids, type, result) { post.ip = undefined; - data.uidsTo.forEach(function (toUid) { + data.uidsTo.forEach((toUid) => { post.categoryWatchState = categoryWatchStates[toUid]; post.topic.isFollowing = topicFollowState[toUid]; websockets.in(`uid_${toUid}`).emit('event:new_post', result); @@ -71,10 +71,8 @@ async function getWatchStates(uids, tid, cid) { } function filterTidCidIgnorers(uids, watchStates) { - return uids.filter(function (uid, index) { - return watchStates.topicFollowed[index] || - (!watchStates.topicIgnored[index] && watchStates.categoryWatchStates[index] !== categories.watchStates.ignoring); - }); + return uids.filter((uid, index) => watchStates.topicFollowed[index] || + (!watchStates.topicIgnored[index] && watchStates.categoryWatchStates[index] !== categories.watchStates.ignoring)); } SocketHelpers.sendNotificationToPostOwner = async function (pid, fromuid, command, notification) { diff --git a/src/socket.io/index.js b/src/socket.io/index.js index 1118560d7d..14dca06ca6 100644 --- a/src/socket.io/index.js +++ b/src/socket.io/index.js @@ -75,7 +75,7 @@ function onConnection(socket) { onMessage(socket, payload); }); - socket.on('disconnect', function () { + socket.on('disconnect', () => { onDisconnect(socket); }); } @@ -114,7 +114,7 @@ async function onMessage(socket, payload) { const parts = eventName.toString().split('.'); const namespace = parts[0]; - const methodToCall = parts.reduce(function (prev, cur) { + const methodToCall = parts.reduce((prev, cur) => { if (prev !== null && prev[cur]) { return prev[cur]; } @@ -151,7 +151,7 @@ async function onMessage(socket, payload) { const result = await methodToCall(socket, params); callback(null, result); } else { - methodToCall(socket, params, function (err, result) { + methodToCall(socket, params, (err, result) => { callback(err ? { message: err.message } : null, result); }); } @@ -167,7 +167,7 @@ function requireModules() { 'flags', 'uploads', ]; - modules.forEach(function (module) { + modules.forEach((module) => { Namespaces[module] = require(`./${module}`); }); } diff --git a/src/socket.io/modules.js b/src/socket.io/modules.js index 0e577d3ca1..20c20b2e8e 100644 --- a/src/socket.io/modules.js +++ b/src/socket.io/modules.js @@ -246,7 +246,7 @@ SocketModules.chats.renameRoom = async function (socket, data) { await Messaging.renameRoom(socket.uid, data.roomId, data.newName); const uids = await Messaging.getUidsInRoom(data.roomId, 0, -1); const eventData = { roomId: data.roomId, newName: validator.escape(String(data.newName)) }; - uids.forEach(function (uid) { + uids.forEach((uid) => { server.in(`uid_${uid}`).emit('event:chats.roomRename', eventData); }); }; diff --git a/src/socket.io/posts/votes.js b/src/socket.io/posts/votes.js index 97e6440e5f..cc87f96dc0 100644 --- a/src/socket.io/posts/votes.js +++ b/src/socket.io/posts/votes.js @@ -47,7 +47,7 @@ module.exports = function (SocketPosts) { return []; } - const result = await Promise.all(data.map(async function (uids) { + const result = await Promise.all(data.map(async (uids) => { let otherCount = 0; if (uids.length > 6) { otherCount = uids.length - 5; diff --git a/src/socket.io/single-host-cluster.js b/src/socket.io/single-host-cluster.js index b2645d6eb9..c091a9a689 100644 --- a/src/socket.io/single-host-cluster.js +++ b/src/socket.io/single-host-cluster.js @@ -9,8 +9,8 @@ var Client = { }); }, trigger: function (channel, message) { - Client.message.concat(Client.pmessage).forEach(function (callback) { - setImmediate(function () { + Client.message.concat(Client.pmessage).forEach((callback) => { + setImmediate(() => { callback.call(Client, channel, message); }); }); @@ -36,16 +36,14 @@ var Client = { return; } if (callback) { - Client[event] = Client[event].filter(function (c) { - return c !== callback; - }); + Client[event] = Client[event].filter(c => c !== callback); } else { Client[event] = []; } }, }; -process.on('message', function (message) { +process.on('message', (message) => { if (message && typeof message === 'object' && message.action === 'socket.io') { Client.trigger(message.channel, message.message); } diff --git a/src/socket.io/topics/move.js b/src/socket.io/topics/move.js index 3115adffa6..261dba980f 100644 --- a/src/socket.io/topics/move.js +++ b/src/socket.io/topics/move.js @@ -20,7 +20,7 @@ module.exports = function (SocketTopics) { const uids = await user.getUidsFromSet('users:online', 0, -1); - await async.eachLimit(data.tids, 10, async function (tid) { + await async.eachLimit(data.tids, 10, async (tid) => { const canMove = await privileges.topics.isAdminOrMod(tid, socket.uid); if (!canMove) { throw new Error('[[error:no-privileges]]'); @@ -49,7 +49,7 @@ module.exports = function (SocketTopics) { const tids = await categories.getAllTopicIds(data.currentCid, 0, -1); data.uid = socket.uid; - await async.eachLimit(tids, 50, async function (tid) { + await async.eachLimit(tids, 50, async (tid) => { await topics.tools.move(tid, data); }); }; diff --git a/src/socket.io/user/profile.js b/src/socket.io/user/profile.js index f5750e24b0..3ffd45feda 100644 --- a/src/socket.io/user/profile.js +++ b/src/socket.io/user/profile.js @@ -128,11 +128,11 @@ module.exports = function (SocketUser) { env: process.env, }); child.send({ uid: data.uid }); - child.on('error', async function (err) { + child.on('error', async (err) => { winston.error(err.stack); await db.deleteObjectField('locks', `export:${data.uid}${type}`); }); - child.on('exit', async function () { + child.on('exit', async () => { await db.deleteObjectField('locks', `export:${data.uid}${type}`); const userData = await user.getUserFields(data.uid, ['username', 'userslug']); const n = await notifications.create({ diff --git a/src/start.js b/src/start.js index 0a0e0d7bd2..f5cf130aa2 100644 --- a/src/start.js +++ b/src/start.js @@ -97,13 +97,13 @@ function addProcessHandlers() { process.on('SIGTERM', shutdown); process.on('SIGINT', shutdown); process.on('SIGHUP', restart); - process.on('uncaughtException', function (err) { + process.on('uncaughtException', (err) => { winston.error(err.stack); require('./meta').js.killMinifier(); shutdown(1); }); - process.on('message', function (msg) { + process.on('message', (msg) => { if (msg && msg.compiling === 'tpl') { const benchpressjs = require('benchpressjs'); benchpressjs.flush(); diff --git a/src/topics/bookmarks.js b/src/topics/bookmarks.js index c661e73f8b..c604d20f5a 100644 --- a/src/topics/bookmarks.js +++ b/src/topics/bookmarks.js @@ -40,10 +40,10 @@ module.exports = function (Topics) { var uidData = bookmarks.map(b => ({ uid: b.value, bookmark: parseInt(b.score, 10) })) .filter(data => data.bookmark >= minIndex); - await async.eachLimit(uidData, 50, async function (data) { + await async.eachLimit(uidData, 50, async (data) => { var bookmark = Math.min(data.bookmark, maxIndex); - postIndices.forEach(function (i) { + postIndices.forEach((i) => { if (i < data.bookmark) { bookmark -= 1; } diff --git a/src/topics/delete.js b/src/topics/delete.js index faa940ee6b..bbafb20bcf 100644 --- a/src/topics/delete.js +++ b/src/topics/delete.js @@ -40,7 +40,7 @@ module.exports = function (Topics) { postData = postData.filter(post => post && !post.deleted); var pidsToAdd = []; var scores = []; - postData.forEach(function (post) { + postData.forEach((post) => { pidsToAdd.push(post.pid); scores.push(post.timestamp); }); @@ -60,8 +60,8 @@ module.exports = function (Topics) { Topics.purgePostsAndTopic = async function (tid, uid) { const mainPid = await Topics.getTopicField(tid, 'mainPid'); - await batch.processSortedSet(`tid:${tid}:posts`, function (pids, next) { - async.eachSeries(pids, function (pid, next) { + await batch.processSortedSet(`tid:${tid}:posts`, (pids, next) => { + async.eachSeries(pids, (pid, next) => { posts.purge(pid, uid, next); }, next); }, { alwaysStartAt: 0 }); diff --git a/src/topics/fork.js b/src/topics/fork.js index 25681b9481..0eb0ccdfe2 100644 --- a/src/topics/fork.js +++ b/src/topics/fork.js @@ -42,7 +42,7 @@ module.exports = function (Topics) { const tid = await Topics.create({ uid: postData.uid, title: title, cid: cid }); await Topics.updateTopicBookmarks(fromTid, pids); - await async.eachSeries(pids, async function (pid) { + await async.eachSeries(pids, async (pid) => { const canEdit = await privileges.posts.canEdit(pid, uid); if (!canEdit.flag) { throw new Error(canEdit.message); diff --git a/src/topics/index.js b/src/topics/index.js index 2c77feba1a..c5f990a662 100644 --- a/src/topics/index.js +++ b/src/topics/index.js @@ -112,7 +112,7 @@ Topics.getTopicsByTids = async function (tids, options) { ]); const sortOldToNew = callerSettings.topicPostSort === 'newest_to_oldest'; - result.topics.forEach(function (topic, i) { + result.topics.forEach((topic, i) => { if (topic) { topic.thumbs = result.thumbs[i]; topic.category = result.categoriesMap[topic.cid]; @@ -280,7 +280,7 @@ Topics.getMainPosts = async function (tids, uid) { async function getMainPosts(mainPids, uid) { const postData = await posts.getPostsByPids(mainPids, uid); - postData.forEach(function (post) { + postData.forEach((post) => { if (post) { post.index = 0; } diff --git a/src/topics/merge.js b/src/topics/merge.js index 2688ef69fc..9a00163039 100644 --- a/src/topics/merge.js +++ b/src/topics/merge.js @@ -17,9 +17,9 @@ module.exports = function (Topics) { const otherTids = tids.sort((a, b) => a - b) .filter(tid => tid && parseInt(tid, 10) !== parseInt(mergeIntoTid, 10)); - await async.eachSeries(otherTids, async function (tid) { + await async.eachSeries(otherTids, async (tid) => { const pids = await Topics.getPids(tid); - await async.eachSeries(pids, function (pid, next) { + await async.eachSeries(pids, (pid, next) => { Topics.movePostToTopic(uid, pid, mergeIntoTid, next); }); diff --git a/src/topics/posts.js b/src/topics/posts.js index cc19fc8a8b..5d1649d2de 100644 --- a/src/topics/posts.js +++ b/src/topics/posts.js @@ -44,17 +44,13 @@ module.exports = function (Topics) { ] = await Promise.all([ posts.hasBookmarked(pids, uid), posts.getVoteStatusByPostIDs(pids, uid), - getPostUserData('uid', async function (uids) { - return await posts.getUserInfoForPosts(uids, uid); - }), - getPostUserData('editor', async function (uids) { - return await user.getUsersFields(uids, ['uid', 'username', 'userslug']); - }), + getPostUserData('uid', async uids => await posts.getUserInfoForPosts(uids, uid)), + getPostUserData('editor', async uids => await user.getUsersFields(uids, ['uid', 'username', 'userslug'])), getPostReplies(pids, uid), Topics.addParentPosts(postData), ]); - postData.forEach(function (postObj, i) { + postData.forEach((postObj, i) => { if (postObj) { postObj.user = postObj.uid ? userData[postObj.uid] : { ...userData[postObj.uid] }; postObj.editor = postObj.editor ? editors[postObj.editor] : null; @@ -82,7 +78,7 @@ module.exports = function (Topics) { Topics.modifyPostsByPrivilege = function (topicData, topicPrivileges) { const loggedIn = parseInt(topicPrivileges.uid, 10) > 0; - topicData.posts.forEach(function (post) { + topicData.posts.forEach((post) => { if (post) { post.topicOwnerPost = parseInt(topicData.uid, 10) === parseInt(post.uid, 10); post.display_edit_tools = topicPrivileges.isAdminOrMod || (post.selfPost && topicPrivileges['posts:edit']); @@ -101,9 +97,7 @@ module.exports = function (Topics) { }; Topics.addParentPosts = async function (postData) { - var parentPids = postData.map(function (postObj) { - return postObj && postObj.hasOwnProperty('toPid') ? parseInt(postObj.toPid, 10) : null; - }).filter(Boolean); + var parentPids = postData.map(postObj => (postObj && postObj.hasOwnProperty('toPid') ? parseInt(postObj.toPid, 10) : null)).filter(Boolean); if (!parentPids.length) { return; @@ -114,21 +108,21 @@ module.exports = function (Topics) { const userData = await user.getUsersFields(parentUids, ['username']); var usersMap = {}; - userData.forEach(function (user) { + userData.forEach((user) => { usersMap[user.uid] = user.username; }); var parents = {}; - parentPosts.forEach(function (post, i) { + parentPosts.forEach((post, i) => { parents[parentPids[i]] = { username: usersMap[post.uid] }; }); - postData.forEach(function (post) { + postData.forEach((post) => { post.parent = parents[post.toPid]; }); }; Topics.calculatePostIndices = function (posts, start) { - posts.forEach(function (post, index) { + posts.forEach((post, index) => { if (post) { post.index = start + index + 1; } @@ -262,7 +256,7 @@ module.exports = function (Topics) { const uidMap = _.zipObject(uniqueUids, userData); const pidMap = _.zipObject(replyData.map(r => r.pid), replyData); - const returnData = arrayOfReplyPids.map(function (replyPids) { + const returnData = arrayOfReplyPids.map((replyPids) => { replyPids = replyPids.filter(pid => pidMap[pid]); const uidsUsed = {}; const currentData = { @@ -275,7 +269,7 @@ module.exports = function (Topics) { replyPids.sort((a, b) => parseInt(a, 10) - parseInt(b, 10)); - replyPids.forEach(function (replyPid) { + replyPids.forEach((replyPid) => { const replyData = pidMap[replyPid]; if (!uidsUsed[replyData.uid] && currentData.users.length < 6) { currentData.users.push(uidMap[replyData.uid]); diff --git a/src/topics/sorted.js b/src/topics/sorted.js index 8006ea5ff0..53bf8dee5b 100644 --- a/src/topics/sorted.js +++ b/src/topics/sorted.js @@ -58,7 +58,7 @@ module.exports = function (Topics) { async function getCidTids(params) { const sets = []; const pinnedSets = []; - params.cids.forEach(function (cid) { + params.cids.forEach((cid) => { if (params.sort === 'recent') { sets.push(`cid:${cid}:tids`); } else { diff --git a/src/topics/tags.js b/src/topics/tags.js index 8ae22c04c4..0051818c6a 100644 --- a/src/topics/tags.js +++ b/src/topics/tags.js @@ -98,7 +98,7 @@ module.exports = function (Topics) { }; Topics.updateTags = async function (data) { - await async.eachSeries(data, async function (tagData) { + await async.eachSeries(data, async (tagData) => { await db.setObject(`tag:${tagData.value}`, { color: tagData.color, bgColor: tagData.bgColor, @@ -107,7 +107,7 @@ module.exports = function (Topics) { }; Topics.renameTags = async function (data) { - await async.eachSeries(data, async function (tagData) { + await async.eachSeries(data, async (tagData) => { await renameTag(tagData.value, tagData.newName); }); }; @@ -128,7 +128,7 @@ module.exports = function (Topics) { }); } - await batch.processSortedSet(`tag:${tag}:topics`, async function (tids) { + await batch.processSortedSet(`tag:${tag}:topics`, async (tids) => { const topicData = await Topics.getTopicsFields(tids, ['tid', 'cid']); const cids = topicData.map(t => t.cid); topicData.forEach((t) => { allCids[t.cid] = true; }); @@ -210,7 +210,7 @@ module.exports = function (Topics) { }; async function removeTagsFromTopics(tags) { - await async.eachLimit(tags, 50, async function (tag) { + await async.eachLimit(tags, 50, async (tag) => { const tids = await db.getSortedSetRange(`tag:${tag}:topics`, 0, -1); if (!tids.length) { return; @@ -271,7 +271,7 @@ module.exports = function (Topics) { return []; } const tagData = await db.getObjects(tags.map(tag => `tag:${tag.value}`)); - tags.forEach(function (tag, index) { + tags.forEach((tag, index) => { tag.valueEscaped = validator.escape(String(tag.value)); tag.color = tagData[index] ? tagData[index].color : ''; tag.bgColor = tagData[index] ? tagData[index].bgColor : ''; @@ -304,7 +304,7 @@ module.exports = function (Topics) { const tagData = await Topics.getTagData(tags); const tagDataMap = _.zipObject(uniqueTopicTags, tagData); - topicTags.forEach(function (tags, index) { + topicTags.forEach((tags, index) => { if (Array.isArray(tags)) { topicTags[index] = tags.map(tag => tagDataMap[tag]); topicTags[index].sort((tag1, tag2) => tag2.value - tag1.value); @@ -443,7 +443,7 @@ module.exports = function (Topics) { } } - matches.sort(function (a, b) { + matches.sort((a, b) => { if (a.value < b.value) { return -1; } else if (a.value > b.value) { @@ -468,7 +468,7 @@ module.exports = function (Topics) { const tagData = await Topics.getTagData(tags.map(tag => ({ value: tag.value }))); - tagData.forEach(function (tag, index) { + tagData.forEach((tag, index) => { tag.score = tags[index].score; }); tagData.sort((a, b) => b.score - a.score); diff --git a/src/topics/teaser.js b/src/topics/teaser.js index b6da823e65..7b97976f7d 100644 --- a/src/topics/teaser.js +++ b/src/topics/teaser.js @@ -27,7 +27,7 @@ module.exports = function (Topics) { var teaserPids = []; var tidToPost = {}; - topics.forEach(function (topic) { + topics.forEach((topic) => { counts.push(topic && topic.postcount); if (topic) { if (topic.teaserPid === 'null') { @@ -52,10 +52,10 @@ module.exports = function (Topics) { const usersData = await user.getUsersFields(uids, ['uid', 'username', 'userslug', 'picture']); var users = {}; - usersData.forEach(function (user) { + usersData.forEach((user) => { users[user.uid] = user; }); - postData.forEach(function (post) { + postData.forEach((post) => { // If the post author isn't represented in the retrieved users' data, then it means they were deleted, assume guest. if (!users.hasOwnProperty(post.uid)) { post.uid = 0; @@ -69,7 +69,7 @@ module.exports = function (Topics) { const { tags } = await plugins.hooks.fire('filter:teasers.configureStripTags', { tags: utils.stripTags.concat(['img']) }); - var teasers = topics.map(function (topic, index) { + var teasers = topics.map((topic, index) => { if (!topic) { return null; } @@ -96,7 +96,7 @@ module.exports = function (Topics) { return teasers; } - return await async.mapSeries(teasers, async function (postData) { + return await async.mapSeries(teasers, async (postData) => { if (blockedUids.includes(parseInt(postData.uid, 10))) { return await getPreviousNonBlockedPost(postData, blockedUids); } diff --git a/src/topics/unread.js b/src/topics/unread.js index b7acce66af..1e97484655 100644 --- a/src/topics/unread.js +++ b/src/topics/unread.js @@ -143,7 +143,7 @@ module.exports = function (Topics) { const filterCids = params.cid && params.cid.map(cid => parseInt(cid, 10)); - topicData.forEach(function (topic) { + topicData.forEach((topic) => { if (topic && topic.cid && (!filterCids || filterCids.includes(topic.cid)) && !blockedUids.includes(topic.uid)) { if (isTopicsFollowed[topic.tid] || userCidState[topic.cid] === categories.watchStates.watching) { tidsByFilter[''].push(topic.tid); @@ -210,13 +210,11 @@ module.exports = function (Topics) { const userScores = _.zipObject(params.tids, results); - return await async.filter(params.tids, async function (tid) { - return await doesTidHaveUnblockedUnreadPosts(tid, { - blockedUids: params.blockedUids, - topicTimestamp: topicScores[tid], - userLastReadTimestamp: userScores[tid], - }); - }); + return await async.filter(params.tids, async tid => await doesTidHaveUnblockedUnreadPosts(tid, { + blockedUids: params.blockedUids, + topicTimestamp: topicScores[tid], + userLastReadTimestamp: userScores[tid], + })); } async function doesTidHaveUnblockedUnreadPosts(tid, params) { @@ -335,14 +333,14 @@ module.exports = function (Topics) { ]); const cutoff = await Topics.unreadCutoff(uid); - const result = tids.map(function (tid, index) { + const result = tids.map((tid, index) => { const read = !tids_unread[index] && (topicScores[index] < cutoff || !!(userScores[index] && userScores[index] >= topicScores[index])); return { tid: tid, read: read, index: index }; }); - return await async.map(result, async function (data) { + return await async.map(result, async (data) => { if (data.read) { return true; } diff --git a/src/upgrade.js b/src/upgrade.js index 9c2da9571a..330330252b 100644 --- a/src/upgrade.js +++ b/src/upgrade.js @@ -26,7 +26,7 @@ Upgrade.getAll = async function () { let files = await file.walk(path.join(__dirname, './upgrades')); // Sort the upgrade scripts based on version - files = files.filter(file => path.basename(file) !== 'TEMPLATE').sort(function (a, b) { + files = files.filter(file => path.basename(file) !== 'TEMPLATE').sort((a, b) => { const versionA = path.dirname(a).split(path.sep).pop(); const versionB = path.dirname(b).split(path.sep).pop(); const semverCompare = semver.compare(versionA, versionB); @@ -66,7 +66,7 @@ Upgrade.appendPluginScripts = async function (files) { try { const pluginConfig = require(configPath); if (pluginConfig.hasOwnProperty('upgrades') && Array.isArray(pluginConfig.upgrades)) { - pluginConfig.upgrades.forEach(function (script) { + pluginConfig.upgrades.forEach((script) => { files.push(path.join(path.dirname(configPath), script)); }); } @@ -96,7 +96,7 @@ Upgrade.run = async function () { ]); let skipped = 0; - const queue = available.filter(function (cur) { + const queue = available.filter((cur) => { const upgradeRan = completed.includes(path.basename(cur, '.js')); if (upgradeRan) { skipped += 1; diff --git a/src/upgrades/1.0.0/chat_room_hashes.js b/src/upgrades/1.0.0/chat_room_hashes.js index 2f4efeeaf1..e77bf00058 100644 --- a/src/upgrades/1.0.0/chat_room_hashes.js +++ b/src/upgrades/1.0.0/chat_room_hashes.js @@ -8,15 +8,15 @@ module.exports = { name: 'Chat room hashes', timestamp: Date.UTC(2015, 11, 23), method: function (callback) { - db.getObjectField('global', 'nextChatRoomId', function (err, nextChatRoomId) { + db.getObjectField('global', 'nextChatRoomId', (err, nextChatRoomId) => { if (err) { return callback(err); } var currentChatRoomId = 1; - async.whilst(function (next) { + async.whilst((next) => { next(null, currentChatRoomId <= nextChatRoomId); - }, function (next) { - db.getSortedSetRange(`chat:room:${currentChatRoomId}:uids`, 0, 0, function (err, uids) { + }, (next) => { + db.getSortedSetRange(`chat:room:${currentChatRoomId}:uids`, 0, 0, (err, uids) => { if (err) { return next(err); } @@ -25,7 +25,7 @@ module.exports = { return next(); } - db.setObject(`chat:room:${currentChatRoomId}`, { owner: uids[0], roomId: currentChatRoomId }, function (err) { + db.setObject(`chat:room:${currentChatRoomId}`, { owner: uids[0], roomId: currentChatRoomId }, (err) => { if (err) { return next(err); } diff --git a/src/upgrades/1.0.0/chat_upgrade.js b/src/upgrades/1.0.0/chat_upgrade.js index 3773e3f72c..83ef810fa4 100644 --- a/src/upgrades/1.0.0/chat_upgrade.js +++ b/src/upgrades/1.0.0/chat_upgrade.js @@ -9,7 +9,7 @@ module.exports = { name: 'Upgrading chats', timestamp: Date.UTC(2015, 11, 15), method: function (callback) { - db.getObjectFields('global', ['nextMid', 'nextChatRoomId'], function (err, globalData) { + db.getObjectFields('global', ['nextMid', 'nextChatRoomId'], (err, globalData) => { if (err) { return callback(err); } @@ -18,10 +18,10 @@ module.exports = { var roomId = globalData.nextChatRoomId || 1; var currentMid = 1; - async.whilst(function (next) { + async.whilst((next) => { next(null, currentMid <= globalData.nextMid); - }, function (next) { - db.getObject(`message:${currentMid}`, function (err, message) { + }, (next) => { + db.getObject(`message:${currentMid}`, (err, message) => { var msgTime; function addMessageToUids(roomId, callback) { @@ -46,7 +46,7 @@ module.exports = { if (rooms[pairID]) { winston.verbose(`adding message ${currentMid} to existing roomID ${roomId}`); - addMessageToUids(rooms[pairID], function (err) { + addMessageToUids(rooms[pairID], (err) => { if (err) { return next(err); } @@ -68,7 +68,7 @@ module.exports = { function (next) { addMessageToUids(roomId, next); }, - ], function (err) { + ], (err) => { if (err) { return next(err); } diff --git a/src/upgrades/1.0.0/user_best_posts.js b/src/upgrades/1.0.0/user_best_posts.js index 3b2f85ebe4..a45e2b4741 100644 --- a/src/upgrades/1.0.0/user_best_posts.js +++ b/src/upgrades/1.0.0/user_best_posts.js @@ -12,9 +12,9 @@ module.exports = { var batch = require('../../batch'); var progress = this.progress; - batch.processSortedSet('posts:pid', function (ids, next) { - async.eachSeries(ids, function (id, next) { - db.getObjectFields(`post:${id}`, ['pid', 'uid', 'votes'], function (err, postData) { + batch.processSortedSet('posts:pid', (ids, next) => { + async.eachSeries(ids, (id, next) => { + db.getObjectFields(`post:${id}`, ['pid', 'uid', 'votes'], (err, postData) => { if (err) { return next(err); } diff --git a/src/upgrades/1.0.0/users_notvalidated.js b/src/upgrades/1.0.0/users_notvalidated.js index 9fd9dfeb3c..7909a939bc 100644 --- a/src/upgrades/1.0.0/users_notvalidated.js +++ b/src/upgrades/1.0.0/users_notvalidated.js @@ -11,9 +11,9 @@ module.exports = { method: function (callback) { var batch = require('../../batch'); var now = Date.now(); - batch.processSortedSet('users:joindate', function (ids, next) { - async.eachSeries(ids, function (id, next) { - db.getObjectFields(`user:${id}`, ['uid', 'email:confirmed'], function (err, userData) { + batch.processSortedSet('users:joindate', (ids, next) => { + async.eachSeries(ids, (id, next) => { + db.getObjectFields(`user:${id}`, ['uid', 'email:confirmed'], (err, userData) => { if (err) { return next(err); } diff --git a/src/upgrades/1.1.0/assign_topic_read_privilege.js b/src/upgrades/1.1.0/assign_topic_read_privilege.js index 75ff4d4b18..f2835da778 100644 --- a/src/upgrades/1.1.0/assign_topic_read_privilege.js +++ b/src/upgrades/1.1.0/assign_topic_read_privilege.js @@ -12,13 +12,13 @@ module.exports = { var groupsAPI = require('../../groups'); var privilegesAPI = require('../../privileges'); - db.getSortedSetRange('categories:cid', 0, -1, function (err, cids) { + db.getSortedSetRange('categories:cid', 0, -1, (err, cids) => { if (err) { return callback(err); } - async.eachSeries(cids, function (cid, next) { - privilegesAPI.categories.list(cid, function (err, data) { + async.eachSeries(cids, (cid, next) => { + privilegesAPI.categories.list(cid, (err, data) => { if (err) { return next(err); } @@ -28,9 +28,9 @@ module.exports = { async.waterfall([ function (next) { - async.eachSeries(groups, function (group, next) { + async.eachSeries(groups, (group, next) => { if (group.privileges['groups:read']) { - return groupsAPI.join(`cid:${cid}:privileges:groups:topics:read`, group.name, function (err) { + return groupsAPI.join(`cid:${cid}:privileges:groups:topics:read`, group.name, (err) => { if (!err) { winston.verbose(`cid:${cid}:privileges:groups:topics:read granted to gid: ${group.name}`); } @@ -43,9 +43,9 @@ module.exports = { }, next); }, function (next) { - async.eachSeries(users, function (user, next) { + async.eachSeries(users, (user, next) => { if (user.privileges.read) { - return groupsAPI.join(`cid:${cid}:privileges:topics:read`, user.uid, function (err) { + return groupsAPI.join(`cid:${cid}:privileges:topics:read`, user.uid, (err) => { if (!err) { winston.verbose(`cid:${cid}:privileges:topics:read granted to uid: ${user.uid}`); } @@ -57,7 +57,7 @@ module.exports = { next(null); }, next); }, - ], function (err) { + ], (err) => { if (!err) { winston.verbose(`-- cid ${cid} upgraded`); } diff --git a/src/upgrades/1.1.0/dismiss_flags_from_deleted_topics.js b/src/upgrades/1.1.0/dismiss_flags_from_deleted_topics.js index a47656d03e..489cba777b 100644 --- a/src/upgrades/1.1.0/dismiss_flags_from_deleted_topics.js +++ b/src/upgrades/1.1.0/dismiss_flags_from_deleted_topics.js @@ -22,16 +22,12 @@ module.exports = { posts.getPostsFields(pids, ['tid'], next); }, function (_tids, next) { - tids = _tids.map(function (a) { - return a.tid; - }); + tids = _tids.map(a => a.tid); topics.getTopicsFields(tids, ['deleted'], next); }, function (state, next) { - var toDismiss = state.map(function (a, idx) { - return parseInt(a.deleted, 10) === 1 ? pids[idx] : null; - }).filter(Boolean); + var toDismiss = state.map((a, idx) => (parseInt(a.deleted, 10) === 1 ? pids[idx] : null)).filter(Boolean); winston.verbose(`[2016/04/29] ${toDismiss.length} dismissable flags found`); async.each(toDismiss, dismissFlag, next); @@ -76,12 +72,12 @@ function dismissFlag(pid, callback) { function (next) { async.series([ function (next) { - db.getSortedSetRange(`pid:${pid}:flag:uids`, 0, -1, function (err, uids) { + db.getSortedSetRange(`pid:${pid}:flag:uids`, 0, -1, (err, uids) => { if (err) { return next(err); } - async.each(uids, function (uid, next) { + async.each(uids, (uid, next) => { var nid = `post_flag:${pid}:uid:${uid}`; async.parallel([ async.apply(db.delete, `notifications:${nid}`), diff --git a/src/upgrades/1.1.0/group_title_update.js b/src/upgrades/1.1.0/group_title_update.js index 94ca3b01a2..72215de139 100644 --- a/src/upgrades/1.1.0/group_title_update.js +++ b/src/upgrades/1.1.0/group_title_update.js @@ -12,18 +12,16 @@ module.exports = { var user = require('../../user'); var batch = require('../../batch'); var count = 0; - batch.processSortedSet('users:joindate', function (uids, next) { + batch.processSortedSet('users:joindate', (uids, next) => { winston.verbose(`upgraded ${count} users`); - user.getMultipleUserSettings(uids, function (err, settings) { + user.getMultipleUserSettings(uids, (err, settings) => { if (err) { return next(err); } count += uids.length; - settings = settings.filter(function (setting) { - return setting && setting.groupTitle; - }); + settings = settings.filter(setting => setting && setting.groupTitle); - async.each(settings, function (setting, next) { + async.each(settings, (setting, next) => { db.setObjectField(`user:${setting.uid}`, 'groupTitle', setting.groupTitle, next); }, next); }); diff --git a/src/upgrades/1.1.0/separate_upvote_downvote.js b/src/upgrades/1.1.0/separate_upvote_downvote.js index 17d16439f5..ae93a820b8 100644 --- a/src/upgrades/1.1.0/separate_upvote_downvote.js +++ b/src/upgrades/1.1.0/separate_upvote_downvote.js @@ -14,10 +14,10 @@ module.exports = { var count = 0; var progress = this.progress; - batch.processSortedSet('posts:pid', function (pids, next) { + batch.processSortedSet('posts:pid', (pids, next) => { winston.verbose(`upgraded ${count} posts`); count += pids.length; - async.each(pids, function (pid, next) { + async.each(pids, (pid, next) => { async.parallel({ upvotes: function (next) { db.setCount(`pid:${pid}:upvote`, next); @@ -25,7 +25,7 @@ module.exports = { downvotes: function (next) { db.setCount(`pid:${pid}:downvote`, next); }, - }, function (err, results) { + }, (err, results) => { if (err) { return next(err); } diff --git a/src/upgrades/1.1.0/user_post_count_per_tid.js b/src/upgrades/1.1.0/user_post_count_per_tid.js index 77e86325d7..ddc32759af 100644 --- a/src/upgrades/1.1.0/user_post_count_per_tid.js +++ b/src/upgrades/1.1.0/user_post_count_per_tid.js @@ -12,15 +12,15 @@ module.exports = { var batch = require('../../batch'); var topics = require('../../topics'); var count = 0; - batch.processSortedSet('topics:tid', function (tids, next) { + batch.processSortedSet('topics:tid', (tids, next) => { winston.verbose(`upgraded ${count} topics`); count += tids.length; - async.each(tids, function (tid, next) { - db.delete(`tid:${tid}:posters`, function (err) { + async.each(tids, (tid, next) => { + db.delete(`tid:${tid}:posters`, (err) => { if (err) { return next(err); } - topics.getPids(tid, function (err, pids) { + topics.getPids(tid, (err, pids) => { if (err) { return next(err); } @@ -29,8 +29,8 @@ module.exports = { return next(); } - async.eachSeries(pids, function (pid, next) { - db.getObjectField(`post:${pid}`, 'uid', function (err, uid) { + async.eachSeries(pids, (pid, next) => { + db.getObjectField(`post:${pid}`, 'uid', (err, uid) => { if (err) { return next(err); } diff --git a/src/upgrades/1.1.1/remove_negative_best_posts.js b/src/upgrades/1.1.1/remove_negative_best_posts.js index fc71b4f524..c80704f69c 100644 --- a/src/upgrades/1.1.1/remove_negative_best_posts.js +++ b/src/upgrades/1.1.1/remove_negative_best_posts.js @@ -10,8 +10,8 @@ module.exports = { timestamp: Date.UTC(2016, 7, 5), method: function (callback) { var batch = require('../../batch'); - batch.processSortedSet('users:joindate', function (ids, next) { - async.each(ids, function (id, next) { + batch.processSortedSet('users:joindate', (ids, next) => { + async.each(ids, (id, next) => { winston.verbose(`processing uid ${id}`); db.sortedSetsRemoveRangeByScore([`uid:${id}:posts:votes`], '-inf', 0, next); }, next); diff --git a/src/upgrades/1.1.1/upload_privileges.js b/src/upgrades/1.1.1/upload_privileges.js index 454f538a8a..d1668a95cf 100644 --- a/src/upgrades/1.1.1/upload_privileges.js +++ b/src/upgrades/1.1.1/upload_privileges.js @@ -11,17 +11,17 @@ module.exports = { var privilegesAPI = require('../../privileges'); var meta = require('../../meta'); - db.getSortedSetRange('categories:cid', 0, -1, function (err, cids) { + db.getSortedSetRange('categories:cid', 0, -1, (err, cids) => { if (err) { return callback(err); } - async.eachSeries(cids, function (cid, next) { - privilegesAPI.categories.list(cid, function (err, data) { + async.eachSeries(cids, (cid, next) => { + privilegesAPI.categories.list(cid, (err, data) => { if (err) { return next(err); } - async.eachSeries(data.groups, function (group, next) { + async.eachSeries(data.groups, (group, next) => { if (group.name === 'guests' && parseInt(meta.config.allowGuestUploads, 10) !== 1) { return next(); } diff --git a/src/upgrades/1.10.0/hash_recent_ip_addresses.js b/src/upgrades/1.10.0/hash_recent_ip_addresses.js index 6d04171074..38ae98f798 100644 --- a/src/upgrades/1.10.0/hash_recent_ip_addresses.js +++ b/src/upgrades/1.10.0/hash_recent_ip_addresses.js @@ -15,8 +15,8 @@ module.exports = { var hashed = /[a-f0-9]{32}/; let hash; - batch.processSortedSet('ip:recent', function (ips, next) { - async.each(ips, function (set, next) { + batch.processSortedSet('ip:recent', (ips, next) => { + async.each(ips, (set, next) => { // Short circuit if already processed if (hashed.test(set.value)) { progress.incr(); @@ -28,7 +28,7 @@ module.exports = { async.series([ async.apply(db.sortedSetAdd, 'ip:recent', set.score, hash), async.apply(db.sortedSetRemove, 'ip:recent', set.value), - ], function (err) { + ], (err) => { progress.incr(); next(err); }); diff --git a/src/upgrades/1.10.0/post_history_privilege.js b/src/upgrades/1.10.0/post_history_privilege.js index 917098a0af..64b515e5fa 100644 --- a/src/upgrades/1.10.0/post_history_privilege.js +++ b/src/upgrades/1.10.0/post_history_privilege.js @@ -10,11 +10,11 @@ module.exports = { name: 'Give post history viewing privilege to registered-users on all categories', timestamp: Date.UTC(2018, 5, 7), method: function (callback) { - db.getSortedSetRange('categories:cid', 0, -1, function (err, cids) { + db.getSortedSetRange('categories:cid', 0, -1, (err, cids) => { if (err) { return callback(err); } - async.eachSeries(cids, function (cid, next) { + async.eachSeries(cids, (cid, next) => { privileges.categories.give(['groups:posts:history'], cid, 'registered-users', next); }, callback); }); diff --git a/src/upgrades/1.10.0/view_deleted_privilege.js b/src/upgrades/1.10.0/view_deleted_privilege.js index 00bf9474f9..fdeb3f38d3 100644 --- a/src/upgrades/1.10.0/view_deleted_privilege.js +++ b/src/upgrades/1.10.0/view_deleted_privilege.js @@ -10,11 +10,11 @@ module.exports = { name: 'Give deleted post viewing privilege to moderators on all categories', timestamp: Date.UTC(2018, 5, 8), method: function (callback) { - db.getSortedSetRange('categories:cid', 0, -1, function (err, cids) { + db.getSortedSetRange('categories:cid', 0, -1, (err, cids) => { if (err) { return callback(err); } - async.eachSeries(cids, function (cid, next) { + async.eachSeries(cids, (cid, next) => { async.waterfall([ async.apply(db.getSortedSetRange.bind(db), `group:cid:${cid}:privileges:moderate:members`, 0, -1), function (uids, next) { diff --git a/src/upgrades/1.10.2/event_filters.js b/src/upgrades/1.10.2/event_filters.js index b016d7358f..96b2341aa1 100644 --- a/src/upgrades/1.10.2/event_filters.js +++ b/src/upgrades/1.10.2/event_filters.js @@ -11,11 +11,11 @@ module.exports = { method: function (callback) { const progress = this.progress; - batch.processSortedSet('events:time', function (eids, next) { - async.eachSeries(eids, function (eid, next) { + batch.processSortedSet('events:time', (eids, next) => { + async.eachSeries(eids, (eid, next) => { progress.incr(); - db.getObject(`event:${eid}`, function (err, eventData) { + db.getObject(`event:${eid}`, (err, eventData) => { if (err) { return next(err); } diff --git a/src/upgrades/1.10.2/fix_category_post_zsets.js b/src/upgrades/1.10.2/fix_category_post_zsets.js index b9aef92bd7..fc4bf54dc1 100644 --- a/src/upgrades/1.10.2/fix_category_post_zsets.js +++ b/src/upgrades/1.10.2/fix_category_post_zsets.js @@ -11,16 +11,14 @@ module.exports = { method: function (callback) { const progress = this.progress; - db.getSortedSetRange('categories:cid', 0, -1, function (err, cids) { + db.getSortedSetRange('categories:cid', 0, -1, (err, cids) => { if (err) { return callback(err); } - var keys = cids.map(function (cid) { - return `cid:${cid}:pids`; - }); + var keys = cids.map(cid => `cid:${cid}:pids`); var posts = require('../../posts'); - batch.processSortedSet('posts:pid', function (postData, next) { - async.eachSeries(postData, function (postData, next) { + batch.processSortedSet('posts:pid', (postData, next) => { + async.eachSeries(postData, (postData, next) => { progress.incr(); var pid = postData.value; var timestamp = postData.score; @@ -35,7 +33,7 @@ module.exports = { }, function (isMembers, next) { var memberCids = []; - isMembers.forEach(function (isMember, index) { + isMembers.forEach((isMember, index) => { if (isMember) { memberCids.push(cids[index]); } diff --git a/src/upgrades/1.10.2/fix_category_topic_zsets.js b/src/upgrades/1.10.2/fix_category_topic_zsets.js index 3679c13dc4..c06c11379b 100644 --- a/src/upgrades/1.10.2/fix_category_topic_zsets.js +++ b/src/upgrades/1.10.2/fix_category_topic_zsets.js @@ -12,8 +12,8 @@ module.exports = { const progress = this.progress; var topics = require('../../topics'); - batch.processSortedSet('topics:tid', function (tids, next) { - async.eachSeries(tids, function (tid, next) { + batch.processSortedSet('topics:tid', (tids, next) => { + async.eachSeries(tids, (tid, next) => { progress.incr(); async.waterfall([ diff --git a/src/upgrades/1.10.2/postgres_sessions.js b/src/upgrades/1.10.2/postgres_sessions.js index 850ae5d1b9..222307fa4c 100644 --- a/src/upgrades/1.10.2/postgres_sessions.js +++ b/src/upgrades/1.10.2/postgres_sessions.js @@ -34,7 +34,7 @@ ALTER TABLE "session" CLUSTER "session"; ANALYZE "session"; -COMMIT;`, function (err) { +COMMIT;`, (err) => { callback(err); }); }, diff --git a/src/upgrades/1.10.2/upgrade_bans_to_hashes.js b/src/upgrades/1.10.2/upgrade_bans_to_hashes.js index 0a2cd722fb..cb8e883845 100644 --- a/src/upgrades/1.10.2/upgrade_bans_to_hashes.js +++ b/src/upgrades/1.10.2/upgrade_bans_to_hashes.js @@ -12,8 +12,8 @@ module.exports = { method: function (callback) { const progress = this.progress; - batch.processSortedSet('users:joindate', function (uids, next) { - async.eachSeries(uids, function (uid, next) { + batch.processSortedSet('users:joindate', (uids, next) => { + async.eachSeries(uids, (uid, next) => { progress.incr(); async.parallel({ @@ -26,7 +26,7 @@ module.exports = { userData: function (next) { db.getObjectFields(`user:${uid}`, ['banned', 'banned:expire', 'joindate', 'lastposttime', 'lastonline'], next); }, - }, function (err, results) { + }, (err, results) => { function addBan(key, data, callback) { async.waterfall([ function (next) { @@ -54,11 +54,9 @@ module.exports = { } // process ban history - async.eachSeries(results.bans, function (ban, next) { + async.eachSeries(results.bans, (ban, next) => { function findReason(score) { - return results.reasons.find(function (reasonData) { - return reasonData.score === score; - }); + return results.reasons.find(reasonData => reasonData.score === score); } const reasonData = findReason(ban.score); const banKey = `uid:${uid}:ban:${ban.score}`; @@ -71,7 +69,7 @@ module.exports = { data.reason = reasonData.value; } addBan(banKey, data, next); - }, function (err) { + }, (err) => { next(err); }); }); diff --git a/src/upgrades/1.10.2/username_email_history.js b/src/upgrades/1.10.2/username_email_history.js index 14bba15c18..d38d7eafdb 100644 --- a/src/upgrades/1.10.2/username_email_history.js +++ b/src/upgrades/1.10.2/username_email_history.js @@ -12,8 +12,8 @@ module.exports = { method: function (callback) { const progress = this.progress; - batch.processSortedSet('users:joindate', function (ids, next) { - async.each(ids, function (uid, next) { + batch.processSortedSet('users:joindate', (ids, next) => { + async.each(ids, (uid, next) => { async.parallel([ function (next) { // Username @@ -57,7 +57,7 @@ module.exports = { }, ], next); }, - ], function (err) { + ], (err) => { progress.incr(); setImmediate(next, err); }); diff --git a/src/upgrades/1.11.0/navigation_visibility_groups.js b/src/upgrades/1.11.0/navigation_visibility_groups.js index c6d88a4d24..53b3a1d9a7 100644 --- a/src/upgrades/1.11.0/navigation_visibility_groups.js +++ b/src/upgrades/1.11.0/navigation_visibility_groups.js @@ -13,7 +13,7 @@ module.exports = { navigationAdmin.get(next); }, function (data, next) { - data.forEach(function (navItem) { + data.forEach((navItem) => { if (navItem && navItem.properties) { navItem.groups = []; if (navItem.properties.adminOnly) { diff --git a/src/upgrades/1.11.0/widget_visibility_groups.js b/src/upgrades/1.11.0/widget_visibility_groups.js index 1cf95cbfbd..fecbfc3947 100644 --- a/src/upgrades/1.11.0/widget_visibility_groups.js +++ b/src/upgrades/1.11.0/widget_visibility_groups.js @@ -13,11 +13,11 @@ module.exports = { widgetAdmin.getAreas(next); }, function (areas, next) { - async.eachSeries(areas, function (area, next) { + async.eachSeries(areas, (area, next) => { if (area.data.length) { // area.data is actually an array of widgets area.widgets = area.data; - area.widgets.forEach(function (widget) { + area.widgets.forEach((widget) => { if (widget && widget.data) { const groupsToShow = ['administrators', 'Global Moderators']; if (widget.data['hide-guests'] !== 'on') { diff --git a/src/upgrades/1.11.1/remove_ignored_cids_per_user.js b/src/upgrades/1.11.1/remove_ignored_cids_per_user.js index 9ce08a49a5..991fcdd37e 100644 --- a/src/upgrades/1.11.1/remove_ignored_cids_per_user.js +++ b/src/upgrades/1.11.1/remove_ignored_cids_per_user.js @@ -10,7 +10,7 @@ module.exports = { method: function (callback) { const progress = this.progress; - batch.processSortedSet('users:joindate', function (uids, next) { + batch.processSortedSet('users:joindate', (uids, next) => { progress.incr(uids.length); const keys = uids.map(uid => `uid:${uid}:ignored:cids`); db.deleteAll(keys, next); diff --git a/src/upgrades/1.12.0/category_watch_state.js b/src/upgrades/1.12.0/category_watch_state.js index 9f1cda40e6..e178004cde 100644 --- a/src/upgrades/1.12.0/category_watch_state.js +++ b/src/upgrades/1.12.0/category_watch_state.js @@ -18,11 +18,11 @@ module.exports = { }, function (cids, next) { keys = cids.map(cid => `cid:${cid}:ignorers`); - batch.processSortedSet('users:joindate', function (uids, next) { + batch.processSortedSet('users:joindate', (uids, next) => { progress.incr(uids.length); - async.eachSeries(cids, function (cid, next) { - db.isSortedSetMembers(`cid:${cid}:ignorers`, uids, function (err, isMembers) { + async.eachSeries(cids, (cid, next) => { + db.isSortedSetMembers(`cid:${cid}:ignorers`, uids, (err, isMembers) => { if (err) { return next(err); } diff --git a/src/upgrades/1.12.1/clear_username_email_history.js b/src/upgrades/1.12.1/clear_username_email_history.js index d84f916374..200d2fc9eb 100644 --- a/src/upgrades/1.12.1/clear_username_email_history.js +++ b/src/upgrades/1.12.1/clear_username_email_history.js @@ -10,17 +10,17 @@ module.exports = { method: function (callback) { const progress = this.progress; var currentUid = 1; - db.getObjectField('global', 'nextUid', function (err, nextUid) { + db.getObjectField('global', 'nextUid', (err, nextUid) => { if (err) { return callback(err); } progress.total = nextUid; - async.whilst(function (next) { + async.whilst((next) => { next(null, currentUid < nextUid); }, - function (next) { + (next) => { progress.incr(); - user.exists(currentUid, function (err, exists) { + user.exists(currentUid, (err, exists) => { if (err) { return next(err); } @@ -28,7 +28,7 @@ module.exports = { currentUid += 1; return next(); } - db.deleteAll([`user:${currentUid}:usernames`, `user:${currentUid}:emails`], function (err) { + db.deleteAll([`user:${currentUid}:usernames`, `user:${currentUid}:emails`], (err) => { if (err) { return next(err); } @@ -37,7 +37,7 @@ module.exports = { }); }); }, - function (err) { + (err) => { callback(err); }); }); diff --git a/src/upgrades/1.12.1/moderation_notes_refactor.js b/src/upgrades/1.12.1/moderation_notes_refactor.js index 958466a410..fe53083a88 100644 --- a/src/upgrades/1.12.1/moderation_notes_refactor.js +++ b/src/upgrades/1.12.1/moderation_notes_refactor.js @@ -11,15 +11,15 @@ module.exports = { method: function (callback) { var progress = this.progress; - batch.processSortedSet('users:joindate', function (ids, next) { - async.each(ids, function (uid, next) { + batch.processSortedSet('users:joindate', (ids, next) => { + async.each(ids, (uid, next) => { progress.incr(); - db.getSortedSetRevRange(`uid:${uid}:moderation:notes`, 0, -1, function (err, notes) { + db.getSortedSetRevRange(`uid:${uid}:moderation:notes`, 0, -1, (err, notes) => { if (err || !notes.length) { return next(err); } - async.eachSeries(notes, function (note, next) { + async.eachSeries(notes, (note, next) => { var noteData; async.waterfall([ function (next) { diff --git a/src/upgrades/1.12.1/post_upload_sizes.js b/src/upgrades/1.12.1/post_upload_sizes.js index 44732b1ad3..ffd04bcdda 100644 --- a/src/upgrades/1.12.1/post_upload_sizes.js +++ b/src/upgrades/1.12.1/post_upload_sizes.js @@ -11,8 +11,8 @@ module.exports = { method: function (callback) { const progress = this.progress; - batch.processSortedSet('posts:pid', function (postData, next) { - async.eachSeries(postData, async function (pid) { + batch.processSortedSet('posts:pid', (postData, next) => { + async.eachSeries(postData, async (pid) => { const uploads = await posts.uploads.list(pid); await posts.uploads.saveSize(uploads); progress.incr(); diff --git a/src/upgrades/1.12.3/give_mod_info_privilege.js b/src/upgrades/1.12.3/give_mod_info_privilege.js index bcb49b5bc2..e66d53bdf4 100644 --- a/src/upgrades/1.12.3/give_mod_info_privilege.js +++ b/src/upgrades/1.12.3/give_mod_info_privilege.js @@ -14,7 +14,7 @@ module.exports = { db.getSortedSetRevRange('categories:cid', 0, -1, next); }, function (cids, next) { - async.eachSeries(cids, function (cid, next) { + async.eachSeries(cids, (cid, next) => { async.waterfall([ function (next) { givePrivsToModerators(cid, '', next); @@ -35,7 +35,7 @@ module.exports = { db.getSortedSetRevRange(`group:cid:${cid}:privileges:${groupPrefix}moderate:members`, 0, -1, next); }, function (members, next) { - async.eachSeries(members, function (member, next) { + async.eachSeries(members, (member, next) => { groups.join(['cid:0:privileges:view:users:info'], member, next); }, next); }, diff --git a/src/upgrades/1.12.3/give_mod_privileges.js b/src/upgrades/1.12.3/give_mod_privileges.js index c8d0fcda7d..f2dcf1e9ca 100644 --- a/src/upgrades/1.12.3/give_mod_privileges.js +++ b/src/upgrades/1.12.3/give_mod_privileges.js @@ -48,7 +48,7 @@ module.exports = { db.getSortedSetRevRange('categories:cid', 0, -1, next); }, function (cids, next) { - async.eachSeries(cids, function (cid, next) { + async.eachSeries(cids, (cid, next) => { async.waterfall([ function (next) { givePrivsToModerators(cid, '', next); @@ -68,16 +68,14 @@ module.exports = { ], callback); function givePrivsToModerators(cid, groupPrefix, callback) { - const privGroups = modPrivileges.map(function (priv) { - return `cid:${cid}:privileges:${groupPrefix}${priv}`; - }); + const privGroups = modPrivileges.map(priv => `cid:${cid}:privileges:${groupPrefix}${priv}`); async.waterfall([ function (next) { db.getSortedSetRevRange(`group:cid:${cid}:privileges:${groupPrefix}moderate:members`, 0, -1, next); }, function (members, next) { - async.eachSeries(members, function (member, next) { + async.eachSeries(members, (member, next) => { groups.join(privGroups, member, next); }, next); }, diff --git a/src/upgrades/1.12.3/user_pid_sets.js b/src/upgrades/1.12.3/user_pid_sets.js index ac85abdb5e..a9692d6d4c 100644 --- a/src/upgrades/1.12.3/user_pid_sets.js +++ b/src/upgrades/1.12.3/user_pid_sets.js @@ -13,7 +13,7 @@ module.exports = { method: function (callback) { const progress = this.progress; - batch.processSortedSet('posts:pid', function (pids, next) { + batch.processSortedSet('posts:pid', (pids, next) => { progress.incr(pids.length); let postData; async.waterfall([ @@ -27,7 +27,7 @@ module.exports = { }, function (topicData, next) { const bulk = []; - postData.forEach(function (p, index) { + postData.forEach((p, index) => { if (p && p.uid && p.pid && p.tid && p.timestamp) { bulk.push([`cid:${topicData[index].cid}:uid:${p.uid}:pids`, p.timestamp, p.pid]); if (p.votes > 0) { diff --git a/src/upgrades/1.13.0/clean_flag_byCid.js b/src/upgrades/1.13.0/clean_flag_byCid.js index 7da4891337..c0968e2535 100644 --- a/src/upgrades/1.13.0/clean_flag_byCid.js +++ b/src/upgrades/1.13.0/clean_flag_byCid.js @@ -9,7 +9,7 @@ module.exports = { method: async function () { const progress = this.progress; - await batch.processSortedSet('flags:datetime', async function (flagIds) { + await batch.processSortedSet('flags:datetime', async (flagIds) => { progress.incr(flagIds.length); const flagData = await db.getObjects(flagIds.map(id => `flag:${id}`)); const bulkRemove = []; diff --git a/src/upgrades/1.13.0/clean_post_topic_hash.js b/src/upgrades/1.13.0/clean_post_topic_hash.js index 30a5038d53..e797b576b5 100644 --- a/src/upgrades/1.13.0/clean_post_topic_hash.js +++ b/src/upgrades/1.13.0/clean_post_topic_hash.js @@ -14,11 +14,11 @@ module.exports = { }; async function cleanPost(progress) { - await batch.processSortedSet('posts:pid', async function (pids) { + await batch.processSortedSet('posts:pid', async (pids) => { progress.incr(pids.length); const postData = await db.getObjects(pids.map(pid => `post:${pid}`)); - await Promise.all(postData.map(async function (post) { + await Promise.all(postData.map(async (post) => { if (!post) { return; } @@ -56,10 +56,10 @@ async function cleanPost(progress) { } async function cleanTopic(progress) { - await batch.processSortedSet('topics:tid', async function (tids) { + await batch.processSortedSet('topics:tid', async (tids) => { progress.incr(tids.length); const topicData = await db.getObjects(tids.map(tid => `topic:${tid}`)); - await Promise.all(topicData.map(async function (topic) { + await Promise.all(topicData.map(async (topic) => { if (!topic) { return; } diff --git a/src/upgrades/1.13.0/cleanup_old_notifications.js b/src/upgrades/1.13.0/cleanup_old_notifications.js index dbd70eefb1..bf4cdb9c89 100644 --- a/src/upgrades/1.13.0/cleanup_old_notifications.js +++ b/src/upgrades/1.13.0/cleanup_old_notifications.js @@ -11,14 +11,14 @@ module.exports = { const progress = this.progress; const week = 604800000; const cutoffTime = Date.now() - week; - await batch.processSortedSet('users:joindate', async function (uids) { + await batch.processSortedSet('users:joindate', async (uids) => { progress.incr(uids.length); await Promise.all([ db.sortedSetsRemoveRangeByScore(uids.map(uid => `uid:${uid}:notifications:unread`), '-inf', cutoffTime), db.sortedSetsRemoveRangeByScore(uids.map(uid => `uid:${uid}:notifications:read`), '-inf', cutoffTime), ]); const userData = await user.getUsersData(uids); - await Promise.all(userData.map(async function (user) { + await Promise.all(userData.map(async (user) => { if (!user) { return; } diff --git a/src/upgrades/1.13.3/fix_users_sorted_sets.js b/src/upgrades/1.13.3/fix_users_sorted_sets.js index 0e5a0da746..f977c09847 100644 --- a/src/upgrades/1.13.3/fix_users_sorted_sets.js +++ b/src/upgrades/1.13.3/fix_users_sorted_sets.js @@ -25,11 +25,11 @@ module.exports = { 'users:flags', ], 'null'); - await batch.processArray(allUids, async function (uids) { + await batch.processArray(allUids, async (uids) => { progress.incr(uids.length); const userData = await db.getObjects(uids.map(id => `user:${id}`)); - await Promise.all(userData.map(async function (userData, index) { + await Promise.all(userData.map(async (userData, index) => { if (!userData || !userData.uid) { await db.sortedSetsRemove([ 'users:joindate', diff --git a/src/upgrades/1.14.0/fix_category_image_field.js b/src/upgrades/1.14.0/fix_category_image_field.js index d27ad11064..036f4063e8 100644 --- a/src/upgrades/1.14.0/fix_category_image_field.js +++ b/src/upgrades/1.14.0/fix_category_image_field.js @@ -7,7 +7,7 @@ module.exports = { timestamp: Date.UTC(2020, 5, 9), method: async () => { const batch = require('../../batch'); - await batch.processSortedSet('categories:cid', async function (cids) { + await batch.processSortedSet('categories:cid', async (cids) => { let categoryData = await db.getObjects(cids.map(c => `category:${c}`)); categoryData = categoryData.filter(c => c && (c.image || c.backgroundImage)); if (categoryData.length) { diff --git a/src/upgrades/1.14.0/unescape_navigation_titles.js b/src/upgrades/1.14.0/unescape_navigation_titles.js index b77dad4225..4db6c00c6f 100644 --- a/src/upgrades/1.14.0/unescape_navigation_titles.js +++ b/src/upgrades/1.14.0/unescape_navigation_titles.js @@ -10,7 +10,7 @@ module.exports = { const translator = require('../../translator'); const order = []; const items = []; - data.forEach(function (item) { + data.forEach((item) => { const navItem = JSON.parse(item.value); if (navItem.hasOwnProperty('title')) { navItem.title = translator.unescape(navItem.title); diff --git a/src/upgrades/1.14.1/readd_deleted_recent_topics.js b/src/upgrades/1.14.1/readd_deleted_recent_topics.js index 9015dce26e..6dc0cc42c5 100644 --- a/src/upgrades/1.14.1/readd_deleted_recent_topics.js +++ b/src/upgrades/1.14.1/readd_deleted_recent_topics.js @@ -10,7 +10,7 @@ module.exports = { method: async function () { const progress = this.progress; - await batch.processSortedSet('topics:tid', async function (tids) { + await batch.processSortedSet('topics:tid', async (tids) => { progress.incr(tids.length); const topicData = await db.getObjectsFields( tids.map(tid => `topic:${tid}`), diff --git a/src/upgrades/1.15.0/add_target_uid_to_flags.js b/src/upgrades/1.15.0/add_target_uid_to_flags.js index d70c8d4187..f76cdc4b09 100644 --- a/src/upgrades/1.15.0/add_target_uid_to_flags.js +++ b/src/upgrades/1.15.0/add_target_uid_to_flags.js @@ -10,7 +10,7 @@ module.exports = { method: async function () { const progress = this.progress; - await batch.processSortedSet('flags:datetime', async function (flagIds) { + await batch.processSortedSet('flags:datetime', async (flagIds) => { progress.incr(flagIds.length); const flagData = await db.getObjects(flagIds.map(id => `flag:${id}`)); for (const flagObj of flagData) { diff --git a/src/upgrades/1.15.0/consolidate_flags.js b/src/upgrades/1.15.0/consolidate_flags.js index 481895e9d3..01aa94e7ae 100644 --- a/src/upgrades/1.15.0/consolidate_flags.js +++ b/src/upgrades/1.15.0/consolidate_flags.js @@ -16,7 +16,7 @@ module.exports = { flags = await db.getObjectsFields(flags, ['flagId', 'type', 'targetId', 'uid', 'description', 'datetime']); progress.total = flags.length; - await batch.processArray(flags, async function (subset) { + await batch.processArray(flags, async (subset) => { progress.incr(subset.length); await Promise.all(subset.map(async (flagObj) => { diff --git a/src/upgrades/1.15.0/fix_category_colors.js b/src/upgrades/1.15.0/fix_category_colors.js index 16e6253fe1..4e5288c87a 100644 --- a/src/upgrades/1.15.0/fix_category_colors.js +++ b/src/upgrades/1.15.0/fix_category_colors.js @@ -7,7 +7,7 @@ module.exports = { timestamp: Date.UTC(2020, 9, 11), method: async () => { const batch = require('../../batch'); - await batch.processSortedSet('categories:cid', async function (cids) { + await batch.processSortedSet('categories:cid', async (cids) => { let categoryData = await db.getObjects(cids.map(c => `category:${c}`)); categoryData = categoryData.filter(c => c && (c.color === '#fff' || c.color === '#333' || String(c.color).length !== 7)); if (categoryData.length) { diff --git a/src/upgrades/1.15.0/fullname_search_set.js b/src/upgrades/1.15.0/fullname_search_set.js index b761e846cc..42e8476dff 100644 --- a/src/upgrades/1.15.0/fullname_search_set.js +++ b/src/upgrades/1.15.0/fullname_search_set.js @@ -11,7 +11,7 @@ module.exports = { method: async function () { const progress = this.progress; - await batch.processSortedSet('users:joindate', async function (uids) { + await batch.processSortedSet('users:joindate', async (uids) => { progress.incr(uids.length); const userData = await user.getUsersFields(uids, ['uid', 'fullname']); const bulkAdd = userData diff --git a/src/upgrades/1.15.0/topic_poster_count.js b/src/upgrades/1.15.0/topic_poster_count.js index b25473ab19..3ac1bf44e0 100644 --- a/src/upgrades/1.15.0/topic_poster_count.js +++ b/src/upgrades/1.15.0/topic_poster_count.js @@ -10,7 +10,7 @@ module.exports = { method: async function () { const progress = this.progress; - await batch.processSortedSet('topics:tid', async function (tids) { + await batch.processSortedSet('topics:tid', async (tids) => { progress.incr(tids.length); const keys = tids.map(tid => `tid:${tid}:posters`); await db.sortedSetsRemoveRangeByScore(keys, '-inf', 0); diff --git a/src/upgrades/1.15.0/verified_users_group.js b/src/upgrades/1.15.0/verified_users_group.js index 37032b2f0a..66c4ccd92f 100644 --- a/src/upgrades/1.15.0/verified_users_group.js +++ b/src/upgrades/1.15.0/verified_users_group.js @@ -44,7 +44,7 @@ module.exports = { } // restore setting meta.config.maximumGroupNameLength = maxGroupLength; - await batch.processSortedSet('users:joindate', async function (uids) { + await batch.processSortedSet('users:joindate', async (uids) => { progress.incr(uids.length); const userData = await user.getUsersFields(uids, ['uid', 'email:confirmed']); diff --git a/src/upgrades/1.15.4/clear_purged_replies.js b/src/upgrades/1.15.4/clear_purged_replies.js index 7401e9defb..2077965e45 100644 --- a/src/upgrades/1.15.4/clear_purged_replies.js +++ b/src/upgrades/1.15.4/clear_purged_replies.js @@ -11,7 +11,7 @@ module.exports = { method: async function () { const progress = this.progress; - await batch.processSortedSet('posts:pid', async function (pids) { + await batch.processSortedSet('posts:pid', async (pids) => { progress.incr(pids.length); let postData = await db.getObjects(pids.map(pid => `post:${pid}`)); postData = postData.filter(p => p && parseInt(p.toPid, 10)); diff --git a/src/upgrades/1.16.0/category_tags.js b/src/upgrades/1.16.0/category_tags.js index 3dfd380d19..8cd1c2c1e1 100644 --- a/src/upgrades/1.16.0/category_tags.js +++ b/src/upgrades/1.16.0/category_tags.js @@ -11,8 +11,8 @@ module.exports = { method: async function () { const progress = this.progress; - await batch.processSortedSet('topics:tid', async function (tids) { - await async.eachSeries(tids, async function (tid) { + await batch.processSortedSet('topics:tid', async (tids) => { + await async.eachSeries(tids, async (tid) => { const [topicData, tags] = await Promise.all([ topics.getTopicFields(tid, ['cid', 'timestamp']), topics.getTopicTags(tid), @@ -20,7 +20,7 @@ module.exports = { if (tags.length) { const cid = topicData.cid; - await async.eachSeries(tags, async function (tag) { + await async.eachSeries(tags, async (tag) => { await db.sortedSetAdd(`cid:${cid}:tag:${tag}:topics`, topicData.timestamp, tid); const count = await db.sortedSetCard(`cid:${cid}:tag:${tag}:topics`); await db.sortedSetAdd(`cid:${cid}:tags`, count, tag); diff --git a/src/upgrades/1.16.0/migrate_thumbs.js b/src/upgrades/1.16.0/migrate_thumbs.js index 34851568e7..c791ed9ae6 100644 --- a/src/upgrades/1.16.0/migrate_thumbs.js +++ b/src/upgrades/1.16.0/migrate_thumbs.js @@ -18,7 +18,7 @@ module.exports = { await meta.configs.set('topicThumbSize', 512); } - await batch.processSortedSet('topics:tid', async function (tids) { + await batch.processSortedSet('topics:tid', async (tids) => { const keys = tids.map(tid => `topic:${tid}`); const topicThumbs = (await db.getObjectsFields(keys, ['thumb'])) .map(obj => (obj.thumb ? obj.thumb.replace(nconf.get('upload_url'), '') : null)); diff --git a/src/upgrades/1.17.0/banned_users_group.js b/src/upgrades/1.17.0/banned_users_group.js index 15457d1510..27ebc3b340 100644 --- a/src/upgrades/1.17.0/banned_users_group.js +++ b/src/upgrades/1.17.0/banned_users_group.js @@ -25,7 +25,7 @@ module.exports = { }); } - await batch.processSortedSet('users:banned', async function (uids) { + await batch.processSortedSet('users:banned', async (uids) => { progress.incr(uids.length); await db.sortedSetAdd( diff --git a/src/upgrades/1.17.0/category_name_zset.js b/src/upgrades/1.17.0/category_name_zset.js index 1c2017a6ab..1ace788d24 100644 --- a/src/upgrades/1.17.0/category_name_zset.js +++ b/src/upgrades/1.17.0/category_name_zset.js @@ -9,17 +9,15 @@ module.exports = { method: async function () { const progress = this.progress; - await batch.processSortedSet('categories:cid', async function (cids) { + await batch.processSortedSet('categories:cid', async (cids) => { const keys = cids.map(cid => `category:${cid}`); let categoryData = await db.getObjectsFields(keys, ['cid', 'name']); categoryData = categoryData.filter(c => c.cid && c.name); - const bulkAdd = categoryData.map(function (cat) { - return [ - 'categories:name', - 0, - `${String(cat.name).substr(0, 200).toLowerCase()}:${cat.cid}`, - ]; - }); + const bulkAdd = categoryData.map(cat => [ + 'categories:name', + 0, + `${String(cat.name).substr(0, 200).toLowerCase()}:${cat.cid}`, + ]); await db.sortedSetAddBulk(bulkAdd); progress.incr(cids.length); }, { diff --git a/src/upgrades/1.17.0/subcategories_per_page.js b/src/upgrades/1.17.0/subcategories_per_page.js index 194105ce09..c6b667d5c5 100644 --- a/src/upgrades/1.17.0/subcategories_per_page.js +++ b/src/upgrades/1.17.0/subcategories_per_page.js @@ -9,7 +9,7 @@ module.exports = { method: async function () { const progress = this.progress; - await batch.processSortedSet('categories:cid', async function (cids) { + await batch.processSortedSet('categories:cid', async (cids) => { const keys = cids.map(cid => `category:${cid}`); await db.setObject(keys, { subCategoriesPerPage: 10, diff --git a/src/upgrades/1.17.0/topic_thumb_count.js b/src/upgrades/1.17.0/topic_thumb_count.js index f565c076c4..f5ccd134b2 100644 --- a/src/upgrades/1.17.0/topic_thumb_count.js +++ b/src/upgrades/1.17.0/topic_thumb_count.js @@ -10,7 +10,7 @@ module.exports = { method: async function () { const progress = this.progress; - await batch.processSortedSet('topics:tid', async function (tids) { + await batch.processSortedSet('topics:tid', async (tids) => { const keys = tids.map(tid => `topic:${tid}:thumbs`); const counts = await db.sortedSetsCard(keys); const tidToCount = _.zip(tids, counts); diff --git a/src/upgrades/1.2.0/category_recent_tids.js b/src/upgrades/1.2.0/category_recent_tids.js index d95850db73..31a1da5ed8 100644 --- a/src/upgrades/1.2.0/category_recent_tids.js +++ b/src/upgrades/1.2.0/category_recent_tids.js @@ -8,17 +8,17 @@ module.exports = { name: 'Category recent tids', timestamp: Date.UTC(2016, 8, 22), method: function (callback) { - db.getSortedSetRange('categories:cid', 0, -1, function (err, cids) { + db.getSortedSetRange('categories:cid', 0, -1, (err, cids) => { if (err) { return callback(err); } - async.eachSeries(cids, function (cid, next) { - db.getSortedSetRevRange(`cid:${cid}:pids`, 0, 0, function (err, pid) { + async.eachSeries(cids, (cid, next) => { + db.getSortedSetRevRange(`cid:${cid}:pids`, 0, 0, (err, pid) => { if (err || !pid) { return next(err); } - db.getObjectFields(`post:${pid}`, ['tid', 'timestamp'], function (err, postData) { + db.getObjectFields(`post:${pid}`, ['tid', 'timestamp'], (err, postData) => { if (err || !postData || !postData.tid) { return next(err); } diff --git a/src/upgrades/1.2.0/edit_delete_deletetopic_privileges.js b/src/upgrades/1.2.0/edit_delete_deletetopic_privileges.js index a65d340138..9627f64271 100644 --- a/src/upgrades/1.2.0/edit_delete_deletetopic_privileges.js +++ b/src/upgrades/1.2.0/edit_delete_deletetopic_privileges.js @@ -12,13 +12,13 @@ module.exports = { var groupsAPI = require('../../groups'); var privilegesAPI = require('../../privileges'); - db.getSortedSetRange('categories:cid', 0, -1, function (err, cids) { + db.getSortedSetRange('categories:cid', 0, -1, (err, cids) => { if (err) { return callback(err); } - async.eachSeries(cids, function (cid, next) { - privilegesAPI.categories.list(cid, function (err, data) { + async.eachSeries(cids, (cid, next) => { + privilegesAPI.categories.list(cid, (err, data) => { if (err) { return next(err); } @@ -28,12 +28,12 @@ module.exports = { async.waterfall([ function (next) { - async.eachSeries(groups, function (group, next) { + async.eachSeries(groups, (group, next) => { if (group.privileges['groups:topics:reply']) { return async.parallel([ async.apply(groupsAPI.join, `cid:${cid}:privileges:groups:posts:edit`, group.name), async.apply(groupsAPI.join, `cid:${cid}:privileges:groups:posts:delete`, group.name), - ], function (err) { + ], (err) => { if (!err) { winston.verbose(`cid:${cid}:privileges:groups:posts:edit, cid:${cid}:privileges:groups:posts:delete granted to gid: ${group.name}`); } @@ -46,9 +46,9 @@ module.exports = { }, next); }, function (next) { - async.eachSeries(groups, function (group, next) { + async.eachSeries(groups, (group, next) => { if (group.privileges['groups:topics:create']) { - return groupsAPI.join(`cid:${cid}:privileges:groups:topics:delete`, group.name, function (err) { + return groupsAPI.join(`cid:${cid}:privileges:groups:topics:delete`, group.name, (err) => { if (!err) { winston.verbose(`cid:${cid}:privileges:groups:topics:delete granted to gid: ${group.name}`); } @@ -61,12 +61,12 @@ module.exports = { }, next); }, function (next) { - async.eachSeries(users, function (user, next) { + async.eachSeries(users, (user, next) => { if (user.privileges['topics:reply']) { return async.parallel([ async.apply(groupsAPI.join, `cid:${cid}:privileges:posts:edit`, user.uid), async.apply(groupsAPI.join, `cid:${cid}:privileges:posts:delete`, user.uid), - ], function (err) { + ], (err) => { if (!err) { winston.verbose(`cid:${cid}:privileges:posts:edit, cid:${cid}:privileges:posts:delete granted to uid: ${user.uid}`); } @@ -79,9 +79,9 @@ module.exports = { }, next); }, function (next) { - async.eachSeries(users, function (user, next) { + async.eachSeries(users, (user, next) => { if (user.privileges['topics:create']) { - return groupsAPI.join(`cid:${cid}:privileges:topics:delete`, user.uid, function (err) { + return groupsAPI.join(`cid:${cid}:privileges:topics:delete`, user.uid, (err) => { if (!err) { winston.verbose(`cid:${cid}:privileges:topics:delete granted to uid: ${user.uid}`); } @@ -93,7 +93,7 @@ module.exports = { next(null); }, next); }, - ], function (err) { + ], (err) => { if (!err) { winston.verbose(`-- cid ${cid} upgraded`); } diff --git a/src/upgrades/1.3.0/favourites_to_bookmarks.js b/src/upgrades/1.3.0/favourites_to_bookmarks.js index 86c31aa2a0..07071fee84 100644 --- a/src/upgrades/1.3.0/favourites_to_bookmarks.js +++ b/src/upgrades/1.3.0/favourites_to_bookmarks.js @@ -13,8 +13,8 @@ module.exports = { function upgradePosts(next) { var batch = require('../../batch'); - batch.processSortedSet('posts:pid', function (ids, next) { - async.each(ids, function (id, next) { + batch.processSortedSet('posts:pid', (ids, next) => { + async.each(ids, (id, next) => { progress.incr(); async.waterfall([ @@ -44,8 +44,8 @@ module.exports = { function upgradeUsers(next) { var batch = require('../../batch'); - batch.processSortedSet('users:joindate', function (ids, next) { - async.each(ids, function (id, next) { + batch.processSortedSet('users:joindate', (ids, next) => { + async.each(ids, (id, next) => { db.rename(`uid:${id}:favourites`, `uid:${id}:bookmarks`, next); }, next); }, {}, next); diff --git a/src/upgrades/1.3.0/sorted_sets_for_post_replies.js b/src/upgrades/1.3.0/sorted_sets_for_post_replies.js index d3503414eb..24cbf3b9e2 100644 --- a/src/upgrades/1.3.0/sorted_sets_for_post_replies.js +++ b/src/upgrades/1.3.0/sorted_sets_for_post_replies.js @@ -13,15 +13,15 @@ module.exports = { var batch = require('../../batch'); var progress = this.progress; - batch.processSortedSet('posts:pid', function (ids, next) { - posts.getPostsFields(ids, ['pid', 'toPid', 'timestamp'], function (err, data) { + batch.processSortedSet('posts:pid', (ids, next) => { + posts.getPostsFields(ids, ['pid', 'toPid', 'timestamp'], (err, data) => { if (err) { return next(err); } progress.incr(); - async.eachSeries(data, function (postData, next) { + async.eachSeries(data, (postData, next) => { if (!parseInt(postData.toPid, 10)) { return next(null); } diff --git a/src/upgrades/1.4.0/global_and_user_language_keys.js b/src/upgrades/1.4.0/global_and_user_language_keys.js index cfa01d9bd1..862a86cbbf 100644 --- a/src/upgrades/1.4.0/global_and_user_language_keys.js +++ b/src/upgrades/1.4.0/global_and_user_language_keys.js @@ -14,7 +14,7 @@ module.exports = { var newLanguage; async.parallel([ function (next) { - meta.configs.get('defaultLang', function (err, defaultLang) { + meta.configs.get('defaultLang', (err, defaultLang) => { if (err) { return next(err); } @@ -32,8 +32,8 @@ module.exports = { }); }, function (next) { - batch.processSortedSet('users:joindate', function (ids, next) { - async.each(ids, function (uid, next) { + batch.processSortedSet('users:joindate', (ids, next) => { + async.each(ids, (uid, next) => { async.waterfall([ async.apply(db.getObjectField, `user:${uid}:settings`, 'userLang'), function (language, next) { diff --git a/src/upgrades/1.4.0/sorted_set_for_pinned_topics.js b/src/upgrades/1.4.0/sorted_set_for_pinned_topics.js index 1320bd041a..b699a0ef8f 100644 --- a/src/upgrades/1.4.0/sorted_set_for_pinned_topics.js +++ b/src/upgrades/1.4.0/sorted_set_for_pinned_topics.js @@ -11,17 +11,15 @@ module.exports = { method: function (callback) { var topics = require('../../topics'); var batch = require('../../batch'); - batch.processSortedSet('topics:tid', function (ids, next) { - topics.getTopicsFields(ids, ['tid', 'cid', 'pinned', 'lastposttime'], function (err, data) { + batch.processSortedSet('topics:tid', (ids, next) => { + topics.getTopicsFields(ids, ['tid', 'cid', 'pinned', 'lastposttime'], (err, data) => { if (err) { return next(err); } - data = data.filter(function (topicData) { - return parseInt(topicData.pinned, 10) === 1; - }); + data = data.filter(topicData => parseInt(topicData.pinned, 10) === 1); - async.eachSeries(data, function (topicData, next) { + async.eachSeries(data, (topicData, next) => { winston.verbose(`processing tid: ${topicData.tid}`); async.parallel([ diff --git a/src/upgrades/1.4.4/config_urls_update.js b/src/upgrades/1.4.4/config_urls_update.js index 95b0cc61c5..64f24ed525 100644 --- a/src/upgrades/1.4.4/config_urls_update.js +++ b/src/upgrades/1.4.4/config_urls_update.js @@ -19,7 +19,7 @@ module.exports = { var keys = ['brand:favicon', 'brand:touchicon', 'og:image', 'brand:logo:url', 'defaultAvatar', 'profile:defaultCovers']; - keys.forEach(function (key) { + keys.forEach((key) => { var oldValue = config[key]; if (!oldValue || typeof oldValue !== 'string') { diff --git a/src/upgrades/1.4.4/sound_settings.js b/src/upgrades/1.4.4/sound_settings.js index 7d1225eccb..25efa2f0ad 100644 --- a/src/upgrades/1.4.4/sound_settings.js +++ b/src/upgrades/1.4.4/sound_settings.js @@ -21,12 +21,12 @@ module.exports = { function (cb) { var keys = ['chat-incoming', 'chat-outgoing', 'notification']; - db.getObject('settings:sounds', function (err, settings) { + db.getObject('settings:sounds', (err, settings) => { if (err || !settings) { return cb(err); } - keys.forEach(function (key) { + keys.forEach((key) => { if (settings[key] && !settings[key].includes(' | ')) { settings[key] = map[settings[key]] || ''; } @@ -38,14 +38,14 @@ module.exports = { function (cb) { var keys = ['notificationSound', 'incomingChatSound', 'outgoingChatSound']; - batch.processSortedSet('users:joindate', function (ids, next) { - async.each(ids, function (uid, next) { - db.getObject(`user:${uid}:settings`, function (err, settings) { + batch.processSortedSet('users:joindate', (ids, next) => { + async.each(ids, (uid, next) => { + db.getObject(`user:${uid}:settings`, (err, settings) => { if (err || !settings) { return next(err); } var newSettings = {}; - keys.forEach(function (key) { + keys.forEach((key) => { if (settings[key] && !settings[key].includes(' | ')) { newSettings[key] = map[settings[key]] || ''; } diff --git a/src/upgrades/1.4.6/delete_sessions.js b/src/upgrades/1.4.6/delete_sessions.js index 4b19a77def..1fe6d0b6bc 100644 --- a/src/upgrades/1.4.6/delete_sessions.js +++ b/src/upgrades/1.4.6/delete_sessions.js @@ -36,9 +36,9 @@ module.exports = { function (sessionKeys, next) { progress.total = sessionKeys.length; - batch.processArray(sessionKeys, function (keys, next) { + batch.processArray(sessionKeys, (keys, next) => { var multi = client.multi(); - keys.forEach(function (key) { + keys.forEach((key) => { progress.incr(); multi.del(key); }); @@ -47,11 +47,11 @@ module.exports = { batch: 1000, }, next); }, - ], function (err) { + ], (err) => { next(err); }); } else if (db.client && db.client.collection) { - db.client.collection('sessions').deleteMany({}, {}, function (err) { + db.client.collection('sessions').deleteMany({}, {}, (err) => { next(err); }); } else { diff --git a/src/upgrades/1.5.0/allowed_file_extensions.js b/src/upgrades/1.5.0/allowed_file_extensions.js index 29e348f16f..7f1af2a5c3 100644 --- a/src/upgrades/1.5.0/allowed_file_extensions.js +++ b/src/upgrades/1.5.0/allowed_file_extensions.js @@ -6,7 +6,7 @@ module.exports = { name: 'Set default allowed file extensions', timestamp: Date.UTC(2017, 3, 14), method: function (callback) { - db.getObjectField('config', 'allowedFileExtensions', function (err, value) { + db.getObjectField('config', 'allowedFileExtensions', (err, value) => { if (err || value) { return callback(err); } diff --git a/src/upgrades/1.5.0/flags_refactor.js b/src/upgrades/1.5.0/flags_refactor.js index 5608ab3ec1..b19fdfa30d 100644 --- a/src/upgrades/1.5.0/flags_refactor.js +++ b/src/upgrades/1.5.0/flags_refactor.js @@ -13,23 +13,21 @@ module.exports = { var flags = require('../../flags'); var progress = this.progress; - batch.processSortedSet('posts:pid', function (ids, next) { - posts.getPostsByPids(ids, 1, function (err, posts) { + batch.processSortedSet('posts:pid', (ids, next) => { + posts.getPostsByPids(ids, 1, (err, posts) => { if (err) { return next(err); } - posts = posts.filter(function (post) { - return post.hasOwnProperty('flags'); - }); + posts = posts.filter(post => post.hasOwnProperty('flags')); - async.each(posts, function (post, next) { + async.each(posts, (post, next) => { progress.incr(); async.parallel({ uids: async.apply(db.getSortedSetRangeWithScores, `pid:${post.pid}:flag:uids`, 0, -1), reasons: async.apply(db.getSortedSetRange, `pid:${post.pid}:flag:uid:reason`, 0, -1), - }, function (err, data) { + }, (err, data) => { if (err) { return next(err); } @@ -62,9 +60,7 @@ module.exports = { if (post.hasOwnProperty('flag:notes') && post['flag:notes'].length) { try { var history = JSON.parse(post['flag:history']); - history = history.filter(function (event) { - return event.type === 'notes'; - })[0]; + history = history.filter(event => event.type === 'notes')[0]; flags.appendNote(flagObj.flagId, history.uid, post['flag:notes'], history.timestamp, next); } catch (e) { @@ -74,7 +70,7 @@ module.exports = { setImmediate(next); } }, - ], function (err) { + ], (err) => { if (err && err.message === '[[error:post-already-flagged]]') { // Already flagged, no need to parse, but not an error next(); diff --git a/src/upgrades/1.5.0/moderation_history_refactor.js b/src/upgrades/1.5.0/moderation_history_refactor.js index 50f528b1dd..eb112bf5e7 100644 --- a/src/upgrades/1.5.0/moderation_history_refactor.js +++ b/src/upgrades/1.5.0/moderation_history_refactor.js @@ -11,9 +11,9 @@ module.exports = { method: function (callback) { var progress = this.progress; - batch.processSortedSet('users:joindate', function (ids, next) { - async.each(ids, function (uid, next) { - db.getObjectField(`user:${uid}`, 'moderationNote', function (err, moderationNote) { + batch.processSortedSet('users:joindate', (ids, next) => { + async.each(ids, (uid, next) => { + db.getObjectField(`user:${uid}`, 'moderationNote', (err, moderationNote) => { if (err || !moderationNote) { progress.incr(); return next(err); diff --git a/src/upgrades/1.5.0/post_votes_zset.js b/src/upgrades/1.5.0/post_votes_zset.js index c25d9e58ee..dd81bf2663 100644 --- a/src/upgrades/1.5.0/post_votes_zset.js +++ b/src/upgrades/1.5.0/post_votes_zset.js @@ -10,9 +10,9 @@ module.exports = { method: function (callback) { var progress = this.progress; - require('../../batch').processSortedSet('posts:pid', function (pids, next) { - async.each(pids, function (pid, next) { - db.getObjectFields(`post:${pid}`, ['upvotes', 'downvotes'], function (err, postData) { + require('../../batch').processSortedSet('posts:pid', (pids, next) => { + async.each(pids, (pid, next) => { + db.getObjectFields(`post:${pid}`, ['upvotes', 'downvotes'], (err, postData) => { if (err || !postData) { return next(err); } diff --git a/src/upgrades/1.5.0/remove_relative_uploaded_profile_cover.js b/src/upgrades/1.5.0/remove_relative_uploaded_profile_cover.js index e85d79c8d3..93a891b501 100644 --- a/src/upgrades/1.5.0/remove_relative_uploaded_profile_cover.js +++ b/src/upgrades/1.5.0/remove_relative_uploaded_profile_cover.js @@ -11,8 +11,8 @@ module.exports = { method: function (callback) { var progress = this.progress; - batch.processSortedSet('users:joindate', function (ids, done) { - async.each(ids, function (uid, cb) { + batch.processSortedSet('users:joindate', (ids, done) => { + async.each(ids, (uid, cb) => { async.waterfall([ function (next) { db.getObjectField(`user:${uid}`, 'cover:url', next); diff --git a/src/upgrades/1.5.1/rename_mods_group.js b/src/upgrades/1.5.1/rename_mods_group.js index a15e293d74..cd43a7925c 100644 --- a/src/upgrades/1.5.1/rename_mods_group.js +++ b/src/upgrades/1.5.1/rename_mods_group.js @@ -12,11 +12,11 @@ module.exports = { timestamp: Date.UTC(2017, 4, 26), method: function (callback) { var progress = this.progress; - batch.processSortedSet('categories:cid', function (cids, next) { - async.eachSeries(cids, function (cid, next) { + batch.processSortedSet('categories:cid', (cids, next) => { + async.eachSeries(cids, (cid, next) => { var groupName = `cid:${cid}:privileges:mods`; var newName = `cid:${cid}:privileges:moderate`; - groups.exists(groupName, function (err, exists) { + groups.exists(groupName, (err, exists) => { if (err || !exists) { progress.incr(); return next(err); diff --git a/src/upgrades/1.5.2/rss_token_wipe.js b/src/upgrades/1.5.2/rss_token_wipe.js index 2ef8a67f14..76a0915c4f 100644 --- a/src/upgrades/1.5.2/rss_token_wipe.js +++ b/src/upgrades/1.5.2/rss_token_wipe.js @@ -10,8 +10,8 @@ module.exports = { method: function (callback) { var progress = this.progress; - batch.processSortedSet('users:joindate', function (uids, next) { - async.eachLimit(uids, 500, function (uid, next) { + batch.processSortedSet('users:joindate', (uids, next) => { + async.eachLimit(uids, 500, (uid, next) => { progress.incr(); db.deleteObjectField(`user:${uid}`, 'rss_token', next); }, next); diff --git a/src/upgrades/1.5.2/tags_privilege.js b/src/upgrades/1.5.2/tags_privilege.js index 12efefd6de..80733d1d9f 100644 --- a/src/upgrades/1.5.2/tags_privilege.js +++ b/src/upgrades/1.5.2/tags_privilege.js @@ -10,8 +10,8 @@ module.exports = { method: function (callback) { var progress = this.progress; var privileges = require('../../privileges'); - batch.processSortedSet('categories:cid', function (cids, next) { - async.eachSeries(cids, function (cid, next) { + batch.processSortedSet('categories:cid', (cids, next) => { + async.eachSeries(cids, (cid, next) => { progress.incr(); privileges.categories.give(['groups:topics:tag'], cid, 'registered-users', next); }, next); diff --git a/src/upgrades/1.6.0/generate-email-logo.js b/src/upgrades/1.6.0/generate-email-logo.js index 7b94ecb717..6e307f2a61 100644 --- a/src/upgrades/1.6.0/generate-email-logo.js +++ b/src/upgrades/1.6.0/generate-email-logo.js @@ -25,7 +25,7 @@ module.exports = { return setImmediate(next); } - fs.access(sourcePath, function (err) { + fs.access(sourcePath, (err) => { if (err || path.extname(sourcePath) === '.svg') { skip = true; return setImmediate(next); diff --git a/src/upgrades/1.6.2/topics_lastposttime_zset.js b/src/upgrades/1.6.2/topics_lastposttime_zset.js index c100df32ee..b7b614b8c9 100644 --- a/src/upgrades/1.6.2/topics_lastposttime_zset.js +++ b/src/upgrades/1.6.2/topics_lastposttime_zset.js @@ -10,9 +10,9 @@ module.exports = { method: function (callback) { var progress = this.progress; - require('../../batch').processSortedSet('topics:tid', function (tids, next) { - async.eachSeries(tids, function (tid, next) { - db.getObjectFields(`topic:${tid}`, ['cid', 'timestamp', 'lastposttime'], function (err, topicData) { + require('../../batch').processSortedSet('topics:tid', (tids, next) => { + async.eachSeries(tids, (tid, next) => { + db.getObjectFields(`topic:${tid}`, ['cid', 'timestamp', 'lastposttime'], (err, topicData) => { if (err || !topicData) { return next(err); } diff --git a/src/upgrades/1.7.0/generate-custom-html.js b/src/upgrades/1.7.0/generate-custom-html.js index 58ac2adf61..795327af20 100644 --- a/src/upgrades/1.7.0/generate-custom-html.js +++ b/src/upgrades/1.7.0/generate-custom-html.js @@ -7,7 +7,7 @@ module.exports = { name: 'Generate customHTML block from old customJS setting', timestamp: Date.UTC(2017, 9, 12), method: function (callback) { - db.getObjectField('config', 'customJS', function (err, newHTML) { + db.getObjectField('config', 'customJS', (err, newHTML) => { if (err) { return callback(err); } diff --git a/src/upgrades/1.7.1/notification-settings.js b/src/upgrades/1.7.1/notification-settings.js index d215e0b7aa..5076bbd92b 100644 --- a/src/upgrades/1.7.1/notification-settings.js +++ b/src/upgrades/1.7.1/notification-settings.js @@ -10,8 +10,8 @@ module.exports = { method: function (callback) { var progress = this.progress; - batch.processSortedSet('users:joindate', function (uids, next) { - async.eachLimit(uids, 500, function (uid, next) { + batch.processSortedSet('users:joindate', (uids, next) => { + async.eachLimit(uids, 500, (uid, next) => { progress.incr(); async.waterfall([ function (next) { @@ -32,7 +32,7 @@ module.exports = { return next(); } - async.series(tasks, function (err) { + async.series(tasks, (err) => { _next(err); }); }, diff --git a/src/upgrades/1.7.3/key_value_schema_change.js b/src/upgrades/1.7.3/key_value_schema_change.js index cee08a8a9f..ccbb24874e 100644 --- a/src/upgrades/1.7.3/key_value_schema_change.js +++ b/src/upgrades/1.7.3/key_value_schema_change.js @@ -39,10 +39,10 @@ module.exports = { var done = false; async.whilst( - function (next) { + (next) => { next(null, !done); }, - function (next) { + (next) => { async.waterfall([ function (next) { cursor.next(next); @@ -60,7 +60,7 @@ module.exports = { next(); } }, - ], function (err) { + ], (err) => { next(err); }); }, diff --git a/src/upgrades/1.7.3/topic_votes.js b/src/upgrades/1.7.3/topic_votes.js index 3c608606b8..cfd8132a0d 100644 --- a/src/upgrades/1.7.3/topic_votes.js +++ b/src/upgrades/1.7.3/topic_votes.js @@ -10,8 +10,8 @@ module.exports = { method: function (callback) { var progress = this.progress; - batch.processSortedSet('topics:tid', function (tids, next) { - async.eachLimit(tids, 500, function (tid, _next) { + batch.processSortedSet('topics:tid', (tids, next) => { + async.eachLimit(tids, 500, (tid, _next) => { progress.incr(); var topicData; async.waterfall([ @@ -50,7 +50,7 @@ module.exports = { next(); } }, - ], function (err) { + ], (err) => { next(err); }); }, diff --git a/src/upgrades/1.7.4/fix_moved_topics_byvotes.js b/src/upgrades/1.7.4/fix_moved_topics_byvotes.js index 9a11ebc5f2..9a6b1c8697 100644 --- a/src/upgrades/1.7.4/fix_moved_topics_byvotes.js +++ b/src/upgrades/1.7.4/fix_moved_topics_byvotes.js @@ -10,8 +10,8 @@ module.exports = { method: function (callback) { var progress = this.progress; - batch.processSortedSet('topics:tid', function (tids, next) { - async.eachLimit(tids, 500, function (tid, _next) { + batch.processSortedSet('topics:tid', (tids, next) => { + async.eachLimit(tids, 500, (tid, _next) => { progress.incr(); var topicData; async.waterfall([ @@ -39,7 +39,7 @@ module.exports = { next(); } }, - ], function (err) { + ], (err) => { next(err); }); }, diff --git a/src/upgrades/1.7.4/fix_user_topics_per_category.js b/src/upgrades/1.7.4/fix_user_topics_per_category.js index 6347e9fd4b..df5534554f 100644 --- a/src/upgrades/1.7.4/fix_user_topics_per_category.js +++ b/src/upgrades/1.7.4/fix_user_topics_per_category.js @@ -10,8 +10,8 @@ module.exports = { method: function (callback) { var progress = this.progress; - batch.processSortedSet('topics:tid', function (tids, next) { - async.eachLimit(tids, 500, function (tid, _next) { + batch.processSortedSet('topics:tid', (tids, next) => { + async.eachLimit(tids, 500, (tid, _next) => { progress.incr(); var topicData; async.waterfall([ @@ -35,7 +35,7 @@ module.exports = { function (next) { db.sortedSetAdd(`cid:${topicData.cid}:uid:${topicData.uid}:tids`, topicData.timestamp, tid, next); }, - ], function (err) { + ], (err) => { next(err); }); } else { diff --git a/src/upgrades/1.7.4/global_upload_privilege.js b/src/upgrades/1.7.4/global_upload_privilege.js index 49be4a24bf..e25392f599 100644 --- a/src/upgrades/1.7.4/global_upload_privilege.js +++ b/src/upgrades/1.7.4/global_upload_privilege.js @@ -10,12 +10,12 @@ module.exports = { name: 'Give upload privilege to registered-users globally if it is given on a category', timestamp: Date.UTC(2018, 0, 3), method: function (callback) { - db.getSortedSetRange('categories:cid', 0, -1, function (err, cids) { + db.getSortedSetRange('categories:cid', 0, -1, (err, cids) => { if (err) { return callback(err); } - async.eachSeries(cids, function (cid, next) { - getGroupPrivileges(cid, function (err, groupPrivileges) { + async.eachSeries(cids, (cid, next) => { + getGroupPrivileges(cid, (err, groupPrivileges) => { if (err) { return next(err); } @@ -37,7 +37,7 @@ module.exports = { function getGroupPrivileges(cid, callback) { var tasks = {}; - ['groups:upload:post:image', 'groups:upload:post:file'].forEach(function (privilege) { + ['groups:upload:post:image', 'groups:upload:post:file'].forEach((privilege) => { tasks[privilege] = async.apply(groups.isMember, 'registered-users', `cid:${cid}:privileges:${privilege}`); }); diff --git a/src/upgrades/1.7.4/rename_min_reputation_settings.js b/src/upgrades/1.7.4/rename_min_reputation_settings.js index 1abbce1378..782f92c40e 100644 --- a/src/upgrades/1.7.4/rename_min_reputation_settings.js +++ b/src/upgrades/1.7.4/rename_min_reputation_settings.js @@ -6,7 +6,7 @@ module.exports = { name: 'Rename privileges:downvote and privileges:flag to min:rep:downvote, min:rep:flag respectively', timestamp: Date.UTC(2018, 0, 12), method: function (callback) { - db.getObjectFields('config', ['privileges:downvote', 'privileges:flag'], function (err, config) { + db.getObjectFields('config', ['privileges:downvote', 'privileges:flag'], (err, config) => { if (err) { return callback(err); } @@ -14,7 +14,7 @@ module.exports = { db.setObject('config', { 'min:rep:downvote': parseInt(config['privileges:downvote'], 10) || 0, 'min:rep:flag': parseInt(config['privileges:downvote'], 10) || 0, - }, function (err) { + }, (err) => { if (err) { return callback(err); } diff --git a/src/upgrades/1.7.4/vote_privilege.js b/src/upgrades/1.7.4/vote_privilege.js index 2083b9721c..be14cc7ef9 100644 --- a/src/upgrades/1.7.4/vote_privilege.js +++ b/src/upgrades/1.7.4/vote_privilege.js @@ -10,11 +10,11 @@ module.exports = { name: 'Give vote privilege to registered-users on all categories', timestamp: Date.UTC(2018, 0, 9), method: function (callback) { - db.getSortedSetRange('categories:cid', 0, -1, function (err, cids) { + db.getSortedSetRange('categories:cid', 0, -1, (err, cids) => { if (err) { return callback(err); } - async.eachSeries(cids, function (cid, next) { + async.eachSeries(cids, (cid, next) => { privileges.categories.give(['groups:posts:upvote', 'groups:posts:downvote'], cid, 'registered-users', next); }, callback); }); diff --git a/src/upgrades/1.7.6/flatten_navigation_data.js b/src/upgrades/1.7.6/flatten_navigation_data.js index 9fd0901274..52e5e38519 100644 --- a/src/upgrades/1.7.6/flatten_navigation_data.js +++ b/src/upgrades/1.7.6/flatten_navigation_data.js @@ -14,7 +14,7 @@ module.exports = { function (data, next) { var order = []; var items = []; - data.forEach(function (item) { + data.forEach((item) => { var navItem = JSON.parse(item.value); var keys = Object.keys(navItem); if (keys.length && parseInt(keys[0], 10) >= 0) { diff --git a/src/upgrades/1.8.0/give_spiders_privileges.js b/src/upgrades/1.8.0/give_spiders_privileges.js index 18dbb722c5..9e5d13573a 100644 --- a/src/upgrades/1.8.0/give_spiders_privileges.js +++ b/src/upgrades/1.8.0/give_spiders_privileges.js @@ -10,12 +10,12 @@ module.exports = { name: 'Give category access privileges to spiders system group', timestamp: Date.UTC(2018, 0, 31), method: function (callback) { - db.getSortedSetRange('categories:cid', 0, -1, function (err, cids) { + db.getSortedSetRange('categories:cid', 0, -1, (err, cids) => { if (err) { return callback(err); } - async.eachSeries(cids, function (cid, next) { - getGroupPrivileges(cid, function (err, groupPrivileges) { + async.eachSeries(cids, (cid, next) => { + getGroupPrivileges(cid, (err, groupPrivileges) => { if (err) { return next(err); } @@ -41,7 +41,7 @@ module.exports = { function getGroupPrivileges(cid, callback) { var tasks = {}; - ['groups:find', 'groups:read', 'groups:topics:read'].forEach(function (privilege) { + ['groups:find', 'groups:read', 'groups:topics:read'].forEach((privilege) => { tasks[privilege] = async.apply(groups.isMember, 'guests', `cid:${cid}:privileges:${privilege}`); }); diff --git a/src/upgrades/1.8.1/diffs_zset_to_listhash.js b/src/upgrades/1.8.1/diffs_zset_to_listhash.js index e105c8df44..ea2a4ddd55 100644 --- a/src/upgrades/1.8.1/diffs_zset_to_listhash.js +++ b/src/upgrades/1.8.1/diffs_zset_to_listhash.js @@ -11,9 +11,9 @@ module.exports = { method: function (callback) { var progress = this.progress; - batch.processSortedSet('posts:pid', function (pids, next) { - async.each(pids, function (pid, next) { - db.getSortedSetRangeWithScores(`post:${pid}:diffs`, 0, -1, function (err, diffs) { + batch.processSortedSet('posts:pid', (pids, next) => { + async.each(pids, (pid, next) => { + db.getSortedSetRangeWithScores(`post:${pid}:diffs`, 0, -1, (err, diffs) => { if (err) { return next(err); } @@ -24,7 +24,7 @@ module.exports = { } // For each diff, push to list - async.each(diffs, function (diff, next) { + async.each(diffs, (diff, next) => { async.series([ async.apply(db.delete.bind(db), `post:${pid}:diffs`), async.apply(db.listPrepend.bind(db), `post:${pid}:diffs`, diff.score), @@ -33,7 +33,7 @@ module.exports = { patch: diff.value, }), ], next); - }, function (err) { + }, (err) => { if (err) { return next(err); } @@ -42,7 +42,7 @@ module.exports = { return next(); }); }); - }, function (err) { + }, (err) => { if (err) { // Probably type error, ok to incr and continue progress.incr(); diff --git a/src/upgrades/1.9.0/refresh_post_upload_associations.js b/src/upgrades/1.9.0/refresh_post_upload_associations.js index e176835940..1e5fc84450 100644 --- a/src/upgrades/1.9.0/refresh_post_upload_associations.js +++ b/src/upgrades/1.9.0/refresh_post_upload_associations.js @@ -9,8 +9,8 @@ module.exports = { method: function (callback) { var progress = this.progress; - require('../../batch').processSortedSet('posts:pid', function (pids, next) { - async.each(pids, function (pid, next) { + require('../../batch').processSortedSet('posts:pid', (pids, next) => { + async.each(pids, (pid, next) => { posts.uploads.sync(pid, next); progress.incr(); }, next); diff --git a/src/user/admin.js b/src/user/admin.js index ec09aa7f6b..51468a2a1b 100644 --- a/src/user/admin.js +++ b/src/user/admin.js @@ -59,7 +59,7 @@ module.exports = function (User) { await batch.processSortedSet('users:joindate', async (uids) => { const usersData = await User.getUsersFields(uids, data.fields.slice()); let line = ''; - usersData.forEach(function (user) { + usersData.forEach((user) => { line += `${data.fields.map(field => user[field]).join(',')}\n`; }); diff --git a/src/user/approval.js b/src/user/approval.js index 6074ab1728..04974b8470 100644 --- a/src/user/approval.js +++ b/src/user/approval.js @@ -14,9 +14,9 @@ const slugify = require('../slugify'); const plugins = require('../plugins'); module.exports = function (User) { - new cronJob('0 * * * *', function () { + new cronJob('0 * * * *', (() => { User.autoApprove(); - }, null, true); + }), null, true); User.addToApprovalQueue = async function (userData) { userData.username = userData.username.trim(); @@ -120,7 +120,7 @@ module.exports = function (User) { const data = await db.getSortedSetRevRangeWithScores('registration:queue', start, stop); const keys = data.filter(Boolean).map(user => `registration:queue:name:${user.value}`); let users = await db.getObjects(keys); - users = users.filter(Boolean).map(function (user, index) { + users = users.filter(Boolean).map((user, index) => { user.timestampISO = utils.toISOString(data[index].score); user.email = validator.escape(String(user.email)); user.usernameEscaped = validator.escape(String(user.username)); diff --git a/src/user/auth.js b/src/user/auth.js index 91d5b371aa..21a050480f 100644 --- a/src/user/auth.js +++ b/src/user/auth.js @@ -69,7 +69,7 @@ module.exports = function (User) { await cleanExpiredSessions(uid); const sids = await db.getSortedSetRevRange(`uid:${uid}:sessions`, 0, 19); let sessions = await Promise.all(sids.map(sid => getSessionFromStore(sid))); - sessions = sessions.map(function (sessObj, idx) { + sessions = sessions.map((sessObj, idx) => { if (sessObj && sessObj.meta) { sessObj.meta.current = curSessionId === sids[idx]; sessObj.meta.datetimeISO = new Date(sessObj.meta.datetime).toISOString(); @@ -142,7 +142,7 @@ module.exports = function (User) { }; User.auth.deleteAllSessions = async function () { - await batch.processSortedSet('users:joindate', async function (uids) { + await batch.processSortedSet('users:joindate', async (uids) => { const sessionKeys = uids.map(uid => `uid:${uid}:sessions`); const sessionUUIDKeys = uids.map(uid => `uid:${uid}:sessionUUID:sessionId`); const sids = _.flatten(await db.getSortedSetRange(sessionKeys, 0, -1)); diff --git a/src/user/blocks.js b/src/user/blocks.js index 7c805deda9..7980efc64d 100644 --- a/src/user/blocks.js +++ b/src/user/blocks.js @@ -54,7 +54,7 @@ module.exports = function (User) { return blocked; }; - pubsub.on('user:blocks:cache:del', function (uid) { + pubsub.on('user:blocks:cache:del', (uid) => { User.blocks._cache.del(uid); }); @@ -86,7 +86,7 @@ module.exports = function (User) { }; User.blocks.filterUids = async function (targetUid, uids) { - return await async.filter(uids, async function (uid) { + return await async.filter(uids, async (uid) => { const isBlocked = await User.blocks.is(targetUid, uid); return !isBlocked; }); @@ -108,9 +108,7 @@ module.exports = function (User) { const blocked_uids = await User.blocks.list(uid); const blockedSet = new Set(blocked_uids); - set = set.filter(function (item) { - return !blockedSet.has(parseInt(isPlain ? item : (item && item[property]), 10)); - }); + set = set.filter(item => !blockedSet.has(parseInt(isPlain ? item : (item && item[property]), 10))); const data = await plugins.hooks.fire('filter:user.blocks.filter', { set: set, property: property, uid: uid, blockedSet: blockedSet }); return data.set; diff --git a/src/user/data.js b/src/user/data.js index 59ec983635..2f94f24c2a 100644 --- a/src/user/data.js +++ b/src/user/data.js @@ -116,7 +116,7 @@ module.exports = function (User) { function uidsToUsers(uids, uniqueUids, usersData) { const uidToUser = _.zipObject(uniqueUids, usersData); - const users = uids.map(function (uid) { + const users = uids.map((uid) => { const user = uidToUser[uid] || { ...User.guestData }; if (!parseInt(user.uid, 10)) { user.username = (user.hasOwnProperty('oldUid') && parseInt(user.oldUid, 10)) ? '[[global:former_user]]' : '[[global:guest]]'; @@ -157,7 +157,7 @@ module.exports = function (User) { )); } - await Promise.all(users.map(async function (user) { + await Promise.all(users.map(async (user) => { if (!user) { return; } @@ -205,9 +205,7 @@ module.exports = function (User) { // User Icons if (user.hasOwnProperty('picture') && user.username && parseInt(user.uid, 10) && !meta.config.defaultAvatar) { user['icon:text'] = (user.username[0] || '').toUpperCase(); - user['icon:bgColor'] = iconBackgrounds[Array.prototype.reduce.call(user.username, function (cur, next) { - return cur + next.charCodeAt(); - }, 0) % iconBackgrounds.length]; + user['icon:bgColor'] = iconBackgrounds[Array.prototype.reduce.call(user.username, (cur, next) => cur + next.charCodeAt(), 0) % iconBackgrounds.length]; } if (user.hasOwnProperty('joindate')) { diff --git a/src/user/delete.js b/src/user/delete.js index d5285c199f..4367914b4c 100644 --- a/src/user/delete.js +++ b/src/user/delete.js @@ -40,24 +40,24 @@ module.exports = function (User) { }; async function deletePosts(callerUid, uid) { - await batch.processSortedSet(`uid:${uid}:posts`, async function (ids) { - await async.eachSeries(ids, async function (pid) { + await batch.processSortedSet(`uid:${uid}:posts`, async (ids) => { + await async.eachSeries(ids, async (pid) => { await posts.purge(pid, callerUid); }); }, { alwaysStartAt: 0 }); } async function deleteTopics(callerUid, uid) { - await batch.processSortedSet(`uid:${uid}:topics`, async function (ids) { - await async.eachSeries(ids, async function (tid) { + await batch.processSortedSet(`uid:${uid}:topics`, async (ids) => { + await async.eachSeries(ids, async (tid) => { await topics.purge(tid, callerUid); }); }, { alwaysStartAt: 0 }); } async function deleteUploads(uid) { - await batch.processSortedSet(`uid:${uid}:uploads`, async function (uploadNames) { - await async.each(uploadNames, async function (uploadName) { + await batch.processSortedSet(`uid:${uid}:uploads`, async (uploadNames) => { + await async.each(uploadNames, async (uploadName) => { await file.delete(path.join(nconf.get('upload_path'), uploadName)); }); await db.sortedSetRemove(`uid:${uid}:uploads`, uploadNames); @@ -66,7 +66,7 @@ module.exports = function (User) { async function deleteQueued(uid) { let deleteIds = []; - await batch.processSortedSet('post:queue', async function (ids) { + await batch.processSortedSet('post:queue', async (ids) => { const data = await db.getObjects(ids.map(id => `post:queue:${id}`)); const userQueuedIds = data.filter(d => parseInt(d.uid, 10) === parseInt(uid, 10)).map(d => d.id); deleteIds = deleteIds.concat(userQueuedIds); @@ -165,7 +165,7 @@ module.exports = function (User) { db.getSortedSetRange(`uid:${uid}:downvote`, 0, -1), ]); const pids = _.uniq(upvotedPids.concat(downvotedPids).filter(Boolean)); - await async.eachSeries(pids, async function (pid) { + await async.eachSeries(pids, async (pid) => { await posts.unvote(pid, uid); }); } @@ -199,7 +199,7 @@ module.exports = function (User) { ]); async function updateCount(uids, name, fieldName) { - await async.each(uids, async function (uid) { + await async.each(uids, async (uid) => { let count = await db.sortedSetCard(name + uid); count = parseInt(count, 10) || 0; await db.setObjectField(`user:${uid}`, fieldName, count); diff --git a/src/user/digest.js b/src/user/digest.js index c793cfce6e..14da55e953 100644 --- a/src/user/digest.js +++ b/src/user/digest.js @@ -72,10 +72,10 @@ Digest.getUsersInterval = async (uids) => { Digest.getSubscribers = async function (interval) { var subscribers = []; - await batch.processSortedSet('users:joindate', async function (uids) { + await batch.processSortedSet('users:joindate', async (uids) => { const settings = await user.getMultipleUserSettings(uids); let subUids = []; - settings.forEach(function (hash) { + settings.forEach((hash) => { if (hash.dailyDigestFreq === interval) { subUids.push(hash.uid); } @@ -100,7 +100,7 @@ Digest.send = async function (data) { return emailsSent; } - await async.eachLimit(data.subscribers, 100, async function (uid) { + await async.eachLimit(data.subscribers, 100, async (uid) => { const userObj = await user.getUserFields(uid, ['uid', 'username', 'userslug', 'lastonline']); const [notifications, topTopics, popularTopics, recentTopics] = await Promise.all([ user.notifications.getUnreadInterval(userObj.uid, data.interval), @@ -114,7 +114,7 @@ Digest.send = async function (data) { return; } - unreadNotifs.forEach(function (n) { + unreadNotifs.forEach((n) => { if (n.image && !n.image.startsWith('http')) { n.image = nconf.get('base_url') + n.image; } @@ -184,7 +184,7 @@ async function getTermTopics(term, uid, start, stop, sort) { await topics.getLatestTopics(options) : await topics.getSortedTopics(options); - data.topics.forEach(function (topicObj) { + data.topics.forEach((topicObj) => { if (topicObj) { if (topicObj.teaser && topicObj.teaser.content && topicObj.teaser.content.length > 255) { topicObj.teaser.content = `${topicObj.teaser.content.slice(0, 255)}...`; diff --git a/src/user/info.js b/src/user/info.js index 946bb46c17..4e113432f4 100644 --- a/src/user/info.js +++ b/src/user/info.js @@ -40,7 +40,7 @@ module.exports = function (User) { const payload = await db.getObjectsFields(keys, ['type', 'targetId']); // Only pass on flag ids from posts - flags = payload.reduce(function (memo, cur, idx) { + flags = payload.reduce((memo, cur, idx) => { if (cur.type === 'post') { memo.push({ value: parseInt(cur.targetId, 10), @@ -64,7 +64,7 @@ module.exports = function (User) { User.getHistory = async function (set) { const data = await db.getSortedSetRevRangeWithScores(set, 0, -1); - return data.map(function (set) { + return data.map((set) => { set.timestamp = set.score; set.timestampISO = utils.toISOString(set.score); set.value = validator.escape(String(set.value.split(':')[0])); @@ -79,7 +79,7 @@ module.exports = function (User) { const tids = postData.map(post => post.tid); const topicData = await topics.getTopicsFields(tids, ['title']); - flags = flags.map(function (flagObj, idx) { + flags = flags.map((flagObj, idx) => { flagObj.pid = flagObj.value; flagObj.timestamp = flagObj.score; flagObj.timestampISO = new Date(flagObj.score).toISOString(); @@ -99,7 +99,7 @@ module.exports = function (User) { const banData = await db.getObjects(bans); const uids = banData.map(banData => banData.fromUid); const usersData = await User.getUsersFields(uids, ['uid', 'username', 'userslug', 'picture']); - return banData.map(function (banObj, index) { + return banData.map((banObj, index) => { banObj.user = usersData[index]; banObj.until = parseInt(banObj.expire, 10); banObj.untilReadable = new Date(banObj.until).toString(); @@ -116,7 +116,7 @@ module.exports = function (User) { const notes = await db.getObjects(keys); const uids = []; - const noteData = notes.map(function (note) { + const noteData = notes.map((note) => { if (note) { uids.push(note.uid); note.timestampISO = utils.toISOString(note.timestamp); @@ -126,7 +126,7 @@ module.exports = function (User) { }); const userData = await User.getUsersFields(uids, ['uid', 'username', 'userslug', 'picture']); - noteData.forEach(function (note, index) { + noteData.forEach((note, index) => { if (note) { note.user = userData[index]; } diff --git a/src/user/invite.js b/src/user/invite.js index 86ae825dbc..13c8163e76 100644 --- a/src/user/invite.js +++ b/src/user/invite.js @@ -29,12 +29,10 @@ module.exports = function (User) { User.getAllInvites = async function () { const uids = await User.getInvitingUsers(); const invitations = await async.map(uids, User.getInvites); - return invitations.map(function (invites, index) { - return { - uid: uids[index], - invitations: invites, - }; - }); + return invitations.map((invites, index) => ({ + uid: uids[index], + invitations: invites, + })); }; User.sendInvitationEmail = async function (uid, email, groupsToJoin) { diff --git a/src/user/jobs.js b/src/user/jobs.js index b9a86c06f9..1ef3c95377 100644 --- a/src/user/jobs.js +++ b/src/user/jobs.js @@ -36,10 +36,10 @@ module.exports = function (User) { }; function startDigestJob(name, cronString, term) { - jobs[name] = new cronJob(cronString, function () { + jobs[name] = new cronJob(cronString, (() => { winston.verbose(`[user/jobs] Digest job (${name}) started.`); User.digest.execute({ interval: term }); - }, null, true); + }), null, true); winston.verbose(`[user/jobs] Starting job (${name})`); } diff --git a/src/user/jobs/export-posts.js b/src/user/jobs/export-posts.js index 1acaeaeeac..3f1e39b170 100644 --- a/src/user/jobs/export-posts.js +++ b/src/user/jobs/export-posts.js @@ -22,7 +22,7 @@ prestart.setupWinston(); const db = require('../../database'); const batch = require('../../batch'); -process.on('message', async function (msg) { +process.on('message', async (msg) => { if (msg && msg.uid) { await db.init(); @@ -32,10 +32,10 @@ process.on('message', async function (msg) { const posts = require('../../posts'); let payload = []; - await batch.processSortedSet(`uid:${targetUid}:posts`, async function (pids) { + await batch.processSortedSet(`uid:${targetUid}:posts`, async (pids) => { let postData = await posts.getPostsData(pids); // Remove empty post references and convert newlines in content - postData = postData.filter(Boolean).map(function (post) { + postData = postData.filter(Boolean).map((post) => { post.content = `"${String(post.content || '').replace(/\n/g, '\\n').replace(/"/g, '\\"')}"`; return post; }); diff --git a/src/user/jobs/export-profile.js b/src/user/jobs/export-profile.js index 22a6cb95cc..8fb2dce0c7 100644 --- a/src/user/jobs/export-profile.js +++ b/src/user/jobs/export-profile.js @@ -22,7 +22,7 @@ prestart.setupWinston(); const db = require('../../database'); const batch = require('../../batch'); -process.on('message', async function (msg) { +process.on('message', async (msg) => { if (msg && msg.uid) { await db.init(); await db.initSessionStore(); diff --git a/src/user/jobs/export-uploads.js b/src/user/jobs/export-uploads.js index b6d8cd5a4f..a3bc097a49 100644 --- a/src/user/jobs/export-uploads.js +++ b/src/user/jobs/export-uploads.js @@ -22,7 +22,7 @@ prestart.setupWinston(); const db = require('../../database'); -process.on('message', async function (msg) { +process.on('message', async (msg) => { if (msg && msg.uid) { await db.init(); @@ -37,7 +37,7 @@ process.on('message', async function (msg) { zlib: { level: 9 }, // Sets the compression level. }); - archive.on('warning', function (err) { + archive.on('warning', (err) => { switch (err.code) { case 'ENOENT': winston.warn(`[user/export/uploads] File not found: ${err.path}`); @@ -49,7 +49,7 @@ process.on('message', async function (msg) { } }); - archive.on('error', function (err) { + archive.on('error', (err) => { const trimPath = function (path) { return path.replace(rootDirectory, ''); }; @@ -65,7 +65,7 @@ process.on('message', async function (msg) { }); const output = fs.createWriteStream(archivePath); - output.on('close', async function () { + output.on('close', async () => { await db.close(); process.exit(0); }); diff --git a/src/user/notifications.js b/src/user/notifications.js index b6be13f384..46fd795206 100644 --- a/src/user/notifications.js +++ b/src/user/notifications.js @@ -48,7 +48,7 @@ UserNotifications.getAll = async function (uid, filter) { const exists = await db.isSortedSetMembers('notifications', nids); var deleteNids = []; - nids = nids.filter(function (nid, index) { + nids = nids.filter((nid, index) => { if (!nid || !exists[index]) { deleteNids.push(nid); } @@ -82,7 +82,7 @@ UserNotifications.getNotifications = async function (nids, uid) { ]); const deletedNids = []; - let notificationData = notifObjs.filter(function (notification, index) { + let notificationData = notifObjs.filter((notification, index) => { if (!notification || !notification.nid) { deletedNids.push(nids[index]); } @@ -133,7 +133,7 @@ UserNotifications.getUnreadCount = async function (uid) { const mergeIds = notifData.map(n => n.mergeId); // Collapse any notifications with identical mergeIds - return mergeIds.reduce(function (count, mergeId, idx, arr) { + return mergeIds.reduce((count, mergeId, idx, arr) => { // A missing (null) mergeId means that notification is counted separately. if (mergeId === null || idx === arr.indexOf(mergeId)) { count += 1; diff --git a/src/user/profile.js b/src/user/profile.js index bce17ad442..f8d6ab787a 100644 --- a/src/user/profile.js +++ b/src/user/profile.js @@ -35,7 +35,7 @@ module.exports = function (User) { const oldData = await User.getUserFields(updateUid, fields); - await async.each(fields, async function (field) { + await async.each(fields, async (field) => { if (!(data[field] !== undefined && typeof data[field] === 'string')) { return; } diff --git a/src/user/reset.js b/src/user/reset.js index be3c0d3527..507cac674e 100644 --- a/src/user/reset.js +++ b/src/user/reset.js @@ -129,7 +129,7 @@ UserReset.cleanByUid = async function (uid) { const tokensToClean = []; uid = parseInt(uid, 10); - await batch.processSortedSet('reset:issueDate', async function (tokens) { + await batch.processSortedSet('reset:issueDate', async (tokens) => { const results = await db.getObjectFields('reset:uid', tokens); for (var code in results) { if (results.hasOwnProperty(code) && parseInt(results[code], 10) === uid) { diff --git a/src/user/search.js b/src/user/search.js index 317c3ebfd7..2713b3a8dd 100644 --- a/src/user/search.js +++ b/src/user/search.js @@ -92,7 +92,7 @@ module.exports = function (User) { fields.push(data.sortBy); } - filters.forEach(function (filter) { + filters.forEach((filter) => { if (filterFieldMap[filter]) { fields.push(...filterFieldMap[filter]); } @@ -116,7 +116,7 @@ module.exports = function (User) { fields.push('uid'); let userData = await User.getUsersFields(uids, fields); - filters.forEach(function (filter) { + filters.forEach((filter) => { if (filterFnMap[filter]) { userData = userData.filter(filterFnMap[filter]); } @@ -140,7 +140,7 @@ module.exports = function (User) { if (isNumeric) { userData.sort((u1, u2) => direction * (u2[sortBy] - u1[sortBy])); } else { - userData.sort(function (u1, u2) { + userData.sort((u1, u2) => { if (u1[sortBy] < u2[sortBy]) { return direction * -1; } else if (u1[sortBy] > u2[sortBy]) { diff --git a/src/user/settings.js b/src/user/settings.js index bad45000e0..490282e46f 100644 --- a/src/user/settings.js +++ b/src/user/settings.js @@ -27,7 +27,7 @@ module.exports = function (User) { const keys = uids.map(uid => `user:${uid}:settings`); let settings = await db.getObjects(keys); - settings = settings.map(function (userSettings, index) { + settings = settings.map((userSettings, index) => { userSettings = userSettings || {}; userSettings.uid = uids[index]; return userSettings; @@ -73,7 +73,7 @@ module.exports = function (User) { settings.categoryWatchState = getSetting(settings, 'categoryWatchState', 'notwatching'); const notificationTypes = await notifications.getAllNotificationTypes(); - notificationTypes.forEach(function (notificationType) { + notificationTypes.forEach((notificationType) => { settings[notificationType] = getSetting(settings, notificationType, 'notification'); }); @@ -135,7 +135,7 @@ module.exports = function (User) { topicPostSort: data.topicPostSort, }; const notificationTypes = await notifications.getAllNotificationTypes(); - notificationTypes.forEach(function (notificationType) { + notificationTypes.forEach((notificationType) => { if (data[notificationType]) { settings[notificationType] = data[notificationType]; } diff --git a/src/user/uploads.js b/src/user/uploads.js index 4bc4027d13..066730249e 100644 --- a/src/user/uploads.js +++ b/src/user/uploads.js @@ -31,8 +31,8 @@ module.exports = function (User) { }; User.collateUploads = async function (uid, archive) { - await batch.processSortedSet(`uid:${uid}:uploads`, function (files, next) { - files.forEach(function (file) { + await batch.processSortedSet(`uid:${uid}:uploads`, (files, next) => { + files.forEach((file) => { archive.file(path.join(nconf.get('upload_path'), file), { name: path.basename(file), }); diff --git a/src/webserver.js b/src/webserver.js index fa8628202e..d23318024d 100644 --- a/src/webserver.js +++ b/src/webserver.js @@ -48,7 +48,7 @@ if (nconf.get('ssl')) { module.exports.server = server; module.exports.app = app; -server.on('error', function (err) { +server.on('error', (err) => { if (err.code === 'EADDRINUSE') { winston.error(`NodeBB address in use, exiting...\n${err.stack}`); } else { @@ -60,10 +60,10 @@ server.on('error', function (err) { // see https://github.com/isaacs/server-destroy/blob/master/index.js var connections = {}; -server.on('connection', function (conn) { +server.on('connection', (conn) => { var key = `${conn.remoteAddress}:${conn.remotePort}`; connections[key] = conn; - conn.on('close', function () { + conn.on('close', () => { delete connections[key]; }); }); @@ -117,7 +117,7 @@ function setupExpressApp(app) { const relativePath = nconf.get('relative_path'); const viewsDir = nconf.get('views_dir'); - app.engine('tpl', function (filepath, data, next) { + app.engine('tpl', (filepath, data, next) => { filepath = filepath.replace(/\.tpl$/, '.js'); Benchpress.__express(filepath, data, next); @@ -150,11 +150,11 @@ function setupExpressApp(app) { app.use(cookieParser(nconf.get('secret'))); const userAgentMiddleware = useragent.express(); - app.use(function userAgent(req, res, next) { + app.use((req, res, next) => { userAgentMiddleware(req, res, next); }); const spiderDetectorMiddleware = detector.middleware(); - app.use(function spiderDetector(req, res, next) { + app.use((req, res, next) => { spiderDetectorMiddleware(req, res, next); }); @@ -261,7 +261,7 @@ function listen(callback) { var args = isSocket ? [socketPath] : [port, bind_address]; var oldUmask; - args.push(function (err) { + args.push((err) => { if (err) { winston.info(`[startup] NodeBB was unable to listen on: ${bind_address}:${port}`); process.exit(); @@ -277,7 +277,7 @@ function listen(callback) { // Alter umask if necessary if (isSocket) { oldUmask = process.umask('0000'); - module.exports.testSocket(socketPath, function (err) { + module.exports.testSocket(socketPath, (err) => { if (err) { winston.error(`[startup] NodeBB was unable to secure domain socket access (${socketPath})\n${err.stack}`); throw err; @@ -298,7 +298,7 @@ exports.testSocket = function (socketPath, callback) { var file = require('./file'); async.series([ function (next) { - file.exists(socketPath, function (err, exists) { + file.exists(socketPath, (err, exists) => { if (exists) { next(); } else { @@ -308,10 +308,10 @@ exports.testSocket = function (socketPath, callback) { }, function (next) { var testSocket = new net.Socket(); - testSocket.on('error', function (err) { + testSocket.on('error', (err) => { next(err.code !== 'ECONNREFUSED' ? err : null); }); - testSocket.connect({ path: socketPath }, function () { + testSocket.connect({ path: socketPath }, () => { // Something's listening here, abort callback(new Error('port-in-use')); }); diff --git a/src/widgets/admin.js b/src/widgets/admin.js index cfc3e50a8c..d6e67f6917 100644 --- a/src/widgets/admin.js +++ b/src/widgets/admin.js @@ -45,7 +45,7 @@ async function getAvailableWidgets() { plugins.hooks.fire('filter:widgets.getWidgets', []), renderAdminTemplate(), ]); - availableWidgets.forEach(function (w) { + availableWidgets.forEach((w) => { w.content += adminTemplate; }); return availableWidgets; @@ -62,7 +62,7 @@ function buildTemplatesFromAreas(areas) { const list = {}; let index = 0; - areas.forEach(function (area) { + areas.forEach((area) => { if (typeof list[area.template] === 'undefined') { list[area.template] = index; templates.push({ diff --git a/src/widgets/index.js b/src/widgets/index.js index 9a6f492786..2c38436144 100644 --- a/src/widgets/index.js +++ b/src/widgets/index.js @@ -25,7 +25,7 @@ widgets.render = async function (uid, options) { const widgetData = await Promise.all(locations.map(location => renderLocation(location, data, uid, options))); const returnData = {}; - locations.forEach(function (location, i) { + locations.forEach((location, i) => { if (Array.isArray(widgetData[i]) && widgetData[i].length) { returnData[location] = widgetData[i].filter(Boolean); } @@ -110,13 +110,13 @@ widgets.getWidgetDataForTemplates = async function (templates) { const returnData = {}; - templates.forEach(function (template, index) { + templates.forEach((template, index) => { returnData[template] = returnData[template] || {}; const templateWidgetData = data[index] || {}; const locations = Object.keys(templateWidgetData); - locations.forEach(function (location) { + locations.forEach((location) => { if (templateWidgetData && templateWidgetData[location]) { try { returnData[template][location] = parseWidgetData(templateWidgetData[location]); @@ -143,7 +143,7 @@ widgets.getArea = async function (template, location) { function parseWidgetData(data) { const widgets = JSON.parse(data); - widgets.forEach(function (widget) { + widgets.forEach((widget) => { if (widget) { widget.data.groups = widget.data.groups || []; if (widget.data.groups && !Array.isArray(widget.data.groups)) { diff --git a/test/api.js b/test/api.js index 0bf95e8fff..af21409775 100644 --- a/test/api.js +++ b/test/api.js @@ -98,7 +98,7 @@ describe('API', async () => { // pretend to handle sending emails } - after(async function () { + after(async () => { plugins.hooks.unregister('core', 'filter:search.query', dummySearchHook); plugins.hooks.unregister('emailer-test', 'filter:email.send'); }); @@ -251,14 +251,12 @@ describe('API', async () => { return _.flatten(paths); }; - let paths = buildPaths(webserver.app._router.stack).filter(Boolean).map(function normalize(pathObj) { + let paths = buildPaths(webserver.app._router.stack).filter(Boolean).map((pathObj) => { pathObj.path = pathObj.path.replace(/\/:([^\\/]+)/g, '/{$1}'); return pathObj; }); const exclusionPrefixes = ['/api/admin/plugins', '/api/compose', '/debug']; - paths = paths.filter(function filterExclusions(path) { - return path.method !== '_all' && !exclusionPrefixes.some(prefix => path.path.startsWith(prefix)); - }); + paths = paths.filter(path => path.method !== '_all' && !exclusionPrefixes.some(prefix => path.path.startsWith(prefix))); // For each express path, query for existence in read and write api schemas @@ -393,7 +391,7 @@ describe('API', async () => { }); } else if (type === 'form') { response = await new Promise((resolve, reject) => { - helpers.uploadFile(url, pathLib.join(__dirname, './files/test.png'), {}, jar, csrfToken, function (err, res) { + helpers.uploadFile(url, pathLib.join(__dirname, './files/test.png'), {}, jar, csrfToken, (err, res) => { if (err) { return reject(err); } diff --git a/test/authentication.js b/test/authentication.js index 6b299f6254..bbe2567d3f 100644 --- a/test/authentication.js +++ b/test/authentication.js @@ -14,14 +14,14 @@ var meta = require('../src/meta'); var privileges = require('../src/privileges'); var helpers = require('./helpers'); -describe('authentication', function () { +describe('authentication', () => { function loginUser(username, password, callback) { var jar = request.jar(); request({ url: `${nconf.get('url')}/api/config`, json: true, jar: jar, - }, function (err, response, body) { + }, (err, response, body) => { if (err) { return callback(err); } @@ -36,7 +36,7 @@ describe('authentication', function () { headers: { 'x-csrf-token': body.csrf_token, }, - }, function (err, response, body) { + }, (err, response, body) => { callback(err, response, body, jar); }); }); @@ -49,7 +49,7 @@ describe('authentication', function () { url: `${nconf.get('url')}/api/config`, json: true, jar: jar, - }, function (err, response, body) { + }, (err, response, body) => { if (err) { return callback(err); } @@ -67,7 +67,7 @@ describe('authentication', function () { headers: { 'x-csrf-token': body.csrf_token, }, - }, function (err, response, body) { + }, (err, response, body) => { callback(err, response, body, jar); }); }); @@ -75,21 +75,21 @@ describe('authentication', function () { var jar = request.jar(); var regularUid; - before(function (done) { - user.create({ username: 'regular', password: 'regularpwd', email: 'regular@nodebb.org' }, function (err, uid) { + before((done) => { + user.create({ username: 'regular', password: 'regularpwd', email: 'regular@nodebb.org' }, (err, uid) => { assert.ifError(err); regularUid = uid; done(); }); }); - it('should fail to create user if username is too short', function (done) { + it('should fail to create user if username is too short', (done) => { helpers.registerUser({ username: 'a', password: '123456', 'password-confirm': '123456', email: 'should@error1.com', - }, function (err, jar, response, body) { + }, (err, jar, response, body) => { assert.ifError(err); assert.equal(response.statusCode, 400); assert.equal(body, '[[error:username-too-short]]'); @@ -97,13 +97,13 @@ describe('authentication', function () { }); }); - it('should fail to create user if userslug is too short', function (done) { + it('should fail to create user if userslug is too short', (done) => { helpers.registerUser({ username: '----a-----', password: '123456', 'password-confirm': '123456', email: 'should@error2.com', - }, function (err, jar, response, body) { + }, (err, jar, response, body) => { assert.ifError(err); assert.equal(response.statusCode, 400); assert.equal(body, '[[error:username-too-short]]'); @@ -111,13 +111,13 @@ describe('authentication', function () { }); }); - it('should fail to create user if userslug is too short', function (done) { + it('should fail to create user if userslug is too short', (done) => { helpers.registerUser({ username: ' a', password: '123456', 'password-confirm': '123456', email: 'should@error3.com', - }, function (err, jar, response, body) { + }, (err, jar, response, body) => { assert.ifError(err); assert.equal(response.statusCode, 400); assert.equal(body, '[[error:username-too-short]]'); @@ -125,13 +125,13 @@ describe('authentication', function () { }); }); - it('should fail to create user if userslug is too short', function (done) { + it('should fail to create user if userslug is too short', (done) => { helpers.registerUser({ username: 'a ', password: '123456', 'password-confirm': '123456', email: 'should@error4.com', - }, function (err, jar, response, body) { + }, (err, jar, response, body) => { assert.ifError(err); assert.equal(response.statusCode, 400); assert.equal(body, '[[error:username-too-short]]'); @@ -140,12 +140,12 @@ describe('authentication', function () { }); - it('should register and login a user', function (done) { + it('should register and login a user', (done) => { request({ url: `${nconf.get('url')}/api/config`, json: true, jar: jar, - }, function (err, response, body) { + }, (err, response, body) => { assert.ifError(err); request.post(`${nconf.get('url')}/register`, { @@ -162,7 +162,7 @@ describe('authentication', function () { headers: { 'x-csrf-token': body.csrf_token, }, - }, function (err, response, body) { + }, (err, response, body) => { assert.ifError(err); assert(body); @@ -170,12 +170,12 @@ describe('authentication', function () { url: `${nconf.get('url')}/api/self`, json: true, jar: jar, - }, function (err, response, body) { + }, (err, response, body) => { assert.ifError(err); assert(body); assert.equal(body.username, 'admin'); assert.equal(body.email, 'admin@nodebb.org'); - user.getSettings(body.uid, function (err, settings) { + user.getSettings(body.uid, (err, settings) => { assert.ifError(err); assert.equal(settings.userLang, 'it'); done(); @@ -185,14 +185,14 @@ describe('authentication', function () { }); }); - it('should logout a user', function (done) { - helpers.logoutUser(jar, function (err) { + it('should logout a user', (done) => { + helpers.logoutUser(jar, (err) => { assert.ifError(err); request({ url: `${nconf.get('url')}/api/me`, json: true, jar: jar, - }, function (err, res, body) { + }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 401); assert.strictEqual(body.status.code, 'not-authorised'); @@ -201,20 +201,20 @@ describe('authentication', function () { }); }); - it('should login a user', function (done) { - loginUser('regular', 'regularpwd', function (err, response, body, jar) { + it('should login a user', (done) => { + loginUser('regular', 'regularpwd', (err, response, body, jar) => { assert.ifError(err); assert(body); request({ url: `${nconf.get('url')}/api/self`, json: true, jar: jar, - }, function (err, response, body) { + }, (err, response, body) => { assert.ifError(err); assert(body); assert.equal(body.username, 'regular'); assert.equal(body.email, 'regular@nodebb.org'); - db.getObject(`uid:${regularUid}:sessionUUID:sessionId`, function (err, sessions) { + db.getObject(`uid:${regularUid}:sessionUUID:sessionId`, (err, sessions) => { assert.ifError(err); assert(sessions); assert(Object.keys(sessions).length > 0); @@ -224,14 +224,14 @@ describe('authentication', function () { }); }); - it('should revoke all sessions', function (done) { + it('should revoke all sessions', (done) => { var socketAdmin = require('../src/socket.io/admin'); - db.sortedSetCard(`uid:${regularUid}:sessions`, function (err, count) { + db.sortedSetCard(`uid:${regularUid}:sessions`, (err, count) => { assert.ifError(err); assert(count); - socketAdmin.deleteAllSessions({ uid: 1 }, {}, function (err) { + socketAdmin.deleteAllSessions({ uid: 1 }, {}, (err) => { assert.ifError(err); - db.sortedSetCard(`uid:${regularUid}:sessions`, function (err, count) { + db.sortedSetCard(`uid:${regularUid}:sessions`, (err, count) => { assert.ifError(err); assert(!count); done(); @@ -240,13 +240,13 @@ describe('authentication', function () { }); }); - it('should fail to login if ip address is invalid', function (done) { + it('should fail to login if ip address is invalid', (done) => { var jar = request.jar(); request({ url: `${nconf.get('url')}/api/config`, json: true, jar: jar, - }, function (err, response, body) { + }, (err, response, body) => { if (err) { return done(err); } @@ -262,7 +262,7 @@ describe('authentication', function () { 'x-csrf-token': body.csrf_token, 'x-forwarded-for': '', }, - }, function (err, response, body) { + }, (err, response, body) => { assert.ifError(err); assert.equal(response.statusCode, 500); done(); @@ -270,8 +270,8 @@ describe('authentication', function () { }); }); - it('should fail to login if user does not exist', function (done) { - loginUser('doesnotexist', 'nopassword', function (err, response, body) { + it('should fail to login if user does not exist', (done) => { + loginUser('doesnotexist', 'nopassword', (err, response, body) => { assert.ifError(err); assert.equal(response.statusCode, 403); assert.equal(body, '[[error:invalid-login-credentials]]'); @@ -279,8 +279,8 @@ describe('authentication', function () { }); }); - it('should fail to login if username is empty', function (done) { - loginUser('', 'some password', function (err, response, body) { + it('should fail to login if username is empty', (done) => { + loginUser('', 'some password', (err, response, body) => { assert.ifError(err); assert.equal(response.statusCode, 403); assert.equal(body, '[[error:invalid-username-or-password]]'); @@ -288,8 +288,8 @@ describe('authentication', function () { }); }); - it('should fail to login if password is empty', function (done) { - loginUser('someuser', '', function (err, response, body) { + it('should fail to login if password is empty', (done) => { + loginUser('someuser', '', (err, response, body) => { assert.ifError(err); assert.equal(response.statusCode, 403); assert.equal(body, '[[error:invalid-username-or-password]]'); @@ -297,8 +297,8 @@ describe('authentication', function () { }); }); - it('should fail to login if username and password are empty', function (done) { - loginUser('', '', function (err, response, body) { + it('should fail to login if username and password are empty', (done) => { + loginUser('', '', (err, response, body) => { assert.ifError(err); assert.equal(response.statusCode, 403); assert.equal(body, '[[error:invalid-username-or-password]]'); @@ -306,10 +306,10 @@ describe('authentication', function () { }); }); - it('should fail to login if user does not have password field in db', function (done) { - user.create({ username: 'hasnopassword', email: 'no@pass.org' }, function (err, uid) { + it('should fail to login if user does not have password field in db', (done) => { + user.create({ username: 'hasnopassword', email: 'no@pass.org' }, (err, uid) => { assert.ifError(err); - loginUser('hasnopassword', 'doesntmatter', function (err, response, body) { + loginUser('hasnopassword', 'doesntmatter', (err, response, body) => { assert.ifError(err); assert.equal(response.statusCode, 403); assert.equal(body, '[[error:invalid-login-credentials]]'); @@ -318,12 +318,12 @@ describe('authentication', function () { }); }); - it('should fail to login if password is longer than 4096', function (done) { + it('should fail to login if password is longer than 4096', (done) => { var longPassword; for (var i = 0; i < 5000; i++) { longPassword += 'a'; } - loginUser('someuser', longPassword, function (err, response, body) { + loginUser('someuser', longPassword, (err, response, body) => { assert.ifError(err); assert.equal(response.statusCode, 403); assert.equal(body, '[[error:password-too-long]]'); @@ -331,10 +331,10 @@ describe('authentication', function () { }); }); - it('should fail to login if local login is disabled', function (done) { - privileges.global.rescind(['groups:local:login'], 'registered-users', function (err) { + it('should fail to login if local login is disabled', (done) => { + privileges.global.rescind(['groups:local:login'], 'registered-users', (err) => { assert.ifError(err); - loginUser('regular', 'regularpwd', function (err, response, body) { + loginUser('regular', 'regularpwd', (err, response, body) => { assert.ifError(err); assert.equal(response.statusCode, 403); assert.equal(body, '[[error:local-login-disabled]]'); @@ -343,9 +343,9 @@ describe('authentication', function () { }); }); - it('should fail to register if registraton is disabled', function (done) { + it('should fail to register if registraton is disabled', (done) => { meta.config.registrationType = 'disabled'; - registerUser('some@user.com', 'someuser', 'somepassword', function (err, response, body) { + registerUser('some@user.com', 'someuser', 'somepassword', (err, response, body) => { assert.ifError(err); assert.equal(response.statusCode, 403); assert.equal(body, 'Forbidden'); @@ -353,9 +353,9 @@ describe('authentication', function () { }); }); - it('should return error if invitation is not valid', function (done) { + it('should return error if invitation is not valid', (done) => { meta.config.registrationType = 'invite-only'; - registerUser('some@user.com', 'someuser', 'somepassword', function (err, response, body) { + registerUser('some@user.com', 'someuser', 'somepassword', (err, response, body) => { meta.config.registrationType = 'normal'; assert.ifError(err); assert.equal(response.statusCode, 400); @@ -364,8 +364,8 @@ describe('authentication', function () { }); }); - it('should fail to register if email is falsy', function (done) { - registerUser('', 'someuser', 'somepassword', function (err, response, body) { + it('should fail to register if email is falsy', (done) => { + registerUser('', 'someuser', 'somepassword', (err, response, body) => { assert.ifError(err); assert.equal(response.statusCode, 400); assert.equal(body, '[[error:invalid-email]]'); @@ -373,12 +373,12 @@ describe('authentication', function () { }); }); - it('should fail to register if username is falsy or too short', function (done) { - registerUser('some@user.com', '', 'somepassword', function (err, response, body) { + it('should fail to register if username is falsy or too short', (done) => { + registerUser('some@user.com', '', 'somepassword', (err, response, body) => { assert.ifError(err); assert.equal(response.statusCode, 400); assert.equal(body, '[[error:username-too-short]]'); - registerUser('some@user.com', 'a', 'somepassword', function (err, response, body) { + registerUser('some@user.com', 'a', 'somepassword', (err, response, body) => { assert.ifError(err); assert.equal(response.statusCode, 400); assert.equal(body, '[[error:username-too-short]]'); @@ -387,8 +387,8 @@ describe('authentication', function () { }); }); - it('should fail to register if username is too long', function (done) { - registerUser('some@user.com', 'thisisareallylongusername', '123456', function (err, response, body) { + it('should fail to register if username is too long', (done) => { + registerUser('some@user.com', 'thisisareallylongusername', '123456', (err, response, body) => { assert.ifError(err); assert.equal(response.statusCode, 400); assert.equal(body, '[[error:username-too-long]]'); @@ -396,9 +396,9 @@ describe('authentication', function () { }); }); - it('should queue user if ip is used before', function (done) { + it('should queue user if ip is used before', (done) => { meta.config.registrationApprovalType = 'admin-approval-ip'; - registerUser('another@user.com', 'anotheruser', 'anotherpwd', function (err, response, body) { + registerUser('another@user.com', 'anotheruser', 'anotherpwd', (err, response, body) => { meta.config.registrationApprovalType = 'normal'; assert.ifError(err); assert.equal(response.statusCode, 200); @@ -408,10 +408,10 @@ describe('authentication', function () { }); - it('should be able to login with email', function (done) { - user.create({ username: 'ginger', password: '123456', email: 'ginger@nodebb.org' }, function (err) { + it('should be able to login with email', (done) => { + user.create({ username: 'ginger', password: '123456', email: 'ginger@nodebb.org' }, (err) => { assert.ifError(err); - loginUser('ginger@nodebb.org', '123456', function (err, response) { + loginUser('ginger@nodebb.org', '123456', (err, response) => { assert.ifError(err); assert.equal(response.statusCode, 200); done(); @@ -419,9 +419,9 @@ describe('authentication', function () { }); }); - it('should fail to login if login type is username and an email is sent', function (done) { + it('should fail to login if login type is username and an email is sent', (done) => { meta.config.allowLoginWith = 'username'; - loginUser('ginger@nodebb.org', '123456', function (err, response, body) { + loginUser('ginger@nodebb.org', '123456', (err, response, body) => { meta.config.allowLoginWith = 'username-email'; assert.ifError(err); assert.equal(response.statusCode, 400); @@ -430,13 +430,13 @@ describe('authentication', function () { }); }); - it('should send 200 if not logged in', function (done) { + it('should send 200 if not logged in', (done) => { var jar = request.jar(); request({ url: `${nconf.get('url')}/api/config`, json: true, jar: jar, - }, function (err, response, body) { + }, (err, response, body) => { assert.ifError(err); request.post(`${nconf.get('url')}/logout`, { @@ -446,7 +446,7 @@ describe('authentication', function () { headers: { 'x-csrf-token': body.csrf_token, }, - }, function (err, res, body) { + }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert.equal(body, 'not-logged-in'); @@ -455,30 +455,30 @@ describe('authentication', function () { }); }); - describe('banned user authentication', function () { + describe('banned user authentication', () => { const bannedUser = { username: 'banme', pw: '123456', uid: null, }; - before(async function () { + before(async () => { bannedUser.uid = await user.create({ username: 'banme', password: '123456', email: 'ban@me.com' }); }); - it('should prevent banned user from logging in', function (done) { - user.bans.ban(bannedUser.uid, 0, 'spammer', function (err) { + it('should prevent banned user from logging in', (done) => { + user.bans.ban(bannedUser.uid, 0, 'spammer', (err) => { assert.ifError(err); - loginUser(bannedUser.username, bannedUser.pw, function (err, res, body) { + loginUser(bannedUser.username, bannedUser.pw, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 403); assert.equal(body, '[[error:user-banned-reason, spammer]]'); - user.bans.unban(bannedUser.uid, function (err) { + user.bans.unban(bannedUser.uid, (err) => { assert.ifError(err); var expiry = Date.now() + 10000; - user.bans.ban(bannedUser.uid, expiry, '', function (err) { + user.bans.ban(bannedUser.uid, expiry, '', (err) => { assert.ifError(err); - loginUser(bannedUser.username, bannedUser.pw, function (err, res, body) { + loginUser(bannedUser.username, bannedUser.pw, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 403); assert.equal(body, `[[error:user-banned-reason-until, ${utils.toISOString(expiry)}, No reason given.]]`); @@ -490,13 +490,13 @@ describe('authentication', function () { }); }); - it('should allow banned user to log in if the "banned-users" group has "local-login" privilege', async function () { + it('should allow banned user to log in if the "banned-users" group has "local-login" privilege', async () => { await privileges.global.give(['groups:local:login'], 'banned-users'); const res = await loginUserPromisified(bannedUser.username, bannedUser.pw); assert.strictEqual(res.statusCode, 200); }); - it('should allow banned user to log in if the user herself has "local-login" privilege', async function () { + it('should allow banned user to log in if the user herself has "local-login" privilege', async () => { await privileges.global.rescind(['groups:local:login'], 'banned-users'); await privileges.categories.give(['local:login'], 0, bannedUser.uid); const res = await loginUserPromisified(bannedUser.username, bannedUser.pw); @@ -504,7 +504,7 @@ describe('authentication', function () { }); }); - it('should lockout account on 3 failed login attempts', function (done) { + it('should lockout account on 3 failed login attempts', (done) => { meta.config.loginAttempts = 3; var uid; async.waterfall([ diff --git a/test/batch.js b/test/batch.js index 23bc4cb9a5..6d54431bfb 100644 --- a/test/batch.js +++ b/test/batch.js @@ -7,10 +7,10 @@ var db = require('./mocks/databasemock'); var batch = require('../src/batch'); -describe('batch', function () { +describe('batch', () => { const scores = []; const values = []; - before(function (done) { + before((done) => { for (let i = 0; i < 100; i++) { scores.push(i); values.push(`val${i}`); @@ -18,10 +18,10 @@ describe('batch', function () { db.sortedSetAdd('processMe', scores, values, done); }); - it('should process sorted set with callbacks', function (done) { + it('should process sorted set with callbacks', (done) => { let total = 0; - batch.processSortedSet('processMe', function (items, next) { - items.forEach(function (item) { + batch.processSortedSet('processMe', (items, next) => { + items.forEach((item) => { total += item.score; }); @@ -30,32 +30,32 @@ describe('batch', function () { withScores: true, interval: 50, batch: 10, - }, function (err) { + }, (err) => { assert.ifError(err); assert.strictEqual(total, 4950); done(); }); }); - it('should process sorted set with callbacks', function (done) { + it('should process sorted set with callbacks', (done) => { let total = 0; - batch.processSortedSet('processMe', function (values, next) { - values.forEach(function (val) { + batch.processSortedSet('processMe', (values, next) => { + values.forEach((val) => { total += val.length; }); setImmediate(next); - }, function (err) { + }, (err) => { assert.ifError(err); assert.strictEqual(total, 490); done(); }); }); - it('should process sorted set with async/await', async function () { + it('should process sorted set with async/await', async () => { let total = 0; - await batch.processSortedSet('processMe', function (values, next) { - values.forEach(function (val) { + await batch.processSortedSet('processMe', (values, next) => { + values.forEach((val) => { total += val.length; }); @@ -65,10 +65,10 @@ describe('batch', function () { assert.strictEqual(total, 490); }); - it('should process sorted set with async/await', async function () { + it('should process sorted set with async/await', async () => { let total = 0; - await batch.processSortedSet('processMe', async function (values) { - values.forEach(function (val) { + await batch.processSortedSet('processMe', async (values) => { + values.forEach((val) => { total += val.length; }); await db.getObject('doesnotexist'); @@ -77,10 +77,10 @@ describe('batch', function () { assert.strictEqual(total, 490); }); - it('should process array with callbacks', function (done) { + it('should process array with callbacks', (done) => { let total = 0; - batch.processArray(scores, function (nums, next) { - nums.forEach(function (n) { + batch.processArray(scores, (nums, next) => { + nums.forEach((n) => { total += n; }); @@ -89,17 +89,17 @@ describe('batch', function () { withScores: true, interval: 50, batch: 10, - }, function (err) { + }, (err) => { assert.ifError(err); assert.strictEqual(total, 4950); done(); }); }); - it('should process array with async/await', async function () { + it('should process array with async/await', async () => { let total = 0; - await batch.processArray(scores, function (nums, next) { - nums.forEach(function (n) { + await batch.processArray(scores, (nums, next) => { + nums.forEach((n) => { total += n; }); diff --git a/test/blacklist.js b/test/blacklist.js index d03aad341f..19850aeb61 100644 --- a/test/blacklist.js +++ b/test/blacklist.js @@ -8,11 +8,11 @@ var groups = require('../src/groups'); var user = require('../src/user'); var blacklist = require('../src/meta/blacklist'); -describe('blacklist', function () { +describe('blacklist', () => { var adminUid; - before(function (done) { - user.create({ username: 'admin' }, function (err, uid) { + before((done) => { + user.create({ username: 'admin' }, (err, uid) => { assert.ifError(err); adminUid = uid; groups.join('administrators', adminUid, done); @@ -22,45 +22,45 @@ describe('blacklist', function () { var socketBlacklist = require('../src/socket.io/blacklist'); var rules = '1.1.1.1\n2.2.2.2\n::ffff:0:2.2.2.2\n127.0.0.1\n192.168.100.0/22'; - it('should validate blacklist', function (done) { + it('should validate blacklist', (done) => { socketBlacklist.validate({ uid: adminUid }, { rules: rules, - }, function (err, data) { + }, (err, data) => { assert.ifError(err); done(); }); }); - it('should error if not admin', function (done) { - socketBlacklist.save({ uid: 0 }, rules, function (err) { + it('should error if not admin', (done) => { + socketBlacklist.save({ uid: 0 }, rules, (err) => { assert.equal(err.message, '[[error:no-privileges]]'); done(); }); }); - it('should save blacklist', function (done) { - socketBlacklist.save({ uid: adminUid }, rules, function (err) { + it('should save blacklist', (done) => { + socketBlacklist.save({ uid: adminUid }, rules, (err) => { assert.ifError(err); done(); }); }); - it('should pass ip test against blacklist', function (done) { - blacklist.test('3.3.3.3', function (err) { + it('should pass ip test against blacklist', (done) => { + blacklist.test('3.3.3.3', (err) => { assert.ifError(err); done(); }); }); - it('should fail ip test against blacklist', function (done) { - blacklist.test('1.1.1.1', function (err) { + it('should fail ip test against blacklist', (done) => { + blacklist.test('1.1.1.1', (err) => { assert.equal(err.message, '[[error:blacklisted-ip]]'); done(); }); }); - it('should pass ip test and not crash with ipv6 address', function (done) { - blacklist.test('2001:db8:85a3:0:0:8a2e:370:7334', function (err) { + it('should pass ip test and not crash with ipv6 address', (done) => { + blacklist.test('2001:db8:85a3:0:0:8a2e:370:7334', (err) => { assert.ifError(err); done(); }); diff --git a/test/build.js b/test/build.js index 4f50c84dcf..02b5e85254 100644 --- a/test/build.js +++ b/test/build.js @@ -10,8 +10,8 @@ var async = require('async'); var db = require('./mocks/databasemock'); var file = require('../src/file'); -describe('minifier', function () { - before(async function () { +describe('minifier', () => { + before(async () => { await mkdirp(path.join(__dirname, '../build/test')); }); @@ -19,22 +19,20 @@ describe('minifier', function () { var scripts = [ path.resolve(__dirname, './files/1.js'), path.resolve(__dirname, './files/2.js'), - ].map(function (script) { - return { - srcPath: script, - destPath: path.resolve(__dirname, '../build/test', path.basename(script)), - filename: path.basename(script), - }; - }); + ].map(script => ({ + srcPath: script, + destPath: path.resolve(__dirname, '../build/test', path.basename(script)), + filename: path.basename(script), + })); - it('.js.bundle() should concat scripts', function (done) { + it('.js.bundle() should concat scripts', (done) => { var destPath = path.resolve(__dirname, '../build/test/concatenated.js'); minifier.js.bundle({ files: scripts, destPath: destPath, filename: 'concatenated.js', - }, false, false, function (err) { + }, false, false, (err) => { assert.ifError(err); assert(file.existsSync(destPath)); @@ -55,14 +53,14 @@ describe('minifier', function () { done(); }); }); - it('.js.bundle() should minify scripts', function (done) { + it('.js.bundle() should minify scripts', (done) => { var destPath = path.resolve(__dirname, '../build/test/minified.js'); minifier.js.bundle({ files: scripts, destPath: destPath, filename: 'minified.js', - }, true, false, function (err) { + }, true, false, (err) => { assert.ifError(err); assert(file.existsSync(destPath)); @@ -76,14 +74,14 @@ describe('minifier', function () { }); }); - it('.js.minifyBatch() should minify each script', function (done) { - minifier.js.minifyBatch(scripts, false, function (err) { + it('.js.minifyBatch() should minify each script', (done) => { + minifier.js.minifyBatch(scripts, false, (err) => { assert.ifError(err); assert(file.existsSync(scripts[0].destPath)); assert(file.existsSync(scripts[1].destPath)); - fs.readFile(scripts[0].destPath, function (err, buffer) { + fs.readFile(scripts[0].destPath, (err, buffer) => { assert.ifError(err); assert.strictEqual( buffer.toString(), @@ -102,16 +100,16 @@ describe('minifier', function () { var paths = [ path.resolve(__dirname, './files'), ]; - it('.css.bundle() should concat styles', function (done) { - minifier.css.bundle(styles, paths, false, false, function (err, bundle) { + it('.css.bundle() should concat styles', (done) => { + minifier.css.bundle(styles, paths, false, false, (err, bundle) => { assert.ifError(err); assert.strictEqual(bundle.code, '.help { margin: 10px; } .yellow { background: yellow; }\n.help {\n display: block;\n}\n.help .blue {\n background: blue;\n}\n'); done(); }); }); - it('.css.bundle() should minify styles', function (done) { - minifier.css.bundle(styles, paths, true, false, function (err, bundle) { + it('.css.bundle() should minify styles', (done) => { + minifier.css.bundle(styles, paths, true, false, (err, bundle) => { assert.ifError(err); assert.strictEqual(bundle.code, '.help{margin:10px}.yellow{background:#ff0}.help{display:block}.help .blue{background:#00f}'); done(); @@ -119,26 +117,26 @@ describe('minifier', function () { }); }); -describe('Build', function (done) { +describe('Build', (done) => { var build = require('../src/meta/build'); - before(function (done) { + before((done) => { async.parallel([ async.apply(rimraf, path.join(__dirname, '../build/public')), async.apply(db.sortedSetAdd, 'plugins:active', Date.now(), 'nodebb-plugin-markdown'), ], done); }); - it('should build plugin static dirs', function (done) { - build.build(['plugin static dirs'], function (err) { + it('should build plugin static dirs', (done) => { + build.build(['plugin static dirs'], (err) => { assert.ifError(err); assert(file.existsSync(path.join(__dirname, '../build/public/plugins/nodebb-plugin-dbsearch/dbsearch'))); done(); }); }); - it('should build requirejs modules', function (done) { - build.build(['requirejs modules'], function (err) { + it('should build requirejs modules', (done) => { + build.build(['requirejs modules'], (err) => { assert.ifError(err); var filename = path.join(__dirname, '../build/public/src/modules/Chart.js'); assert(file.existsSync(filename)); @@ -147,8 +145,8 @@ describe('Build', function (done) { }); }); - it('should build client js bundle', function (done) { - build.build(['client js bundle'], function (err) { + it('should build client js bundle', (done) => { + build.build(['client js bundle'], (err) => { assert.ifError(err); var filename = path.join(__dirname, '../build/public/nodebb.min.js'); assert(file.existsSync(filename)); @@ -157,8 +155,8 @@ describe('Build', function (done) { }); }); - it('should build admin js bundle', function (done) { - build.build(['admin js bundle'], function (err) { + it('should build admin js bundle', (done) => { + build.build(['admin js bundle'], (err) => { assert.ifError(err); var filename = path.join(__dirname, '../build/public/acp.min.js'); assert(file.existsSync(filename)); @@ -167,8 +165,8 @@ describe('Build', function (done) { }); }); - it('should build client side styles', function (done) { - build.build(['client side styles'], function (err) { + it('should build client side styles', (done) => { + build.build(['client side styles'], (err) => { assert.ifError(err); var filename = path.join(__dirname, '../build/public/client.css'); assert(file.existsSync(filename)); @@ -177,8 +175,8 @@ describe('Build', function (done) { }); }); - it('should build admin control panel styles', function (done) { - build.build(['admin control panel styles'], function (err) { + it('should build admin control panel styles', (done) => { + build.build(['admin control panel styles'], (err) => { assert.ifError(err); var filename = path.join(__dirname, '../build/public/admin.css'); assert(file.existsSync(filename)); @@ -194,7 +192,7 @@ describe('Build', function (done) { it('should build templates', function (done) { this.timeout(0); - build.build(['templates'], function (err) { + build.build(['templates'], (err) => { assert.ifError(err); var filename = path.join(__dirname, '../build/public/templates/admin/header.tpl'); assert(file.existsSync(filename)); @@ -203,8 +201,8 @@ describe('Build', function (done) { }); }); - it('should build languages', function (done) { - build.build(['languages'], function (err) { + it('should build languages', (done) => { + build.build(['languages'], (err) => { assert.ifError(err); var globalFile = path.join(__dirname, '../build/public/language/en-GB/global.json'); diff --git a/test/categories.js b/test/categories.js index ae08a7fb51..2dbe70e65c 100644 --- a/test/categories.js +++ b/test/categories.js @@ -13,12 +13,12 @@ var User = require('../src/user'); var groups = require('../src/groups'); var privileges = require('../src/privileges'); -describe('Categories', function () { +describe('Categories', () => { var categoryObj; var posterUid; var adminUid; - before(function (done) { + before((done) => { async.series({ posterUid: function (next) { User.create({ username: 'poster' }, next); @@ -26,7 +26,7 @@ describe('Categories', function () { adminUid: function (next) { User.create({ username: 'admin' }, next); }, - }, function (err, results) { + }, (err, results) => { assert.ifError(err); posterUid = results.posterUid; adminUid = results.adminUid; @@ -35,14 +35,14 @@ describe('Categories', function () { }); - it('should create a new category', function (done) { + it('should create a new category', (done) => { Categories.create({ name: 'Test Category & NodeBB', description: 'Test category created by testing script', icon: 'fa-check', blockclass: 'category-blue', order: '5', - }, function (err, category) { + }, (err, category) => { assert.ifError(err); categoryObj = category; @@ -50,13 +50,13 @@ describe('Categories', function () { }); }); - it('should retrieve a newly created category by its ID', function (done) { + it('should retrieve a newly created category by its ID', (done) => { Categories.getCategoryById({ cid: categoryObj.cid, start: 0, stop: -1, uid: 0, - }, function (err, categoryData) { + }, (err, categoryData) => { assert.ifError(err); assert(categoryData); @@ -67,20 +67,20 @@ describe('Categories', function () { }); }); - it('should return null if category does not exist', function (done) { + it('should return null if category does not exist', (done) => { Categories.getCategoryById({ cid: 123123123, start: 0, stop: -1, - }, function (err, categoryData) { + }, (err, categoryData) => { assert.ifError(err); assert.strictEqual(categoryData, null); done(); }); }); - it('should get all categories', function (done) { - Categories.getAllCategories(1, function (err, data) { + it('should get all categories', (done) => { + Categories.getAllCategories(1, (err, data) => { assert.ifError(err); assert(Array.isArray(data)); assert.equal(data[0].cid, categoryObj.cid); @@ -88,8 +88,8 @@ describe('Categories', function () { }); }); - it('should load a category route', function (done) { - request(`${nconf.get('url')}/api/category/${categoryObj.cid}/test-category`, { json: true }, function (err, response, body) { + it('should load a category route', (done) => { + request(`${nconf.get('url')}/api/category/${categoryObj.cid}/test-category`, { json: true }, (err, response, body) => { assert.ifError(err); assert.equal(response.statusCode, 200); assert.equal(body.name, 'Test Category & NodeBB'); @@ -98,8 +98,8 @@ describe('Categories', function () { }); }); - describe('Categories.getRecentTopicReplies', function () { - it('should not throw', function (done) { + describe('Categories.getRecentTopicReplies', () => { + it('should not throw', (done) => { Categories.getCategoryById({ cid: categoryObj.cid, set: `cid:${categoryObj.cid}:tids`, @@ -107,9 +107,9 @@ describe('Categories', function () { start: 0, stop: -1, uid: 0, - }, function (err, categoryData) { + }, (err, categoryData) => { assert.ifError(err); - Categories.getRecentTopicReplies(categoryData, 0, {}, function (err) { + Categories.getRecentTopicReplies(categoryData, 0, {}, (err) => { assert.ifError(err); done(); }); @@ -117,27 +117,25 @@ describe('Categories', function () { }); }); - describe('.getCategoryTopics', function () { - it('should return a list of topics', function (done) { + describe('.getCategoryTopics', () => { + it('should return a list of topics', (done) => { Categories.getCategoryTopics({ cid: categoryObj.cid, start: 0, stop: 10, uid: 0, sort: 'oldest_to_newest', - }, function (err, result) { + }, (err, result) => { assert.equal(err, null); assert(Array.isArray(result.topics)); - assert(result.topics.every(function (topic) { - return topic instanceof Object; - })); + assert(result.topics.every(topic => topic instanceof Object)); done(); }); }); - it('should return a list of topics by a specific user', function (done) { + it('should return a list of topics by a specific user', (done) => { Categories.getCategoryTopics({ cid: categoryObj.cid, start: 0, @@ -145,22 +143,20 @@ describe('Categories', function () { uid: 0, targetUid: 1, sort: 'oldest_to_newest', - }, function (err, result) { + }, (err, result) => { assert.equal(err, null); assert(Array.isArray(result.topics)); - assert(result.topics.every(function (topic) { - return topic instanceof Object && topic.uid === '1'; - })); + assert(result.topics.every(topic => topic instanceof Object && topic.uid === '1')); done(); }); }); }); - describe('Categories.moveRecentReplies', function () { + describe('Categories.moveRecentReplies', () => { var moveCid; var moveTid; - before(function (done) { + before((done) => { async.parallel({ category: function (next) { Categories.create({ @@ -176,25 +172,25 @@ describe('Categories', function () { content: 'The content of test topic', }, next); }, - }, function (err, results) { + }, (err, results) => { if (err) { return done(err); } moveCid = results.category.cid; moveTid = results.topic.topicData.tid; - Topics.reply({ uid: posterUid, content: 'test post', tid: moveTid }, function (err) { + Topics.reply({ uid: posterUid, content: 'test post', tid: moveTid }, (err) => { done(err); }); }); }); - it('should move posts from one category to another', function (done) { - Categories.moveRecentReplies(moveTid, categoryObj.cid, moveCid, function (err) { + it('should move posts from one category to another', (done) => { + Categories.moveRecentReplies(moveTid, categoryObj.cid, moveCid, (err) => { assert.ifError(err); - db.getSortedSetRange(`cid:${categoryObj.cid}:pids`, 0, -1, function (err, pids) { + db.getSortedSetRange(`cid:${categoryObj.cid}:pids`, 0, -1, (err, pids) => { assert.ifError(err); assert.equal(pids.length, 0); - db.getSortedSetRange(`cid:${moveCid}:pids`, 0, -1, function (err, pids) { + db.getSortedSetRange(`cid:${moveCid}:pids`, 0, -1, (err, pids) => { assert.ifError(err); assert.equal(pids.length, 2); done(); @@ -204,10 +200,10 @@ describe('Categories', function () { }); }); - describe('socket methods', function () { + describe('socket methods', () => { var socketCategories = require('../src/socket.io/categories'); - before(function (done) { + before((done) => { Topics.post({ uid: posterUid, cid: categoryObj.cid, @@ -217,31 +213,31 @@ describe('Categories', function () { }, done); }); - it('should get recent replies in category', function (done) { - socketCategories.getRecentReplies({ uid: posterUid }, categoryObj.cid, function (err, data) { + it('should get recent replies in category', (done) => { + socketCategories.getRecentReplies({ uid: posterUid }, categoryObj.cid, (err, data) => { assert.ifError(err); assert(Array.isArray(data)); done(); }); }); - it('should get categories', function (done) { - socketCategories.get({ uid: posterUid }, {}, function (err, data) { + it('should get categories', (done) => { + socketCategories.get({ uid: posterUid }, {}, (err, data) => { assert.ifError(err); assert(Array.isArray(data)); done(); }); }); - it('should get watched categories', function (done) { - socketCategories.getWatchedCategories({ uid: posterUid }, {}, function (err, data) { + it('should get watched categories', (done) => { + socketCategories.getWatchedCategories({ uid: posterUid }, {}, (err, data) => { assert.ifError(err); assert(Array.isArray(data)); done(); }); }); - it('should load more topics', function (done) { + it('should load more topics', (done) => { socketCategories.loadMore({ uid: posterUid }, { cid: categoryObj.cid, after: 0, @@ -249,7 +245,7 @@ describe('Categories', function () { author: 'poster', tag: 'nodebb', }, - }, function (err, data) { + }, (err, data) => { assert.ifError(err); assert(Array.isArray(data.topics)); assert.equal(data.topics[0].user.username, 'poster'); @@ -259,37 +255,37 @@ describe('Categories', function () { }); }); - it('should load topic count', function (done) { - socketCategories.getTopicCount({ uid: posterUid }, categoryObj.cid, function (err, topicCount) { + it('should load topic count', (done) => { + socketCategories.getTopicCount({ uid: posterUid }, categoryObj.cid, (err, topicCount) => { assert.ifError(err); assert.equal(topicCount, 2); done(); }); }); - it('should load category by privilege', function (done) { - socketCategories.getCategoriesByPrivilege({ uid: posterUid }, 'find', function (err, data) { + it('should load category by privilege', (done) => { + socketCategories.getCategoriesByPrivilege({ uid: posterUid }, 'find', (err, data) => { assert.ifError(err); assert(Array.isArray(data)); done(); }); }); - it('should get move categories', function (done) { - socketCategories.getMoveCategories({ uid: posterUid }, {}, function (err, data) { + it('should get move categories', (done) => { + socketCategories.getMoveCategories({ uid: posterUid }, {}, (err, data) => { assert.ifError(err); assert(Array.isArray(data)); done(); }); }); - it('should ignore category', function (done) { - socketCategories.ignore({ uid: posterUid }, { cid: categoryObj.cid }, function (err) { + it('should ignore category', (done) => { + socketCategories.ignore({ uid: posterUid }, { cid: categoryObj.cid }, (err) => { assert.ifError(err); - Categories.isIgnored([categoryObj.cid], posterUid, function (err, isIgnored) { + Categories.isIgnored([categoryObj.cid], posterUid, (err, isIgnored) => { assert.ifError(err); assert.equal(isIgnored[0], true); - Categories.getIgnorers(categoryObj.cid, 0, -1, function (err, ignorers) { + Categories.getIgnorers(categoryObj.cid, 0, -1, (err, ignorers) => { assert.ifError(err); assert.deepEqual(ignorers, [posterUid]); done(); @@ -298,10 +294,10 @@ describe('Categories', function () { }); }); - it('should watch category', function (done) { - socketCategories.watch({ uid: posterUid }, { cid: categoryObj.cid }, function (err) { + it('should watch category', (done) => { + socketCategories.watch({ uid: posterUid }, { cid: categoryObj.cid }, (err) => { assert.ifError(err); - Categories.isIgnored([categoryObj.cid], posterUid, function (err, isIgnored) { + Categories.isIgnored([categoryObj.cid], posterUid, (err, isIgnored) => { assert.ifError(err); assert.equal(isIgnored[0], false); done(); @@ -309,23 +305,23 @@ describe('Categories', function () { }); }); - it('should error if watch state does not exist', function (done) { - socketCategories.setWatchState({ uid: posterUid }, { cid: categoryObj.cid, state: 'invalid-state' }, function (err) { + it('should error if watch state does not exist', (done) => { + socketCategories.setWatchState({ uid: posterUid }, { cid: categoryObj.cid, state: 'invalid-state' }, (err) => { assert.equal(err.message, '[[error:invalid-watch-state]]'); done(); }); }); - it('should check if user is moderator', function (done) { - socketCategories.isModerator({ uid: posterUid }, {}, function (err, isModerator) { + it('should check if user is moderator', (done) => { + socketCategories.isModerator({ uid: posterUid }, {}, (err, isModerator) => { assert.ifError(err); assert(!isModerator); done(); }); }); - it('should get category data', function (done) { - socketCategories.getCategory({ uid: posterUid }, categoryObj.cid, function (err, data) { + it('should get category data', (done) => { + socketCategories.getCategory({ uid: posterUid }, categoryObj.cid, (err, data) => { assert.ifError(err); assert.equal(categoryObj.cid, data.cid); done(); @@ -333,17 +329,17 @@ describe('Categories', function () { }); }); - describe('admin socket methods', function () { + describe('admin socket methods', () => { var socketCategories = require('../src/socket.io/admin/categories'); var cid; - before(function (done) { + before((done) => { socketCategories.create({ uid: adminUid }, { name: 'update name', description: 'update description', parentCid: categoryObj.cid, icon: 'fa-check', order: '5', - }, function (err, category) { + }, (err, category) => { assert.ifError(err); cid = category.cid; @@ -351,25 +347,25 @@ describe('Categories', function () { }); }); - it('should return error with invalid data', function (done) { - socketCategories.update({ uid: adminUid }, null, function (err) { + it('should return error with invalid data', (done) => { + socketCategories.update({ uid: adminUid }, null, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); }); - it('should error if you try to set parent as self', function (done) { + it('should error if you try to set parent as self', (done) => { var updateData = {}; updateData[cid] = { parentCid: cid, }; - socketCategories.update({ uid: adminUid }, updateData, function (err) { + socketCategories.update({ uid: adminUid }, updateData, (err) => { assert.equal(err.message, '[[error:cant-set-self-as-parent]]'); done(); }); }); - it('should error if you try to set child as parent', function (done) { + it('should error if you try to set child as parent', (done) => { var child1Cid; var parentCid; async.waterfall([ @@ -386,7 +382,7 @@ describe('Categories', function () { updateData[parentCid] = { parentCid: child1Cid, }; - socketCategories.update({ uid: adminUid }, updateData, function (err) { + socketCategories.update({ uid: adminUid }, updateData, (err) => { assert.equal(err.message, '[[error:cant-set-child-as-parent]]'); next(); }); @@ -394,7 +390,7 @@ describe('Categories', function () { ], done); }); - it('should update category data', function (done) { + it('should update category data', (done) => { var updateData = {}; updateData[cid] = { name: 'new name', @@ -403,9 +399,9 @@ describe('Categories', function () { order: 3, icon: 'fa-hammer', }; - socketCategories.update({ uid: adminUid }, updateData, function (err) { + socketCategories.update({ uid: adminUid }, updateData, (err) => { assert.ifError(err); - Categories.getCategoryData(cid, function (err, data) { + Categories.getCategoryData(cid, (err, data) => { assert.ifError(err); assert.equal(data.name, updateData[cid].name); assert.equal(data.description, updateData[cid].description); @@ -417,20 +413,20 @@ describe('Categories', function () { }); }); - it('should purge category', function (done) { + it('should purge category', (done) => { Categories.create({ name: 'purge me', description: 'update description', - }, function (err, category) { + }, (err, category) => { assert.ifError(err); Topics.post({ uid: posterUid, cid: category.cid, title: 'Test Topic Title', content: 'The content of test topic', - }, function (err) { + }, (err) => { assert.ifError(err); - socketCategories.purge({ uid: adminUid }, category.cid, function (err) { + socketCategories.purge({ uid: adminUid }, category.cid, (err) => { assert.ifError(err); done(); }); @@ -438,26 +434,26 @@ describe('Categories', function () { }); }); - it('should get all categories', function (done) { - socketCategories.getAll({ uid: adminUid }, {}, function (err, data) { + it('should get all categories', (done) => { + socketCategories.getAll({ uid: adminUid }, {}, (err, data) => { assert.ifError(err); assert(data); done(); }); }); - it('should get all category names', function (done) { - socketCategories.getNames({ uid: adminUid }, {}, function (err, data) { + it('should get all category names', (done) => { + socketCategories.getNames({ uid: adminUid }, {}, (err, data) => { assert.ifError(err); assert(Array.isArray(data)); done(); }); }); - it('should give privilege', function (done) { - socketCategories.setPrivilege({ uid: adminUid }, { cid: categoryObj.cid, privilege: ['groups:topics:delete'], set: true, member: 'registered-users' }, function (err) { + it('should give privilege', (done) => { + socketCategories.setPrivilege({ uid: adminUid }, { cid: categoryObj.cid, privilege: ['groups:topics:delete'], set: true, member: 'registered-users' }, (err) => { assert.ifError(err); - privileges.categories.can('topics:delete', categoryObj.cid, posterUid, function (err, canDeleteTopcis) { + privileges.categories.can('topics:delete', categoryObj.cid, posterUid, (err, canDeleteTopcis) => { assert.ifError(err); assert(canDeleteTopcis); done(); @@ -465,10 +461,10 @@ describe('Categories', function () { }); }); - it('should remove privilege', function (done) { - socketCategories.setPrivilege({ uid: adminUid }, { cid: categoryObj.cid, privilege: 'groups:topics:delete', set: false, member: 'registered-users' }, function (err) { + it('should remove privilege', (done) => { + socketCategories.setPrivilege({ uid: adminUid }, { cid: categoryObj.cid, privilege: 'groups:topics:delete', set: false, member: 'registered-users' }, (err) => { assert.ifError(err); - privileges.categories.can('topics:delete', categoryObj.cid, posterUid, function (err, canDeleteTopcis) { + privileges.categories.can('topics:delete', categoryObj.cid, posterUid, (err, canDeleteTopcis) => { assert.ifError(err); assert(!canDeleteTopcis); done(); @@ -476,15 +472,15 @@ describe('Categories', function () { }); }); - it('should get privilege settings', function (done) { - socketCategories.getPrivilegeSettings({ uid: adminUid }, categoryObj.cid, function (err, data) { + it('should get privilege settings', (done) => { + socketCategories.getPrivilegeSettings({ uid: adminUid }, categoryObj.cid, (err, data) => { assert.ifError(err); assert(data); done(); }); }); - it('should copy privileges to children', function (done) { + it('should copy privileges to children', (done) => { var parentCid; var child1Cid; var child2Cid; @@ -517,7 +513,7 @@ describe('Categories', function () { ], done); }); - it('should create category with settings from', function (done) { + it('should create category with settings from', (done) => { var child1Cid; var parentCid; async.waterfall([ @@ -536,7 +532,7 @@ describe('Categories', function () { ], done); }); - it('should copy settings from', function (done) { + it('should copy settings from', (done) => { var child1Cid; var parentCid; async.waterfall([ @@ -561,7 +557,7 @@ describe('Categories', function () { ], done); }); - it('should copy privileges from another category', function (done) { + it('should copy privileges from another category', (done) => { var child1Cid; var parentCid; async.waterfall([ @@ -589,7 +585,7 @@ describe('Categories', function () { ], done); }); - it('should copy privileges from another category for a single group', function (done) { + it('should copy privileges from another category for a single group', (done) => { var child1Cid; var parentCid; async.waterfall([ @@ -618,19 +614,19 @@ describe('Categories', function () { }); }); - it('should get active users', function (done) { + it('should get active users', (done) => { Categories.create({ name: 'test', - }, function (err, category) { + }, (err, category) => { assert.ifError(err); Topics.post({ uid: posterUid, cid: category.cid, title: 'Test Topic Title', content: 'The content of test topic', - }, function (err) { + }, (err) => { assert.ifError(err); - Categories.getActiveUsers(category.cid, function (err, uids) { + Categories.getActiveUsers(category.cid, (err, uids) => { assert.ifError(err); assert.equal(uids[0], posterUid); done(); @@ -639,42 +635,42 @@ describe('Categories', function () { }); }); - describe('tag whitelist', function () { + describe('tag whitelist', () => { var cid; var socketTopics = require('../src/socket.io/topics'); - before(function (done) { + before((done) => { Categories.create({ name: 'test', - }, function (err, category) { + }, (err, category) => { assert.ifError(err); cid = category.cid; done(); }); }); - it('should error if data is invalid', function (done) { - socketTopics.isTagAllowed({ uid: posterUid }, null, function (err) { + it('should error if data is invalid', (done) => { + socketTopics.isTagAllowed({ uid: posterUid }, null, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); }); - it('should return true if category whitelist is empty', function (done) { - socketTopics.isTagAllowed({ uid: posterUid }, { tag: 'notallowed', cid: cid }, function (err, allowed) { + it('should return true if category whitelist is empty', (done) => { + socketTopics.isTagAllowed({ uid: posterUid }, { tag: 'notallowed', cid: cid }, (err, allowed) => { assert.ifError(err); assert(allowed); done(); }); }); - it('should add tags to category whitelist', function (done) { + it('should add tags to category whitelist', (done) => { var data = {}; data[cid] = { tagWhitelist: 'nodebb,jquery,javascript', }; - Categories.update(data, function (err) { + Categories.update(data, (err) => { assert.ifError(err); - db.getSortedSetRange(`cid:${cid}:tag:whitelist`, 0, -1, function (err, tagWhitelist) { + db.getSortedSetRange(`cid:${cid}:tag:whitelist`, 0, -1, (err, tagWhitelist) => { assert.ifError(err); assert.deepEqual(['nodebb', 'jquery', 'javascript'], tagWhitelist); done(); @@ -682,30 +678,30 @@ describe('Categories', function () { }); }); - it('should return false if category whitelist does not have tag', function (done) { - socketTopics.isTagAllowed({ uid: posterUid }, { tag: 'notallowed', cid: cid }, function (err, allowed) { + it('should return false if category whitelist does not have tag', (done) => { + socketTopics.isTagAllowed({ uid: posterUid }, { tag: 'notallowed', cid: cid }, (err, allowed) => { assert.ifError(err); assert(!allowed); done(); }); }); - it('should return true if category whitelist has tag', function (done) { - socketTopics.isTagAllowed({ uid: posterUid }, { tag: 'nodebb', cid: cid }, function (err, allowed) { + it('should return true if category whitelist has tag', (done) => { + socketTopics.isTagAllowed({ uid: posterUid }, { tag: 'nodebb', cid: cid }, (err, allowed) => { assert.ifError(err); assert(allowed); done(); }); }); - it('should post a topic with only allowed tags', function (done) { + it('should post a topic with only allowed tags', (done) => { Topics.post({ uid: posterUid, cid: cid, title: 'Test Topic Title', content: 'The content of test topic', tags: ['nodebb', 'jquery', 'notallowed'], - }, function (err, data) { + }, (err, data) => { assert.ifError(err); assert.equal(data.topicData.tags.length, 2); done(); @@ -714,27 +710,27 @@ describe('Categories', function () { }); - describe('privileges', function () { + describe('privileges', () => { var privileges = require('../src/privileges'); - it('should return empty array if uids is empty array', function (done) { - privileges.categories.filterUids('find', categoryObj.cid, [], function (err, uids) { + it('should return empty array if uids is empty array', (done) => { + privileges.categories.filterUids('find', categoryObj.cid, [], (err, uids) => { assert.ifError(err); assert.equal(uids.length, 0); done(); }); }); - it('should filter uids by privilege', function (done) { - privileges.categories.filterUids('find', categoryObj.cid, [1, 2, 3, 4], function (err, uids) { + it('should filter uids by privilege', (done) => { + privileges.categories.filterUids('find', categoryObj.cid, [1, 2, 3, 4], (err, uids) => { assert.ifError(err); assert.deepEqual(uids, [1, 2]); done(); }); }); - it('should load category user privileges', function (done) { - privileges.categories.userPrivileges(categoryObj.cid, 1, function (err, data) { + it('should load category user privileges', (done) => { + privileges.categories.userPrivileges(categoryObj.cid, 1, (err, data) => { assert.ifError(err); assert.deepEqual(data, { find: false, @@ -758,8 +754,8 @@ describe('Categories', function () { }); }); - it('should load global user privileges', function (done) { - privileges.global.userPrivileges(1, function (err, data) { + it('should load global user privileges', (done) => { + privileges.global.userPrivileges(1, (err, data) => { assert.ifError(err); assert.deepEqual(data, { ban: false, @@ -783,8 +779,8 @@ describe('Categories', function () { }); }); - it('should load category group privileges', function (done) { - privileges.categories.groupPrivileges(categoryObj.cid, 'registered-users', function (err, data) { + it('should load category group privileges', (done) => { + privileges.categories.groupPrivileges(categoryObj.cid, 'registered-users', (err, data) => { assert.ifError(err); assert.deepEqual(data, { 'groups:find': true, @@ -808,8 +804,8 @@ describe('Categories', function () { }); }); - it('should load global group privileges', function (done) { - privileges.global.groupPrivileges('registered-users', function (err, data) { + it('should load global group privileges', (done) => { + privileges.global.groupPrivileges('registered-users', (err, data) => { assert.ifError(err); assert.deepEqual(data, { 'groups:ban': false, @@ -833,16 +829,16 @@ describe('Categories', function () { }); }); - it('should return false if cid is falsy', function (done) { - privileges.categories.isUserAllowedTo('find', null, adminUid, function (err, isAllowed) { + it('should return false if cid is falsy', (done) => { + privileges.categories.isUserAllowedTo('find', null, adminUid, (err, isAllowed) => { assert.ifError(err); assert.equal(isAllowed, false); done(); }); }); - describe('Categories.getModeratorUids', function () { - before(function (done) { + describe('Categories.getModeratorUids', () => { + before((done) => { async.series([ async.apply(groups.create, { name: 'testGroup' }), async.apply(groups.join, 'cid:1:privileges:groups:moderate', 'testGroup'), @@ -850,8 +846,8 @@ describe('Categories', function () { ], done); }); - it('should retrieve all users with moderator bit in category privilege', function (done) { - Categories.getModeratorUids([1, 2], function (err, uids) { + it('should retrieve all users with moderator bit in category privilege', (done) => { + Categories.getModeratorUids([1, 2], (err, uids) => { assert.ifError(err); assert.strictEqual(uids.length, 2); assert(uids[0].includes('1')); @@ -860,13 +856,13 @@ describe('Categories', function () { }); }); - it('should not fail when there are multiple groups', function (done) { + it('should not fail when there are multiple groups', (done) => { async.series([ async.apply(groups.create, { name: 'testGroup2' }), async.apply(groups.join, 'cid:1:privileges:groups:moderate', 'testGroup2'), async.apply(groups.join, 'testGroup2', 1), function (next) { - Categories.getModeratorUids([1, 2], function (err, uids) { + Categories.getModeratorUids([1, 2], (err, uids) => { assert.ifError(err); assert(uids[0].includes('1')); next(); @@ -875,7 +871,7 @@ describe('Categories', function () { ], done); }); - after(function (done) { + after((done) => { async.series([ async.apply(groups.leave, 'cid:1:privileges:groups:moderate', 'testGroup'), async.apply(groups.leave, 'cid:1:privileges:groups:moderate', 'testGroup2'), @@ -887,9 +883,9 @@ describe('Categories', function () { }); - describe('getTopicIds', function () { + describe('getTopicIds', () => { var plugins = require('../src/plugins'); - it('should get topic ids with filter', function (done) { + it('should get topic ids with filter', (done) => { function method(data, callback) { data.tids = [1, 2, 3]; callback(null, data); @@ -904,7 +900,7 @@ describe('Categories', function () { cid: categoryObj.cid, start: 0, stop: 19, - }, function (err, tids) { + }, (err, tids) => { assert.ifError(err); assert.deepEqual(tids, [1, 2, 3]); plugins.hooks.unregister('my-test-plugin', 'filter:categories.getTopicIds', method); @@ -913,7 +909,7 @@ describe('Categories', function () { }); }); - it('should return nested children categories', async function () { + it('should return nested children categories', async () => { const rootCategory = await Categories.create({ name: 'root' }); const child1 = await Categories.create({ name: 'child1', parentCid: rootCategory.cid }); const child2 = await Categories.create({ name: 'child2', parentCid: child1.cid }); diff --git a/test/controllers-admin.js b/test/controllers-admin.js index 2559fbf21e..61eec1529c 100644 --- a/test/controllers-admin.js +++ b/test/controllers-admin.js @@ -13,7 +13,7 @@ var groups = require('../src/groups'); var helpers = require('./helpers'); var meta = require('../src/meta'); -describe('Admin Controllers', function () { +describe('Admin Controllers', () => { var tid; var cid; var pid; @@ -24,7 +24,7 @@ describe('Admin Controllers', function () { var moderatorUid; var jar; - before(function (done) { + before((done) => { async.series({ category: function (next) { categories.create({ @@ -44,7 +44,7 @@ describe('Admin Controllers', function () { moderatorUid: function (next) { user.create({ username: 'moderator', password: 'modmod' }, next); }, - }, async function (err, results) { + }, async (err, results) => { if (err) { return done(err); } @@ -65,11 +65,11 @@ describe('Admin Controllers', function () { }); }); - it('should 403 if user is not admin', function (done) { - helpers.loginUser('admin', 'barbar', function (err, _jar) { + it('should 403 if user is not admin', (done) => { + helpers.loginUser('admin', 'barbar', (err, _jar) => { assert.ifError(err); jar = _jar; - request(`${nconf.get('url')}/admin`, { jar: jar }, function (err, res, body) { + request(`${nconf.get('url')}/admin`, { jar: jar }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 403); assert(body); @@ -78,10 +78,10 @@ describe('Admin Controllers', function () { }); }); - it('should load admin dashboard', function (done) { - groups.join('administrators', adminUid, function (err) { + it('should load admin dashboard', (done) => { + groups.join('administrators', adminUid, (err) => { assert.ifError(err); - request(`${nconf.get('url')}/admin`, { jar: jar }, function (err, res, body) { + request(`${nconf.get('url')}/admin`, { jar: jar }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -90,8 +90,8 @@ describe('Admin Controllers', function () { }); }); - it('should load groups page', function (done) { - request(`${nconf.get('url')}/admin/manage/groups`, { jar: jar }, function (err, res, body) { + it('should load groups page', (done) => { + request(`${nconf.get('url')}/admin/manage/groups`, { jar: jar }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -99,8 +99,8 @@ describe('Admin Controllers', function () { }); }); - it('should load groups detail page', function (done) { - request(`${nconf.get('url')}/admin/manage/groups/administrators`, { jar: jar }, function (err, res, body) { + it('should load groups detail page', (done) => { + request(`${nconf.get('url')}/admin/manage/groups/administrators`, { jar: jar }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -108,8 +108,8 @@ describe('Admin Controllers', function () { }); }); - it('should load global privileges page', function (done) { - request(`${nconf.get('url')}/admin/manage/privileges`, { jar: jar }, function (err, res, body) { + it('should load global privileges page', (done) => { + request(`${nconf.get('url')}/admin/manage/privileges`, { jar: jar }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -117,8 +117,8 @@ describe('Admin Controllers', function () { }); }); - it('should load privileges page for category 1', function (done) { - request(`${nconf.get('url')}/admin/manage/privileges/1`, { jar: jar }, function (err, res, body) { + it('should load privileges page for category 1', (done) => { + request(`${nconf.get('url')}/admin/manage/privileges/1`, { jar: jar }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -126,8 +126,8 @@ describe('Admin Controllers', function () { }); }); - it('should load manage uploads', function (done) { - request(`${nconf.get('url')}/admin/manage/uploads`, { jar: jar }, function (err, res, body) { + it('should load manage uploads', (done) => { + request(`${nconf.get('url')}/admin/manage/uploads`, { jar: jar }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -135,8 +135,8 @@ describe('Admin Controllers', function () { }); }); - it('should load general settings page', function (done) { - request(`${nconf.get('url')}/admin/settings`, { jar: jar }, function (err, res, body) { + it('should load general settings page', (done) => { + request(`${nconf.get('url')}/admin/settings`, { jar: jar }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -144,8 +144,8 @@ describe('Admin Controllers', function () { }); }); - it('should load email settings page', function (done) { - request(`${nconf.get('url')}/admin/settings/email`, { jar: jar }, function (err, res, body) { + it('should load email settings page', (done) => { + request(`${nconf.get('url')}/admin/settings/email`, { jar: jar }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -153,8 +153,8 @@ describe('Admin Controllers', function () { }); }); - it('should load user settings page', function (done) { - request(`${nconf.get('url')}/admin/settings/user`, { jar: jar }, function (err, res, body) { + it('should load user settings page', (done) => { + request(`${nconf.get('url')}/admin/settings/user`, { jar: jar }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -162,8 +162,8 @@ describe('Admin Controllers', function () { }); }); - it('should load info page for a user', function (done) { - request(`${nconf.get('url')}/api/user/regular/info`, { jar: jar, json: true }, function (err, res, body) { + it('should load info page for a user', (done) => { + request(`${nconf.get('url')}/api/user/regular/info`, { jar: jar, json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body.history); @@ -174,16 +174,16 @@ describe('Admin Controllers', function () { }); }); - it('should 404 for edit/email page if user does not exist', function (done) { - request(`${nconf.get('url')}/api/user/doesnotexist/edit/email`, { jar: jar, json: true }, function (err, res) { + it('should 404 for edit/email page if user does not exist', (done) => { + request(`${nconf.get('url')}/api/user/doesnotexist/edit/email`, { jar: jar, json: true }, (err, res) => { assert.ifError(err); assert.equal(res.statusCode, 404); done(); }); }); - it('should load /admin/settings/homepage', function (done) { - request(`${nconf.get('url')}/api/admin/settings/homepage`, { jar: jar, json: true }, function (err, res, body) { + it('should load /admin/settings/homepage', (done) => { + request(`${nconf.get('url')}/api/admin/settings/homepage`, { jar: jar, json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body.routes); @@ -191,8 +191,8 @@ describe('Admin Controllers', function () { }); }); - it('should load /admin/advanced/database', function (done) { - request(`${nconf.get('url')}/api/admin/advanced/database`, { jar: jar, json: true }, function (err, res, body) { + it('should load /admin/advanced/database', (done) => { + request(`${nconf.get('url')}/api/admin/advanced/database`, { jar: jar, json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); @@ -207,8 +207,8 @@ describe('Admin Controllers', function () { }); }); - it('should load /admin/extend/plugins', function (done) { - request(`${nconf.get('url')}/api/admin/extend/plugins`, { jar: jar, json: true }, function (err, res, body) { + it('should load /admin/extend/plugins', (done) => { + request(`${nconf.get('url')}/api/admin/extend/plugins`, { jar: jar, json: true }, (err, res, body) => { assert.ifError(err); assert(body.hasOwnProperty('installed')); assert(body.hasOwnProperty('upgradeCount')); @@ -218,8 +218,8 @@ describe('Admin Controllers', function () { }); }); - it('should load /admin/manage/users', function (done) { - request(`${nconf.get('url')}/api/admin/manage/users`, { jar: jar, json: true }, function (err, res, body) { + it('should load /admin/manage/users', (done) => { + request(`${nconf.get('url')}/api/admin/manage/users`, { jar: jar, json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -227,8 +227,8 @@ describe('Admin Controllers', function () { }); }); - it('should load /admin/manage/registration', function (done) { - request(`${nconf.get('url')}/api/admin/manage/registration`, { jar: jar, json: true }, function (err, res, body) { + it('should load /admin/manage/registration', (done) => { + request(`${nconf.get('url')}/api/admin/manage/registration`, { jar: jar, json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -236,8 +236,8 @@ describe('Admin Controllers', function () { }); }); - it('should 404 if users is not privileged', function (done) { - request(`${nconf.get('url')}/api/registration-queue`, { json: true }, function (err, res, body) { + it('should 404 if users is not privileged', (done) => { + request(`${nconf.get('url')}/api/registration-queue`, { json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 404); assert(body); @@ -245,8 +245,8 @@ describe('Admin Controllers', function () { }); }); - it('should load /api/registration-queue', function (done) { - request(`${nconf.get('url')}/api/registration-queue`, { jar: jar, json: true }, function (err, res, body) { + it('should load /api/registration-queue', (done) => { + request(`${nconf.get('url')}/api/registration-queue`, { jar: jar, json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -254,8 +254,8 @@ describe('Admin Controllers', function () { }); }); - it('should load /admin/manage/admins-mods', function (done) { - request(`${nconf.get('url')}/api/admin/manage/admins-mods`, { jar: jar, json: true }, function (err, res, body) { + it('should load /admin/manage/admins-mods', (done) => { + request(`${nconf.get('url')}/api/admin/manage/admins-mods`, { jar: jar, json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -263,17 +263,17 @@ describe('Admin Controllers', function () { }); }); - it('should load /admin/users/csv', function (done) { + it('should load /admin/users/csv', (done) => { const socketAdmin = require('../src/socket.io/admin'); - socketAdmin.user.exportUsersCSV({ uid: adminUid }, {}, function (err) { + socketAdmin.user.exportUsersCSV({ uid: adminUid }, {}, (err) => { assert.ifError(err); - setTimeout(function () { + setTimeout(() => { request(`${nconf.get('url')}/api/admin/users/csv`, { jar: jar, headers: { referer: `${nconf.get('url')}/admin/manage/users`, }, - }, function (err, res, body) { + }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -283,8 +283,8 @@ describe('Admin Controllers', function () { }); }); - it('should return 403 if no referer', function (done) { - request(`${nconf.get('url')}/api/admin/groups/administrators/csv`, { jar: jar }, function (err, res, body) { + it('should return 403 if no referer', (done) => { + request(`${nconf.get('url')}/api/admin/groups/administrators/csv`, { jar: jar }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 403); assert.equal(body, '[[error:invalid-origin]]'); @@ -292,13 +292,13 @@ describe('Admin Controllers', function () { }); }); - it('should return 403 if referer is not /api/admin/groups/administrators/csv', function (done) { + it('should return 403 if referer is not /api/admin/groups/administrators/csv', (done) => { request(`${nconf.get('url')}/api/admin/groups/administrators/csv`, { jar: jar, headers: { referer: '/topic/1/test', }, - }, function (err, res, body) { + }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 403); assert.equal(body, '[[error:invalid-origin]]'); @@ -306,13 +306,13 @@ describe('Admin Controllers', function () { }); }); - it('should load /api/admin/groups/administrators/csv', function (done) { + it('should load /api/admin/groups/administrators/csv', (done) => { request(`${nconf.get('url')}/api/admin/groups/administrators/csv`, { jar: jar, headers: { referer: `${nconf.get('url')}/admin/manage/groups`, }, - }, function (err, res, body) { + }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -320,8 +320,8 @@ describe('Admin Controllers', function () { }); }); - it('should load /admin/advanced/hooks', function (done) { - request(`${nconf.get('url')}/api/admin/advanced/hooks`, { jar: jar, json: true }, function (err, res, body) { + it('should load /admin/advanced/hooks', (done) => { + request(`${nconf.get('url')}/api/admin/advanced/hooks`, { jar: jar, json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -329,8 +329,8 @@ describe('Admin Controllers', function () { }); }); - it('should load /admin/advanced/cache', function (done) { - request(`${nconf.get('url')}/api/admin/advanced/cache`, { jar: jar, json: true }, function (err, res, body) { + it('should load /admin/advanced/cache', (done) => { + request(`${nconf.get('url')}/api/admin/advanced/cache`, { jar: jar, json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -338,8 +338,8 @@ describe('Admin Controllers', function () { }); }); - it('should load /admin/advanced/errors', function (done) { - request(`${nconf.get('url')}/api/admin/advanced/errors`, { jar: jar, json: true }, function (err, res, body) { + it('should load /admin/advanced/errors', (done) => { + request(`${nconf.get('url')}/api/admin/advanced/errors`, { jar: jar, json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -347,10 +347,10 @@ describe('Admin Controllers', function () { }); }); - it('should load /admin/advanced/errors/export', function (done) { - meta.errors.clear(function (err) { + it('should load /admin/advanced/errors/export', (done) => { + meta.errors.clear((err) => { assert.ifError(err); - request(`${nconf.get('url')}/api/admin/advanced/errors/export`, { jar: jar }, function (err, res, body) { + request(`${nconf.get('url')}/api/admin/advanced/errors/export`, { jar: jar }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert.strictEqual(body, ''); @@ -359,11 +359,11 @@ describe('Admin Controllers', function () { }); }); - it('should load /admin/advanced/logs', function (done) { + it('should load /admin/advanced/logs', (done) => { var fs = require('fs'); - fs.appendFile(meta.logs.path, 'dummy log', function (err) { + fs.appendFile(meta.logs.path, 'dummy log', (err) => { assert.ifError(err); - request(`${nconf.get('url')}/api/admin/advanced/logs`, { jar: jar, json: true }, function (err, res, body) { + request(`${nconf.get('url')}/api/admin/advanced/logs`, { jar: jar, json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -372,13 +372,13 @@ describe('Admin Controllers', function () { }); }); - it('should load /admin/settings/navigation', function (done) { + it('should load /admin/settings/navigation', (done) => { var navigation = require('../src/navigation/admin'); var data = require('../install/data/navigation.json'); - navigation.save(data, function (err) { + navigation.save(data, (err) => { assert.ifError(err); - request(`${nconf.get('url')}/api/admin/settings/navigation`, { jar: jar, json: true }, function (err, res, body) { + request(`${nconf.get('url')}/api/admin/settings/navigation`, { jar: jar, json: true }, (err, res, body) => { assert.ifError(err); assert(body); assert(body.available); @@ -388,8 +388,8 @@ describe('Admin Controllers', function () { }); }); - it('should load /admin/development/info', function (done) { - request(`${nconf.get('url')}/api/admin/development/info`, { jar: jar, json: true }, function (err, res, body) { + it('should load /admin/development/info', (done) => { + request(`${nconf.get('url')}/api/admin/development/info`, { jar: jar, json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -397,8 +397,8 @@ describe('Admin Controllers', function () { }); }); - it('should load /admin/development/logger', function (done) { - request(`${nconf.get('url')}/api/admin/development/logger`, { jar: jar, json: true }, function (err, res, body) { + it('should load /admin/development/logger', (done) => { + request(`${nconf.get('url')}/api/admin/development/logger`, { jar: jar, json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -406,8 +406,8 @@ describe('Admin Controllers', function () { }); }); - it('should load /admin/advanced/events', function (done) { - request(`${nconf.get('url')}/api/admin/advanced/events`, { jar: jar, json: true }, function (err, res, body) { + it('should load /admin/advanced/events', (done) => { + request(`${nconf.get('url')}/api/admin/advanced/events`, { jar: jar, json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -415,8 +415,8 @@ describe('Admin Controllers', function () { }); }); - it('should load /admin/manage/categories', function (done) { - request(`${nconf.get('url')}/api/admin/manage/categories`, { jar: jar, json: true }, function (err, res, body) { + it('should load /admin/manage/categories', (done) => { + request(`${nconf.get('url')}/api/admin/manage/categories`, { jar: jar, json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -424,8 +424,8 @@ describe('Admin Controllers', function () { }); }); - it('should load /admin/manage/categories/1', function (done) { - request(`${nconf.get('url')}/api/admin/manage/categories/1`, { jar: jar, json: true }, function (err, res, body) { + it('should load /admin/manage/categories/1', (done) => { + request(`${nconf.get('url')}/api/admin/manage/categories/1`, { jar: jar, json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -433,8 +433,8 @@ describe('Admin Controllers', function () { }); }); - it('should load /admin/manage/categories/1/analytics', function (done) { - request(`${nconf.get('url')}/api/admin/manage/categories/1/analytics`, { jar: jar, json: true }, function (err, res, body) { + it('should load /admin/manage/categories/1/analytics', (done) => { + request(`${nconf.get('url')}/api/admin/manage/categories/1/analytics`, { jar: jar, json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -442,8 +442,8 @@ describe('Admin Controllers', function () { }); }); - it('should load /admin/extend/rewards', function (done) { - request(`${nconf.get('url')}/api/admin/extend/rewards`, { jar: jar, json: true }, function (err, res, body) { + it('should load /admin/extend/rewards', (done) => { + request(`${nconf.get('url')}/api/admin/extend/rewards`, { jar: jar, json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -451,8 +451,8 @@ describe('Admin Controllers', function () { }); }); - it('should load /admin/extend/widgets', function (done) { - request(`${nconf.get('url')}/api/admin/extend/widgets`, { jar: jar, json: true }, function (err, res, body) { + it('should load /admin/extend/widgets', (done) => { + request(`${nconf.get('url')}/api/admin/extend/widgets`, { jar: jar, json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -460,8 +460,8 @@ describe('Admin Controllers', function () { }); }); - it('should load /admin/settings/languages', function (done) { - request(`${nconf.get('url')}/api/admin/settings/languages`, { jar: jar, json: true }, function (err, res, body) { + it('should load /admin/settings/languages', (done) => { + request(`${nconf.get('url')}/api/admin/settings/languages`, { jar: jar, json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -469,16 +469,14 @@ describe('Admin Controllers', function () { }); }); - it('should load /admin/settings/social', function (done) { + it('should load /admin/settings/social', (done) => { var socketAdmin = require('../src/socket.io/admin'); - socketAdmin.social.savePostSharingNetworks({ uid: adminUid }, ['facebook', 'twitter'], function (err) { + socketAdmin.social.savePostSharingNetworks({ uid: adminUid }, ['facebook', 'twitter'], (err) => { assert.ifError(err); - request(`${nconf.get('url')}/api/admin/settings/social`, { jar: jar, json: true }, function (err, res, body) { + request(`${nconf.get('url')}/api/admin/settings/social`, { jar: jar, json: true }, (err, res, body) => { assert.ifError(err); assert(body); - body = body.posts.map(function (network) { - return network && network.id; - }); + body = body.posts.map(network => network && network.id); assert(body.includes('facebook')); assert(body.includes('twitter')); done(); @@ -486,8 +484,8 @@ describe('Admin Controllers', function () { }); }); - it('should load /admin/manage/tags', function (done) { - request(`${nconf.get('url')}/api/admin/manage/tags`, { jar: jar, json: true }, function (err, res, body) { + it('should load /admin/manage/tags', (done) => { + request(`${nconf.get('url')}/api/admin/manage/tags`, { jar: jar, json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -495,8 +493,8 @@ describe('Admin Controllers', function () { }); }); - it('/post-queue should 404 for regular user', function (done) { - request(`${nconf.get('url')}/api/post-queue`, { json: true }, function (err, res, body) { + it('/post-queue should 404 for regular user', (done) => { + request(`${nconf.get('url')}/api/post-queue`, { json: true }, (err, res, body) => { assert.ifError(err); assert(body); assert.equal(res.statusCode, 404); @@ -504,8 +502,8 @@ describe('Admin Controllers', function () { }); }); - it('should load /post-queue', function (done) { - request(`${nconf.get('url')}/api/post-queue`, { jar: jar, json: true }, function (err, res, body) { + it('should load /post-queue', (done) => { + request(`${nconf.get('url')}/api/post-queue`, { jar: jar, json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -513,8 +511,8 @@ describe('Admin Controllers', function () { }); }); - it('/ip-blacklist should 404 for regular user', function (done) { - request(`${nconf.get('url')}/api/ip-blacklist`, { json: true }, function (err, res, body) { + it('/ip-blacklist should 404 for regular user', (done) => { + request(`${nconf.get('url')}/api/ip-blacklist`, { json: true }, (err, res, body) => { assert.ifError(err); assert(body); assert.equal(res.statusCode, 404); @@ -522,8 +520,8 @@ describe('Admin Controllers', function () { }); }); - it('should load /ip-blacklist', function (done) { - request(`${nconf.get('url')}/api/ip-blacklist`, { jar: jar, json: true }, function (err, res, body) { + it('should load /ip-blacklist', (done) => { + request(`${nconf.get('url')}/api/ip-blacklist`, { jar: jar, json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -531,8 +529,8 @@ describe('Admin Controllers', function () { }); }); - it('should load /admin/appearance/themes', function (done) { - request(`${nconf.get('url')}/api/admin/appearance/themes`, { jar: jar, json: true }, function (err, res, body) { + it('should load /admin/appearance/themes', (done) => { + request(`${nconf.get('url')}/api/admin/appearance/themes`, { jar: jar, json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -540,8 +538,8 @@ describe('Admin Controllers', function () { }); }); - it('should load /admin/appearance/customise', function (done) { - request(`${nconf.get('url')}/api/admin/appearance/customise`, { jar: jar, json: true }, function (err, res, body) { + it('should load /admin/appearance/customise', (done) => { + request(`${nconf.get('url')}/api/admin/appearance/customise`, { jar: jar, json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -549,9 +547,9 @@ describe('Admin Controllers', function () { }); }); - it('should load /recent in maintenance mode', function (done) { + it('should load /recent in maintenance mode', (done) => { meta.config.maintenanceMode = 1; - request(`${nconf.get('url')}/api/recent`, { jar: jar, json: true }, function (err, res, body) { + request(`${nconf.get('url')}/api/recent`, { jar: jar, json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -560,11 +558,11 @@ describe('Admin Controllers', function () { }); }); - describe('mods page', function () { + describe('mods page', () => { var moderatorJar; - before(function (done) { - helpers.loginUser('moderator', 'modmod', function (err, _jar) { + before((done) => { + helpers.loginUser('moderator', 'modmod', (err, _jar) => { assert.ifError(err); moderatorJar = _jar; @@ -572,16 +570,16 @@ describe('Admin Controllers', function () { }); }); - it('should error with no privileges', function (done) { - request(`${nconf.get('url')}/api/flags`, { json: true }, function (err, res, body) { + it('should error with no privileges', (done) => { + request(`${nconf.get('url')}/api/flags`, { json: true }, (err, res, body) => { assert.ifError(err); assert.equal(body.error, '[[error:no-privileges]]'); done(); }); }); - it('should load flags page data', function (done) { - request(`${nconf.get('url')}/api/flags`, { jar: moderatorJar, json: true }, function (err, res, body) { + it('should load flags page data', (done) => { + request(`${nconf.get('url')}/api/flags`, { jar: moderatorJar, json: true }, (err, res, body) => { assert.ifError(err); assert(body); assert(body.flags); @@ -591,8 +589,8 @@ describe('Admin Controllers', function () { }); }); - it('should return invalid data if flag does not exist', function (done) { - request(`${nconf.get('url')}/api/flags/123123123`, { jar: moderatorJar, json: true }, function (err, res, body) { + it('should return invalid data if flag does not exist', (done) => { + request(`${nconf.get('url')}/api/flags/123123123`, { jar: moderatorJar, json: true }, (err, res, body) => { assert.ifError(err); assert.equal(body.error, '[[error:invalid-data]]'); done(); @@ -609,25 +607,25 @@ describe('Admin Controllers', function () { } }); - it('should error with not enough reputation to flag', function (done) { + it('should error with not enough reputation to flag', (done) => { var socketFlags = require('../src/socket.io/flags'); var oldValue = meta.config['min:rep:flag']; meta.config['min:rep:flag'] = 1000; - socketFlags.create({ uid: regularUid }, { id: regularPid, type: 'post', reason: 'spam' }, function (err) { + socketFlags.create({ uid: regularUid }, { id: regularPid, type: 'post', reason: 'spam' }, (err) => { assert.strictEqual(err.message, '[[error:not-enough-reputation-to-flag]]'); meta.config['min:rep:flag'] = oldValue; done(); }); }); - it('should return flag details', function (done) { + it('should return flag details', (done) => { var socketFlags = require('../src/socket.io/flags'); var oldValue = meta.config['min:rep:flag']; meta.config['min:rep:flag'] = 0; - socketFlags.create({ uid: regularUid }, { id: regularPid, type: 'post', reason: 'spam' }, function (err, flagId) { + socketFlags.create({ uid: regularUid }, { id: regularPid, type: 'post', reason: 'spam' }, (err, flagId) => { meta.config['min:rep:flag'] = oldValue; assert.ifError(err); - request(`${nconf.get('url')}/api/flags/${flagId}`, { jar: moderatorJar, json: true }, function (err, res, body) { + request(`${nconf.get('url')}/api/flags/${flagId}`, { jar: moderatorJar, json: true }, (err, res, body) => { assert.ifError(err); assert(body); assert(body.reports); @@ -639,7 +637,7 @@ describe('Admin Controllers', function () { }); }); - it('should escape special characters in config', function (done) { + it('should escape special characters in config', (done) => { var plugins = require('../src/plugins'); function onConfigGet(config, callback) { config.someValue = '"foo"'; @@ -648,14 +646,14 @@ describe('Admin Controllers', function () { callback(null, config); } plugins.hooks.register('somePlugin', { hook: 'filter:config.get', method: onConfigGet }); - request(`${nconf.get('url')}/admin`, { jar: jar }, function (err, res, body) { + request(`${nconf.get('url')}/admin`, { jar: jar }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); assert(body.includes('"someValue":"\\\\"foo\\\\""')); assert(body.includes('"otherValue":"\\\'123\\\'"')); assert(body.includes('"script":"<\\/script>"')); - request(nconf.get('url'), { jar: jar }, function (err, res, body) { + request(nconf.get('url'), { jar: jar }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); diff --git a/test/controllers.js b/test/controllers.js index a2cd20c509..b4a83db293 100644 --- a/test/controllers.js +++ b/test/controllers.js @@ -20,14 +20,14 @@ var plugins = require('../src/plugins'); var utils = require('../src/utils'); var helpers = require('./helpers'); -describe('Controllers', function () { +describe('Controllers', () => { var tid; var cid; var pid; var fooUid; var category; - before(function (done) { + before((done) => { async.series({ category: function (next) { categories.create({ @@ -44,7 +44,7 @@ describe('Controllers', function () { navigation.save(data, next); }, - }, function (err, results) { + }, (err, results) => { if (err) { return done(err); } @@ -52,7 +52,7 @@ describe('Controllers', function () { cid = results.category.cid; fooUid = results.user; - topics.post({ uid: results.user, title: 'test topic title', content: 'test topic content', cid: results.category.cid }, function (err, result) { + topics.post({ uid: results.user, title: 'test topic title', content: 'test topic content', cid: results.category.cid }, (err, result) => { tid = result.topicData.tid; pid = result.postData.pid; done(err); @@ -60,11 +60,11 @@ describe('Controllers', function () { }); }); - it('should load /config with csrf_token', function (done) { + it('should load /config with csrf_token', (done) => { request({ url: `${nconf.get('url')}/api/config`, json: true, - }, function (err, response, body) { + }, (err, response, body) => { assert.ifError(err); assert.equal(response.statusCode, 200); assert(body.csrf_token); @@ -72,14 +72,14 @@ describe('Controllers', function () { }); }); - it('should load /config with no csrf_token as spider', function (done) { + it('should load /config with no csrf_token as spider', (done) => { request({ url: `${nconf.get('url')}/api/config`, json: true, headers: { 'user-agent': 'yandex', }, - }, function (err, response, body) { + }, (err, response, body) => { assert.ifError(err); assert.equal(response.statusCode, 200); assert.strictEqual(body.csrf_token, false); @@ -89,7 +89,7 @@ describe('Controllers', function () { }); }); - describe('homepage', function () { + describe('homepage', () => { function hookMethod(hookData) { assert(hookData.req); assert(hookData.res); @@ -113,8 +113,8 @@ describe('Controllers', function () { await meta.templates.compileTemplate(name, message); }); - it('should load default', function (done) { - request(nconf.get('url'), function (err, res, body) { + it('should load default', (done) => { + request(nconf.get('url'), (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -122,11 +122,11 @@ describe('Controllers', function () { }); }); - it('should load unread', function (done) { - meta.configs.set('homePageRoute', 'unread', function (err) { + it('should load unread', (done) => { + meta.configs.set('homePageRoute', 'unread', (err) => { assert.ifError(err); - request(nconf.get('url'), function (err, res, body) { + request(nconf.get('url'), (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -135,11 +135,11 @@ describe('Controllers', function () { }); }); - it('should load recent', function (done) { - meta.configs.set('homePageRoute', 'recent', function (err) { + it('should load recent', (done) => { + meta.configs.set('homePageRoute', 'recent', (err) => { assert.ifError(err); - request(nconf.get('url'), function (err, res, body) { + request(nconf.get('url'), (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -148,11 +148,11 @@ describe('Controllers', function () { }); }); - it('should load top', function (done) { - meta.configs.set('homePageRoute', 'top', function (err) { + it('should load top', (done) => { + meta.configs.set('homePageRoute', 'top', (err) => { assert.ifError(err); - request(nconf.get('url'), function (err, res, body) { + request(nconf.get('url'), (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -161,11 +161,11 @@ describe('Controllers', function () { }); }); - it('should load popular', function (done) { - meta.configs.set('homePageRoute', 'popular', function (err) { + it('should load popular', (done) => { + meta.configs.set('homePageRoute', 'popular', (err) => { assert.ifError(err); - request(nconf.get('url'), function (err, res, body) { + request(nconf.get('url'), (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -174,11 +174,11 @@ describe('Controllers', function () { }); }); - it('should load category', function (done) { - meta.configs.set('homePageRoute', 'category/1/test-category', function (err) { + it('should load category', (done) => { + meta.configs.set('homePageRoute', 'category/1/test-category', (err) => { assert.ifError(err); - request(nconf.get('url'), function (err, res, body) { + request(nconf.get('url'), (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -187,8 +187,8 @@ describe('Controllers', function () { }); }); - it('should not load breadcrumbs on home page route', function (done) { - request(`${nconf.get('url')}/api`, { json: true }, function (err, res, body) { + it('should not load breadcrumbs on home page route', (done) => { + request(`${nconf.get('url')}/api`, { json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -197,11 +197,11 @@ describe('Controllers', function () { }); }); - it('should redirect to custom', function (done) { - meta.configs.set('homePageRoute', 'groups', function (err) { + it('should redirect to custom', (done) => { + meta.configs.set('homePageRoute', 'groups', (err) => { assert.ifError(err); - request(nconf.get('url'), function (err, res, body) { + request(nconf.get('url'), (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -210,11 +210,11 @@ describe('Controllers', function () { }); }); - it('should 404 if custom does not exist', function (done) { - meta.configs.set('homePageRoute', 'this-route-does-not-exist', function (err) { + it('should 404 if custom does not exist', (done) => { + meta.configs.set('homePageRoute', 'this-route-does-not-exist', (err) => { assert.ifError(err); - request(nconf.get('url'), function (err, res, body) { + request(nconf.get('url'), (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 404); assert(body); @@ -223,11 +223,11 @@ describe('Controllers', function () { }); }); - it('api should work with hook', function (done) { - meta.configs.set('homePageRoute', 'mycustompage', function (err) { + it('api should work with hook', (done) => { + meta.configs.set('homePageRoute', 'mycustompage', (err) => { assert.ifError(err); - request(`${nconf.get('url')}/api`, { json: true }, function (err, res, body) { + request(`${nconf.get('url')}/api`, { json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert.equal(body.works, true); @@ -238,11 +238,11 @@ describe('Controllers', function () { }); }); - it('should render with hook', function (done) { - meta.configs.set('homePageRoute', 'mycustompage', function (err) { + it('should render with hook', (done) => { + meta.configs.set('homePageRoute', 'mycustompage', (err) => { assert.ifError(err); - request(nconf.get('url'), function (err, res, body) { + request(nconf.get('url'), (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert.ok(body); @@ -254,15 +254,15 @@ describe('Controllers', function () { }); }); - after(function () { + after(() => { plugins.hooks.unregister('myTestPlugin', 'action:homepage.get:custom', hookMethod); fs.unlinkSync(tplPath); fs.unlinkSync(tplPath.replace(/\.tpl$/, '.js')); }); }); - it('should load /reset without code', function (done) { - request(`${nconf.get('url')}/reset`, function (err, res, body) { + it('should load /reset without code', (done) => { + request(`${nconf.get('url')}/reset`, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -270,8 +270,8 @@ describe('Controllers', function () { }); }); - it('should load /reset with invalid code', function (done) { - request(`${nconf.get('url')}/reset/123123`, function (err, res, body) { + it('should load /reset with invalid code', (done) => { + request(`${nconf.get('url')}/reset/123123`, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -279,8 +279,8 @@ describe('Controllers', function () { }); }); - it('should load /login', function (done) { - request(`${nconf.get('url')}/login`, function (err, res, body) { + it('should load /login', (done) => { + request(`${nconf.get('url')}/login`, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -288,8 +288,8 @@ describe('Controllers', function () { }); }); - it('should load /register', function (done) { - request(`${nconf.get('url')}/register`, function (err, res, body) { + it('should load /register', (done) => { + request(`${nconf.get('url')}/register`, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -297,7 +297,7 @@ describe('Controllers', function () { }); }); - it('should load /register/complete', function (done) { + it('should load /register/complete', (done) => { function hookMethod(data, next) { data.interstitials.push({ template: 'topic.tpl', data: {} }); next(null, data); @@ -320,7 +320,7 @@ describe('Controllers', function () { url: `${nconf.get('url')}/api/config`, json: true, jar: jar, - }, function (err, response, body) { + }, (err, response, body) => { assert.ifError(err); request.post(`${nconf.get('url')}/register`, { @@ -330,14 +330,14 @@ describe('Controllers', function () { headers: { 'x-csrf-token': body.csrf_token, }, - }, function (err, res, body) { + }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert.strictEqual(body.next, `${nconf.get('relative_path')}/register/complete`); request(`${nconf.get('url')}/api/register/complete`, { jar: jar, json: true, - }, function (err, res, body) { + }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body.sections); @@ -350,8 +350,8 @@ describe('Controllers', function () { }); }); - it('should load /robots.txt', function (done) { - request(`${nconf.get('url')}/robots.txt`, function (err, res, body) { + it('should load /robots.txt', (done) => { + request(`${nconf.get('url')}/robots.txt`, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -359,8 +359,8 @@ describe('Controllers', function () { }); }); - it('should load /manifest.webmanifest', function (done) { - request(`${nconf.get('url')}/manifest.webmanifest`, function (err, res, body) { + it('should load /manifest.webmanifest', (done) => { + request(`${nconf.get('url')}/manifest.webmanifest`, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -368,8 +368,8 @@ describe('Controllers', function () { }); }); - it('should load /outgoing?url=', function (done) { - request(`${nconf.get('url')}/outgoing?url=http://youtube.com`, function (err, res, body) { + it('should load /outgoing?url=', (done) => { + request(`${nconf.get('url')}/outgoing?url=http://youtube.com`, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -377,8 +377,8 @@ describe('Controllers', function () { }); }); - it('should 404 on /outgoing with no url', function (done) { - request(`${nconf.get('url')}/outgoing`, function (err, res, body) { + it('should 404 on /outgoing with no url', (done) => { + request(`${nconf.get('url')}/outgoing`, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 404); assert(body); @@ -386,8 +386,8 @@ describe('Controllers', function () { }); }); - it('should 404 on /outgoing with javascript: protocol', function (done) { - request(`${nconf.get('url')}/outgoing?url=javascript:alert(1);`, function (err, res, body) { + it('should 404 on /outgoing with javascript: protocol', (done) => { + request(`${nconf.get('url')}/outgoing?url=javascript:alert(1);`, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 404); assert(body); @@ -395,8 +395,8 @@ describe('Controllers', function () { }); }); - it('should 404 on /outgoing with invalid url', function (done) { - request(`${nconf.get('url')}/outgoing?url=derp`, function (err, res, body) { + it('should 404 on /outgoing with invalid url', (done) => { + request(`${nconf.get('url')}/outgoing?url=derp`, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 404); assert(body); @@ -404,9 +404,9 @@ describe('Controllers', function () { }); }); - it('should load /tos', function (done) { + it('should load /tos', (done) => { meta.config.termsOfUse = 'please accept our tos'; - request(`${nconf.get('url')}/tos`, function (err, res, body) { + request(`${nconf.get('url')}/tos`, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -415,9 +415,9 @@ describe('Controllers', function () { }); - it('should load 404 if meta.config.termsOfUse is empty', function (done) { + it('should load 404 if meta.config.termsOfUse is empty', (done) => { meta.config.termsOfUse = ''; - request(`${nconf.get('url')}/tos`, function (err, res, body) { + request(`${nconf.get('url')}/tos`, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 404); assert(body); @@ -425,8 +425,8 @@ describe('Controllers', function () { }); }); - it('should load /sping', function (done) { - request(`${nconf.get('url')}/sping`, function (err, res, body) { + it('should load /sping', (done) => { + request(`${nconf.get('url')}/sping`, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert.equal(body, 'healthy'); @@ -434,8 +434,8 @@ describe('Controllers', function () { }); }); - it('should load /ping', function (done) { - request(`${nconf.get('url')}/ping`, function (err, res, body) { + it('should load /ping', (done) => { + request(`${nconf.get('url')}/ping`, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert.equal(body, '200'); @@ -443,8 +443,8 @@ describe('Controllers', function () { }); }); - it('should handle 404', function (done) { - request(`${nconf.get('url')}/arouteinthevoid`, function (err, res, body) { + it('should handle 404', (done) => { + request(`${nconf.get('url')}/arouteinthevoid`, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 404); assert(body); @@ -452,8 +452,8 @@ describe('Controllers', function () { }); }); - it('should load topic rss feed', function (done) { - request(`${nconf.get('url')}/topic/${tid}.rss`, function (err, res, body) { + it('should load topic rss feed', (done) => { + request(`${nconf.get('url')}/topic/${tid}.rss`, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -461,8 +461,8 @@ describe('Controllers', function () { }); }); - it('should load category rss feed', function (done) { - request(`${nconf.get('url')}/category/${cid}.rss`, function (err, res, body) { + it('should load category rss feed', (done) => { + request(`${nconf.get('url')}/category/${cid}.rss`, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -470,8 +470,8 @@ describe('Controllers', function () { }); }); - it('should load topics rss feed', function (done) { - request(`${nconf.get('url')}/topics.rss`, function (err, res, body) { + it('should load topics rss feed', (done) => { + request(`${nconf.get('url')}/topics.rss`, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -479,8 +479,8 @@ describe('Controllers', function () { }); }); - it('should load recent rss feed', function (done) { - request(`${nconf.get('url')}/recent.rss`, function (err, res, body) { + it('should load recent rss feed', (done) => { + request(`${nconf.get('url')}/recent.rss`, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -488,8 +488,8 @@ describe('Controllers', function () { }); }); - it('should load top rss feed', function (done) { - request(`${nconf.get('url')}/top.rss`, function (err, res, body) { + it('should load top rss feed', (done) => { + request(`${nconf.get('url')}/top.rss`, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -497,8 +497,8 @@ describe('Controllers', function () { }); }); - it('should load popular rss feed', function (done) { - request(`${nconf.get('url')}/popular.rss`, function (err, res, body) { + it('should load popular rss feed', (done) => { + request(`${nconf.get('url')}/popular.rss`, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -506,8 +506,8 @@ describe('Controllers', function () { }); }); - it('should load popular rss feed with term', function (done) { - request(`${nconf.get('url')}/popular/day.rss`, function (err, res, body) { + it('should load popular rss feed with term', (done) => { + request(`${nconf.get('url')}/popular/day.rss`, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -515,8 +515,8 @@ describe('Controllers', function () { }); }); - it('should load recent posts rss feed', function (done) { - request(`${nconf.get('url')}/recentposts.rss`, function (err, res, body) { + it('should load recent posts rss feed', (done) => { + request(`${nconf.get('url')}/recentposts.rss`, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -524,8 +524,8 @@ describe('Controllers', function () { }); }); - it('should load category recent posts rss feed', function (done) { - request(`${nconf.get('url')}/category/${cid}/recentposts.rss`, function (err, res, body) { + it('should load category recent posts rss feed', (done) => { + request(`${nconf.get('url')}/category/${cid}/recentposts.rss`, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -533,8 +533,8 @@ describe('Controllers', function () { }); }); - it('should load user topics rss feed', function (done) { - request(`${nconf.get('url')}/user/foo/topics.rss`, function (err, res, body) { + it('should load user topics rss feed', (done) => { + request(`${nconf.get('url')}/user/foo/topics.rss`, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -542,8 +542,8 @@ describe('Controllers', function () { }); }); - it('should load tag rss feed', function (done) { - request(`${nconf.get('url')}/tags/nodebb.rss`, function (err, res, body) { + it('should load tag rss feed', (done) => { + request(`${nconf.get('url')}/tags/nodebb.rss`, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -551,8 +551,8 @@ describe('Controllers', function () { }); }); - it('should load client.css', function (done) { - request(`${nconf.get('url')}/assets/client.css`, function (err, res, body) { + it('should load client.css', (done) => { + request(`${nconf.get('url')}/assets/client.css`, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -560,8 +560,8 @@ describe('Controllers', function () { }); }); - it('should load admin.css', function (done) { - request(`${nconf.get('url')}/assets/admin.css`, function (err, res, body) { + it('should load admin.css', (done) => { + request(`${nconf.get('url')}/assets/admin.css`, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -570,8 +570,8 @@ describe('Controllers', function () { }); - it('should load nodebb.min.js', function (done) { - request(`${nconf.get('url')}/assets/nodebb.min.js`, function (err, res, body) { + it('should load nodebb.min.js', (done) => { + request(`${nconf.get('url')}/assets/nodebb.min.js`, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -579,8 +579,8 @@ describe('Controllers', function () { }); }); - it('should load acp.min.js', function (done) { - request(`${nconf.get('url')}/assets/acp.min.js`, function (err, res, body) { + it('should load acp.min.js', (done) => { + request(`${nconf.get('url')}/assets/acp.min.js`, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -588,8 +588,8 @@ describe('Controllers', function () { }); }); - it('should load sitemap.xml', function (done) { - request(`${nconf.get('url')}/sitemap.xml`, function (err, res, body) { + it('should load sitemap.xml', (done) => { + request(`${nconf.get('url')}/sitemap.xml`, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -597,8 +597,8 @@ describe('Controllers', function () { }); }); - it('should load sitemap/pages.xml', function (done) { - request(`${nconf.get('url')}/sitemap/pages.xml`, function (err, res, body) { + it('should load sitemap/pages.xml', (done) => { + request(`${nconf.get('url')}/sitemap/pages.xml`, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -606,8 +606,8 @@ describe('Controllers', function () { }); }); - it('should load sitemap/categories.xml', function (done) { - request(`${nconf.get('url')}/sitemap/categories.xml`, function (err, res, body) { + it('should load sitemap/categories.xml', (done) => { + request(`${nconf.get('url')}/sitemap/categories.xml`, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -615,8 +615,8 @@ describe('Controllers', function () { }); }); - it('should load sitemap/topics/1.xml', function (done) { - request(`${nconf.get('url')}/sitemap/topics.1.xml`, function (err, res, body) { + it('should load sitemap/topics/1.xml', (done) => { + request(`${nconf.get('url')}/sitemap/topics.1.xml`, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -624,8 +624,8 @@ describe('Controllers', function () { }); }); - it('should load robots.txt', function (done) { - request(`${nconf.get('url')}/robots.txt`, function (err, res, body) { + it('should load robots.txt', (done) => { + request(`${nconf.get('url')}/robots.txt`, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -633,8 +633,8 @@ describe('Controllers', function () { }); }); - it('should load theme screenshot', function (done) { - request(`${nconf.get('url')}/css/previews/nodebb-theme-persona`, function (err, res, body) { + it('should load theme screenshot', (done) => { + request(`${nconf.get('url')}/css/previews/nodebb-theme-persona`, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -642,8 +642,8 @@ describe('Controllers', function () { }); }); - it('should load users page', function (done) { - request(`${nconf.get('url')}/users`, function (err, res, body) { + it('should load users page', (done) => { + request(`${nconf.get('url')}/users`, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -651,8 +651,8 @@ describe('Controllers', function () { }); }); - it('should load users page', function (done) { - request(`${nconf.get('url')}/users?section=online`, function (err, res, body) { + it('should load users page', (done) => { + request(`${nconf.get('url')}/users?section=online`, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -660,8 +660,8 @@ describe('Controllers', function () { }); }); - it('should error if guests do not have search privilege', function (done) { - request(`${nconf.get('url')}/api/users?query=bar§ion=sort-posts`, { json: true }, function (err, res, body) { + it('should error if guests do not have search privilege', (done) => { + request(`${nconf.get('url')}/api/users?query=bar§ion=sort-posts`, { json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 500); assert(body); @@ -670,10 +670,10 @@ describe('Controllers', function () { }); }); - it('should load users search page', function (done) { - privileges.global.give(['groups:search:users'], 'guests', function (err) { + it('should load users search page', (done) => { + privileges.global.give(['groups:search:users'], 'guests', (err) => { assert.ifError(err); - request(`${nconf.get('url')}/users?query=bar§ion=sort-posts`, function (err, res, body) { + request(`${nconf.get('url')}/users?query=bar§ion=sort-posts`, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -682,8 +682,8 @@ describe('Controllers', function () { }); }); - it('should load groups page', function (done) { - request(`${nconf.get('url')}/groups`, function (err, res, body) { + it('should load groups page', (done) => { + request(`${nconf.get('url')}/groups`, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -691,23 +691,23 @@ describe('Controllers', function () { }); }); - it('should load group details page', function (done) { + it('should load group details page', (done) => { groups.create({ name: 'group-details', description: 'Foobar!', hidden: 0, - }, function (err) { + }, (err) => { assert.ifError(err); - groups.join('group-details', fooUid, function (err) { + groups.join('group-details', fooUid, (err) => { assert.ifError(err); topics.post({ uid: fooUid, title: 'topic title', content: 'test topic content', cid: cid, - }, function (err) { + }, (err) => { assert.ifError(err); - request(`${nconf.get('url')}/api/groups/group-details`, { json: true }, function (err, res, body) { + request(`${nconf.get('url')}/api/groups/group-details`, { json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -719,8 +719,8 @@ describe('Controllers', function () { }); }); - it('should load group members page', function (done) { - request(`${nconf.get('url')}/groups/group-details/members`, function (err, res, body) { + it('should load group members page', (done) => { + request(`${nconf.get('url')}/groups/group-details/members`, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -728,15 +728,15 @@ describe('Controllers', function () { }); }); - it('should 404 when trying to load group members of hidden group', function (done) { + it('should 404 when trying to load group members of hidden group', (done) => { var groups = require('../src/groups'); groups.create({ name: 'hidden-group', description: 'Foobar!', hidden: 1, - }, function (err) { + }, (err) => { assert.ifError(err); - request(`${nconf.get('url')}/groups/hidden-group/members`, function (err, res) { + request(`${nconf.get('url')}/groups/hidden-group/members`, (err, res) => { assert.ifError(err); assert.equal(res.statusCode, 404); done(); @@ -744,8 +744,8 @@ describe('Controllers', function () { }); }); - it('should get recent posts', function (done) { - request(`${nconf.get('url')}/api/recent/posts/month`, function (err, res, body) { + it('should get recent posts', (done) => { + request(`${nconf.get('url')}/api/recent/posts/month`, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -753,8 +753,8 @@ describe('Controllers', function () { }); }); - it('should get post data', function (done) { - request(`${nconf.get('url')}/api/v3/posts/${pid}`, function (err, res, body) { + it('should get post data', (done) => { + request(`${nconf.get('url')}/api/v3/posts/${pid}`, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -762,8 +762,8 @@ describe('Controllers', function () { }); }); - it('should get topic data', function (done) { - request(`${nconf.get('url')}/api/v3/topics/${tid}`, function (err, res, body) { + it('should get topic data', (done) => { + request(`${nconf.get('url')}/api/v3/topics/${tid}`, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -771,8 +771,8 @@ describe('Controllers', function () { }); }); - it('should get category data', function (done) { - request(`${nconf.get('url')}/api/v3/categories/${cid}`, function (err, res, body) { + it('should get category data', (done) => { + request(`${nconf.get('url')}/api/v3/categories/${cid}`, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -781,16 +781,16 @@ describe('Controllers', function () { }); - describe('revoke session', function () { + describe('revoke session', () => { var uid; var jar; var csrf_token; - before(function (done) { - user.create({ username: 'revokeme', password: 'barbar' }, function (err, _uid) { + before((done) => { + user.create({ username: 'revokeme', password: 'barbar' }, (err, _uid) => { assert.ifError(err); uid = _uid; - helpers.loginUser('revokeme', 'barbar', function (err, _jar, _csrf_token) { + helpers.loginUser('revokeme', 'barbar', (err, _jar, _csrf_token) => { assert.ifError(err); jar = _jar; csrf_token = _csrf_token; @@ -799,26 +799,26 @@ describe('Controllers', function () { }); }); - it('should fail to revoke session with missing uuid', function (done) { + it('should fail to revoke session with missing uuid', (done) => { request.del(`${nconf.get('url')}/api/user/revokeme/session`, { jar: jar, headers: { 'x-csrf-token': csrf_token, }, - }, function (err, res) { + }, (err, res) => { assert.ifError(err); assert.equal(res.statusCode, 404); done(); }); }); - it('should fail if user doesn\'t exist', function (done) { + it('should fail if user doesn\'t exist', (done) => { request.del(`${nconf.get('url')}/api/v3/users/doesnotexist/sessions/1112233`, { jar: jar, headers: { 'x-csrf-token': csrf_token, }, - }, function (err, res, body) { + }, (err, res, body) => { assert.ifError(err); assert.strictEqual(res.statusCode, 404); const parsedResponse = JSON.parse(body); @@ -831,19 +831,19 @@ describe('Controllers', function () { }); }); - it('should revoke user session', function (done) { - db.getSortedSetRange(`uid:${uid}:sessions`, 0, -1, function (err, sids) { + it('should revoke user session', (done) => { + db.getSortedSetRange(`uid:${uid}:sessions`, 0, -1, (err, sids) => { assert.ifError(err); var sid = sids[0]; - db.sessionStore.get(sid, function (err, sessionObj) { + db.sessionStore.get(sid, (err, sessionObj) => { assert.ifError(err); request.del(`${nconf.get('url')}/api/v3/users/${uid}/sessions/${sessionObj.meta.uuid}`, { jar: jar, headers: { 'x-csrf-token': csrf_token, }, - }, function (err, res, body) { + }, (err, res, body) => { assert.ifError(err); assert.strictEqual(res.statusCode, 200); assert.deepStrictEqual(JSON.parse(body), { @@ -860,10 +860,10 @@ describe('Controllers', function () { }); }); - describe('widgets', function () { + describe('widgets', () => { var widgets = require('../src/widgets'); - before(function (done) { + before((done) => { async.waterfall([ function (next) { widgets.reset(next); @@ -889,8 +889,8 @@ describe('Controllers', function () { ], done); }); - it('should return {} if there are no widgets', function (done) { - request(`${nconf.get('url')}/api/category/${cid}`, { json: true }, function (err, res, body) { + it('should return {} if there are no widgets', (done) => { + request(`${nconf.get('url')}/api/category/${cid}`, { json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body.widgets); @@ -899,9 +899,9 @@ describe('Controllers', function () { }); }); - it('should render templates', function (done) { + it('should render templates', (done) => { var url = `${nconf.get('url')}/api/categories`; - request(url, { json: true }, function (err, res, body) { + request(url, { json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body.widgets); @@ -911,10 +911,10 @@ describe('Controllers', function () { }); }); - it('should reset templates', function (done) { - widgets.resetTemplates(['categories', 'category'], function (err) { + it('should reset templates', (done) => { + widgets.resetTemplates(['categories', 'category'], (err) => { assert.ifError(err); - request(`${nconf.get('url')}/api/categories`, { json: true }, function (err, res, body) { + request(`${nconf.get('url')}/api/categories`, { json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body.widgets); @@ -925,24 +925,24 @@ describe('Controllers', function () { }); }); - describe('tags', function () { + describe('tags', () => { var tid; - before(function (done) { + before((done) => { topics.post({ uid: fooUid, title: 'topic title', content: 'test topic content', cid: cid, tags: ['nodebb', 'bug', 'test'], - }, function (err, result) { + }, (err, result) => { assert.ifError(err); tid = result.topicData.tid; done(); }); }); - it('should render tags page', function (done) { - request(`${nconf.get('url')}/api/tags`, { json: true }, function (err, res, body) { + it('should render tags page', (done) => { + request(`${nconf.get('url')}/api/tags`, { json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -951,8 +951,8 @@ describe('Controllers', function () { }); }); - it('should render tag page with no topics', function (done) { - request(`${nconf.get('url')}/api/tags/notag`, { json: true }, function (err, res, body) { + it('should render tag page with no topics', (done) => { + request(`${nconf.get('url')}/api/tags/notag`, { json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -962,8 +962,8 @@ describe('Controllers', function () { }); }); - it('should render tag page with 1 topic', function (done) { - request(`${nconf.get('url')}/api/tags/nodebb`, { json: true }, function (err, res, body) { + it('should render tag page with 1 topic', (done) => { + request(`${nconf.get('url')}/api/tags/nodebb`, { json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -975,26 +975,26 @@ describe('Controllers', function () { }); - describe('maintenance mode', function () { - before(function (done) { + describe('maintenance mode', () => { + before((done) => { meta.config.maintenanceMode = 1; done(); }); - after(function (done) { + after((done) => { meta.config.maintenanceMode = 0; done(); }); - it('should return 503 in maintenance mode', function (done) { - request(`${nconf.get('url')}/recent`, { json: true }, function (err, res) { + it('should return 503 in maintenance mode', (done) => { + request(`${nconf.get('url')}/recent`, { json: true }, (err, res) => { assert.ifError(err); assert.equal(res.statusCode, 503); done(); }); }); - it('should return 503 in maintenance mode', function (done) { - request(`${nconf.get('url')}/api/recent`, { json: true }, function (err, res, body) { + it('should return 503 in maintenance mode', (done) => { + request(`${nconf.get('url')}/api/recent`, { json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 503); assert(body); @@ -1002,8 +1002,8 @@ describe('Controllers', function () { }); }); - it('should return 200 in maintenance mode', function (done) { - request(`${nconf.get('url')}/api/login`, { json: true }, function (err, res, body) { + it('should return 200 in maintenance mode', (done) => { + request(`${nconf.get('url')}/api/login`, { json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -1012,18 +1012,18 @@ describe('Controllers', function () { }); }); - describe('account pages', function () { + describe('account pages', () => { var jar; - before(function (done) { - helpers.loginUser('foo', 'barbar', function (err, _jar) { + before((done) => { + helpers.loginUser('foo', 'barbar', (err, _jar) => { assert.ifError(err); jar = _jar; done(); }); }); - it('should redirect to account page with logged in user', function (done) { - request(`${nconf.get('url')}/api/login`, { jar: jar, json: true }, function (err, res, body) { + it('should redirect to account page with logged in user', (done) => { + request(`${nconf.get('url')}/api/login`, { jar: jar, json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert.equal(res.headers['x-redirect'], '/user/foo'); @@ -1032,16 +1032,16 @@ describe('Controllers', function () { }); }); - it('should 404 if uid is not a number', function (done) { - request(`${nconf.get('url')}/api/uid/test`, { json: true }, function (err, res) { + it('should 404 if uid is not a number', (done) => { + request(`${nconf.get('url')}/api/uid/test`, { json: true }, (err, res) => { assert.ifError(err); assert.equal(res.statusCode, 404); done(); }); }); - it('should redirect to userslug', function (done) { - request(`${nconf.get('url')}/api/uid/${fooUid}`, { json: true }, function (err, res, body) { + it('should redirect to userslug', (done) => { + request(`${nconf.get('url')}/api/uid/${fooUid}`, { json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert.equal(res.headers['x-redirect'], '/user/foo'); @@ -1050,17 +1050,17 @@ describe('Controllers', function () { }); }); - it('should 404 if user does not exist', function (done) { - request(`${nconf.get('url')}/api/uid/123123`, { json: true }, function (err, res) { + it('should 404 if user does not exist', (done) => { + request(`${nconf.get('url')}/api/uid/123123`, { json: true }, (err, res) => { assert.ifError(err); assert.equal(res.statusCode, 404); done(); }); }); - describe('/me/*', function () { - it('should redirect to user profile', function (done) { - request(`${nconf.get('url')}/me`, { jar: jar, json: true }, function (err, res, body) { + describe('/me/*', () => { + it('should redirect to user profile', (done) => { + request(`${nconf.get('url')}/me`, { jar: jar, json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body.includes('"template":{"name":"account/profile","account/profile":true}')); @@ -1068,8 +1068,8 @@ describe('Controllers', function () { done(); }); }); - it('api should redirect to /user/[userslug]/bookmarks', function (done) { - request(`${nconf.get('url')}/api/me/bookmarks`, { jar: jar, json: true }, function (err, res, body) { + it('api should redirect to /user/[userslug]/bookmarks', (done) => { + request(`${nconf.get('url')}/api/me/bookmarks`, { jar: jar, json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert.equal(res.headers['x-redirect'], '/user/foo/bookmarks'); @@ -1077,8 +1077,8 @@ describe('Controllers', function () { done(); }); }); - it('api should redirect to /user/[userslug]/edit/username', function (done) { - request(`${nconf.get('url')}/api/me/edit/username`, { jar: jar, json: true }, function (err, res, body) { + it('api should redirect to /user/[userslug]/edit/username', (done) => { + request(`${nconf.get('url')}/api/me/edit/username`, { jar: jar, json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert.equal(res.headers['x-redirect'], '/user/foo/edit/username'); @@ -1086,8 +1086,8 @@ describe('Controllers', function () { done(); }); }); - it('should redirect to login if user is not logged in', function (done) { - request(`${nconf.get('url')}/me/bookmarks`, { json: true }, function (err, res, body) { + it('should redirect to login if user is not logged in', (done) => { + request(`${nconf.get('url')}/me/bookmarks`, { json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body.includes('Login to your account'), body.substr(0, 500)); @@ -1096,24 +1096,24 @@ describe('Controllers', function () { }); }); - it('should 401 if user is not logged in', function (done) { - request(`${nconf.get('url')}/api/admin`, { json: true }, function (err, res) { + it('should 401 if user is not logged in', (done) => { + request(`${nconf.get('url')}/api/admin`, { json: true }, (err, res) => { assert.ifError(err); assert.equal(res.statusCode, 401); done(); }); }); - it('should 403 if user is not admin', function (done) { - request(`${nconf.get('url')}/api/admin`, { jar: jar, json: true }, function (err, res) { + it('should 403 if user is not admin', (done) => { + request(`${nconf.get('url')}/api/admin`, { jar: jar, json: true }, (err, res) => { assert.ifError(err); assert.equal(res.statusCode, 403); done(); }); }); - it('should load /user/foo/posts', function (done) { - request(`${nconf.get('url')}/api/user/foo/posts`, function (err, res, body) { + it('should load /user/foo/posts', (done) => { + request(`${nconf.get('url')}/api/user/foo/posts`, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -1121,8 +1121,8 @@ describe('Controllers', function () { }); }); - it('should 401 if not logged in', function (done) { - request(`${nconf.get('url')}/api/user/foo/bookmarks`, function (err, res, body) { + it('should 401 if not logged in', (done) => { + request(`${nconf.get('url')}/api/user/foo/bookmarks`, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 401); assert(body); @@ -1130,8 +1130,8 @@ describe('Controllers', function () { }); }); - it('should load /user/foo/bookmarks', function (done) { - request(`${nconf.get('url')}/api/user/foo/bookmarks`, { jar: jar }, function (err, res, body) { + it('should load /user/foo/bookmarks', (done) => { + request(`${nconf.get('url')}/api/user/foo/bookmarks`, { jar: jar }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -1139,8 +1139,8 @@ describe('Controllers', function () { }); }); - it('should load /user/foo/upvoted', function (done) { - request(`${nconf.get('url')}/api/user/foo/upvoted`, { jar: jar }, function (err, res, body) { + it('should load /user/foo/upvoted', (done) => { + request(`${nconf.get('url')}/api/user/foo/upvoted`, { jar: jar }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -1148,8 +1148,8 @@ describe('Controllers', function () { }); }); - it('should load /user/foo/downvoted', function (done) { - request(`${nconf.get('url')}/api/user/foo/downvoted`, { jar: jar }, function (err, res, body) { + it('should load /user/foo/downvoted', (done) => { + request(`${nconf.get('url')}/api/user/foo/downvoted`, { jar: jar }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -1157,8 +1157,8 @@ describe('Controllers', function () { }); }); - it('should load /user/foo/best', function (done) { - request(`${nconf.get('url')}/api/user/foo/best`, function (err, res, body) { + it('should load /user/foo/best', (done) => { + request(`${nconf.get('url')}/api/user/foo/best`, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -1166,8 +1166,8 @@ describe('Controllers', function () { }); }); - it('should load /user/foo/watched', function (done) { - request(`${nconf.get('url')}/api/user/foo/watched`, { jar: jar }, function (err, res, body) { + it('should load /user/foo/watched', (done) => { + request(`${nconf.get('url')}/api/user/foo/watched`, { jar: jar }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -1175,8 +1175,8 @@ describe('Controllers', function () { }); }); - it('should load /user/foo/ignored', function (done) { - request(`${nconf.get('url')}/api/user/foo/ignored`, { jar: jar }, function (err, res, body) { + it('should load /user/foo/ignored', (done) => { + request(`${nconf.get('url')}/api/user/foo/ignored`, { jar: jar }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -1184,8 +1184,8 @@ describe('Controllers', function () { }); }); - it('should load /user/foo/topics', function (done) { - request(`${nconf.get('url')}/api/user/foo/topics`, function (err, res, body) { + it('should load /user/foo/topics', (done) => { + request(`${nconf.get('url')}/api/user/foo/topics`, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -1193,8 +1193,8 @@ describe('Controllers', function () { }); }); - it('should load /user/foo/blocks', function (done) { - request(`${nconf.get('url')}/api/user/foo/blocks`, { jar: jar }, function (err, res, body) { + it('should load /user/foo/blocks', (done) => { + request(`${nconf.get('url')}/api/user/foo/blocks`, { jar: jar }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -1202,8 +1202,8 @@ describe('Controllers', function () { }); }); - it('should load /user/foo/consent', function (done) { - request(`${nconf.get('url')}/api/user/foo/consent`, { jar: jar }, function (err, res, body) { + it('should load /user/foo/consent', (done) => { + request(`${nconf.get('url')}/api/user/foo/consent`, { jar: jar }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -1211,8 +1211,8 @@ describe('Controllers', function () { }); }); - it('should load /user/foo/sessions', function (done) { - request(`${nconf.get('url')}/api/user/foo/sessions`, { jar: jar }, function (err, res, body) { + it('should load /user/foo/sessions', (done) => { + request(`${nconf.get('url')}/api/user/foo/sessions`, { jar: jar }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -1220,8 +1220,8 @@ describe('Controllers', function () { }); }); - it('should load /user/foo/categories', function (done) { - request(`${nconf.get('url')}/api/user/foo/categories`, { jar: jar }, function (err, res, body) { + it('should load /user/foo/categories', (done) => { + request(`${nconf.get('url')}/api/user/foo/categories`, { jar: jar }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -1229,8 +1229,8 @@ describe('Controllers', function () { }); }); - it('should load /user/foo/uploads', function (done) { - request(`${nconf.get('url')}/api/user/foo/uploads`, { jar: jar }, function (err, res, body) { + it('should load /user/foo/uploads', (done) => { + request(`${nconf.get('url')}/api/user/foo/uploads`, { jar: jar }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -1238,8 +1238,8 @@ describe('Controllers', function () { }); }); - it('should export users posts', function (done) { - request(`${nconf.get('url')}/api/user/uid/foo/export/posts`, { jar: jar }, function (err, res, body) { + it('should export users posts', (done) => { + request(`${nconf.get('url')}/api/user/uid/foo/export/posts`, { jar: jar }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -1247,8 +1247,8 @@ describe('Controllers', function () { }); }); - it('should export users uploads', function (done) { - request(`${nconf.get('url')}/api/user/uid/foo/export/uploads`, { jar: jar }, function (err, res, body) { + it('should export users uploads', (done) => { + request(`${nconf.get('url')}/api/user/uid/foo/export/uploads`, { jar: jar }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -1256,8 +1256,8 @@ describe('Controllers', function () { }); }); - it('should export users profile', function (done) { - request(`${nconf.get('url')}/api/user/uid/foo/export/profile`, { jar: jar }, function (err, res, body) { + it('should export users profile', (done) => { + request(`${nconf.get('url')}/api/user/uid/foo/export/profile`, { jar: jar }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -1265,7 +1265,7 @@ describe('Controllers', function () { }); }); - it('should load notifications page', function (done) { + it('should load notifications page', (done) => { var notifications = require('../src/notifications'); var notifData = { bodyShort: '[[notifications:user_posted_to, test1, test2]]', @@ -1305,8 +1305,8 @@ describe('Controllers', function () { ], done); }); - it('should 404 if user does not exist', function (done) { - request(`${nconf.get('url')}/api/user/email/doesnotexist`, function (err, res, body) { + it('should 404 if user does not exist', (done) => { + request(`${nconf.get('url')}/api/user/email/doesnotexist`, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 404); assert(body); @@ -1314,8 +1314,8 @@ describe('Controllers', function () { }); }); - it('should load user by uid', function (done) { - request(`${nconf.get('url')}/api/user/uid/${fooUid}`, function (err, res, body) { + it('should load user by uid', (done) => { + request(`${nconf.get('url')}/api/user/uid/${fooUid}`, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -1323,8 +1323,8 @@ describe('Controllers', function () { }); }); - it('should load user by username', function (done) { - request(`${nconf.get('url')}/api/user/username/foo`, function (err, res, body) { + it('should load user by username', (done) => { + request(`${nconf.get('url')}/api/user/username/foo`, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -1332,8 +1332,8 @@ describe('Controllers', function () { }); }); - it('should load user by email', function (done) { - request(`${nconf.get('url')}/api/user/email/foo@test.com`, function (err, res, body) { + it('should load user by email', (done) => { + request(`${nconf.get('url')}/api/user/email/foo@test.com`, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -1341,10 +1341,10 @@ describe('Controllers', function () { }); }); - it('should return 401 if user does not have view:users privilege', function (done) { - privileges.global.rescind(['groups:view:users'], 'guests', function (err) { + it('should return 401 if user does not have view:users privilege', (done) => { + privileges.global.rescind(['groups:view:users'], 'guests', (err) => { assert.ifError(err); - request(`${nconf.get('url')}/api/user/foo`, { json: true }, function (err, res, body) { + request(`${nconf.get('url')}/api/user/foo`, { json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 401); assert.deepEqual(body, { @@ -1359,15 +1359,15 @@ describe('Controllers', function () { }); }); - it('should return false if user can not edit user', function (done) { - user.create({ username: 'regularJoe', password: 'barbar' }, function (err) { + it('should return false if user can not edit user', (done) => { + user.create({ username: 'regularJoe', password: 'barbar' }, (err) => { assert.ifError(err); - helpers.loginUser('regularJoe', 'barbar', function (err, jar) { + helpers.loginUser('regularJoe', 'barbar', (err, jar) => { assert.ifError(err); - request(`${nconf.get('url')}/api/user/foo/info`, { jar: jar, json: true }, function (err, res) { + request(`${nconf.get('url')}/api/user/foo/info`, { jar: jar, json: true }, (err, res) => { assert.ifError(err); assert.equal(res.statusCode, 403); - request(`${nconf.get('url')}/api/user/foo/edit`, { jar: jar, json: true }, function (err, res) { + request(`${nconf.get('url')}/api/user/foo/edit`, { jar: jar, json: true }, (err, res) => { assert.ifError(err); assert.equal(res.statusCode, 403); done(); @@ -1377,16 +1377,16 @@ describe('Controllers', function () { }); }); - it('should load correct user', function (done) { - request(`${nconf.get('url')}/api/user/FOO`, { jar: jar, json: true }, function (err, res) { + it('should load correct user', (done) => { + request(`${nconf.get('url')}/api/user/FOO`, { jar: jar, json: true }, (err, res) => { assert.ifError(err); assert.equal(res.statusCode, 200); done(); }); }); - it('should redirect', function (done) { - request(`${nconf.get('url')}/user/FOO`, { jar: jar }, function (err, res, body) { + it('should redirect', (done) => { + request(`${nconf.get('url')}/user/FOO`, { jar: jar }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -1394,8 +1394,8 @@ describe('Controllers', function () { }); }); - it('should 404 if user does not exist', function (done) { - request(`${nconf.get('url')}/api/user/doesnotexist`, { jar: jar }, function (err, res) { + it('should 404 if user does not exist', (done) => { + request(`${nconf.get('url')}/api/user/doesnotexist`, { jar: jar }, (err, res) => { assert.ifError(err); assert.equal(res.statusCode, 404); done(); @@ -1403,11 +1403,11 @@ describe('Controllers', function () { }); it('should not increase profile view if you visit your own profile', (done) => { - request(`${nconf.get('url')}/api/user/foo`, { jar: jar }, function (err, res) { + request(`${nconf.get('url')}/api/user/foo`, { jar: jar }, (err, res) => { assert.ifError(err); assert.equal(res.statusCode, 200); - setTimeout(function () { - user.getUserField(fooUid, 'profileviews', function (err, viewcount) { + setTimeout(() => { + user.getUserField(fooUid, 'profileviews', (err, viewcount) => { assert.ifError(err); assert(viewcount === 0); done(); @@ -1417,11 +1417,11 @@ describe('Controllers', function () { }); it('should not increase profile view if a guest visits a profile', (done) => { - request(`${nconf.get('url')}/api/user/foo`, {}, function (err, res) { + request(`${nconf.get('url')}/api/user/foo`, {}, (err, res) => { assert.ifError(err); assert.equal(res.statusCode, 200); - setTimeout(function () { - user.getUserField(fooUid, 'profileviews', function (err, viewcount) { + setTimeout(() => { + user.getUserField(fooUid, 'profileviews', (err, viewcount) => { assert.ifError(err); assert(viewcount === 0); done(); @@ -1430,14 +1430,14 @@ describe('Controllers', function () { }); }); - it('should increase profile view', function (done) { - helpers.loginUser('regularJoe', 'barbar', function (err, jar) { + it('should increase profile view', (done) => { + helpers.loginUser('regularJoe', 'barbar', (err, jar) => { assert.ifError(err); - request(`${nconf.get('url')}/api/user/foo`, { jar: jar }, function (err, res) { + request(`${nconf.get('url')}/api/user/foo`, { jar: jar }, (err, res) => { assert.ifError(err); assert.equal(res.statusCode, 200); - setTimeout(function () { - user.getUserField(fooUid, 'profileviews', function (err, viewcount) { + setTimeout(() => { + user.getUserField(fooUid, 'profileviews', (err, viewcount) => { assert.ifError(err); assert(viewcount > 0); done(); @@ -1447,10 +1447,10 @@ describe('Controllers', function () { }); }); - it('should parse about me', function (done) { - user.setUserFields(fooUid, { picture: '/path/to/picture', aboutme: 'hi i am a bot' }, function (err) { + it('should parse about me', (done) => { + user.setUserFields(fooUid, { picture: '/path/to/picture', aboutme: 'hi i am a bot' }, (err) => { assert.ifError(err); - request(`${nconf.get('url')}/api/user/foo`, { json: true }, function (err, res, body) { + request(`${nconf.get('url')}/api/user/foo`, { json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert.equal(body.aboutme, 'hi i am a bot'); @@ -1460,9 +1460,9 @@ describe('Controllers', function () { }); }); - it('should not return reputation if reputation is disabled', function (done) { + it('should not return reputation if reputation is disabled', (done) => { meta.config['reputation:disabled'] = 1; - request(`${nconf.get('url')}/api/user/foo`, { json: true }, function (err, res, body) { + request(`${nconf.get('url')}/api/user/foo`, { json: true }, (err, res, body) => { meta.config['reputation:disabled'] = 0; assert.ifError(err); assert.equal(res.statusCode, 200); @@ -1471,7 +1471,7 @@ describe('Controllers', function () { }); }); - it('should only return posts that are not deleted', function (done) { + it('should only return posts that are not deleted', (done) => { var topicData; var pidToDelete; async.waterfall([ @@ -1490,12 +1490,10 @@ describe('Controllers', function () { posts.delete(pidToDelete, fooUid, next); }, function (next) { - request(`${nconf.get('url')}/api/user/foo`, { json: true }, function (err, res, body) { + request(`${nconf.get('url')}/api/user/foo`, { json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); - var contents = body.posts.map(function (p) { - return p.content; - }); + var contents = body.posts.map(p => p.content); assert(!contents.includes('1st reply')); done(); }); @@ -1503,16 +1501,16 @@ describe('Controllers', function () { ], done); }); - it('should return selected group title', function (done) { + it('should return selected group title', (done) => { groups.create({ name: 'selectedGroup', - }, function (err) { + }, (err) => { assert.ifError(err); - user.create({ username: 'groupie' }, function (err, uid) { + user.create({ username: 'groupie' }, (err, uid) => { assert.ifError(err); - groups.join('selectedGroup', uid, function (err) { + groups.join('selectedGroup', uid, (err) => { assert.ifError(err); - request(`${nconf.get('url')}/api/user/groupie`, { json: true }, function (err, res, body) { + request(`${nconf.get('url')}/api/user/groupie`, { json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(Array.isArray(body.selectedGroup)); @@ -1524,10 +1522,10 @@ describe('Controllers', function () { }); }); - it('should 404 if user does not exist', function (done) { - groups.join('administrators', fooUid, function (err) { + it('should 404 if user does not exist', (done) => { + groups.join('administrators', fooUid, (err) => { assert.ifError(err); - request(`${nconf.get('url')}/api/user/doesnotexist/edit`, { jar: jar, json: true }, function (err, res, body) { + request(`${nconf.get('url')}/api/user/doesnotexist/edit`, { jar: jar, json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 404); groups.leave('administrators', fooUid, done); @@ -1535,24 +1533,24 @@ describe('Controllers', function () { }); }); - it('should render edit/password', function (done) { - request(`${nconf.get('url')}/api/user/foo/edit/password`, { jar: jar, json: true }, function (err, res, body) { + it('should render edit/password', (done) => { + request(`${nconf.get('url')}/api/user/foo/edit/password`, { jar: jar, json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); done(); }); }); - it('should render edit/email', function (done) { - request(`${nconf.get('url')}/api/user/foo/edit/email`, { jar: jar, json: true }, function (err, res, body) { + it('should render edit/email', (done) => { + request(`${nconf.get('url')}/api/user/foo/edit/email`, { jar: jar, json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); done(); }); }); - it('should render edit/username', function (done) { - request(`${nconf.get('url')}/api/user/foo/edit/username`, { jar: jar, json: true }, function (err, res, body) { + it('should render edit/username', (done) => { + request(`${nconf.get('url')}/api/user/foo/edit/username`, { jar: jar, json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); done(); @@ -1560,16 +1558,16 @@ describe('Controllers', function () { }); }); - describe('account follow page', function () { + describe('account follow page', () => { var socketUser = require('../src/socket.io/user'); var uid; - before(function (done) { - user.create({ username: 'follower' }, function (err, _uid) { + before((done) => { + user.create({ username: 'follower' }, (err, _uid) => { assert.ifError(err); uid = _uid; - socketUser.follow({ uid: uid }, { uid: fooUid }, function (err) { + socketUser.follow({ uid: uid }, { uid: fooUid }, (err) => { assert.ifError(err); - socketUser.isFollowing({ uid: uid }, { uid: fooUid }, function (err, isFollowing) { + socketUser.isFollowing({ uid: uid }, { uid: fooUid }, (err, isFollowing) => { assert.ifError(err); assert(isFollowing); done(); @@ -1578,8 +1576,8 @@ describe('Controllers', function () { }); }); - it('should get followers page', function (done) { - request(`${nconf.get('url')}/api/user/foo/followers`, { json: true }, function (err, res, body) { + it('should get followers page', (done) => { + request(`${nconf.get('url')}/api/user/foo/followers`, { json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert.equal(body.users[0].username, 'follower'); @@ -1587,8 +1585,8 @@ describe('Controllers', function () { }); }); - it('should get following page', function (done) { - request(`${nconf.get('url')}/api/user/follower/following`, { json: true }, function (err, res, body) { + it('should get following page', (done) => { + request(`${nconf.get('url')}/api/user/follower/following`, { json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert.equal(body.users[0].username, 'foo'); @@ -1596,10 +1594,10 @@ describe('Controllers', function () { }); }); - it('should return empty after unfollow', function (done) { - socketUser.unfollow({ uid: uid }, { uid: fooUid }, function (err) { + it('should return empty after unfollow', (done) => { + socketUser.unfollow({ uid: uid }, { uid: fooUid }, (err) => { assert.ifError(err); - request(`${nconf.get('url')}/api/user/foo/followers`, { json: true }, function (err, res, body) { + request(`${nconf.get('url')}/api/user/foo/followers`, { json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert.equal(body.users.length, 0); @@ -1609,28 +1607,28 @@ describe('Controllers', function () { }); }); - describe('post redirect', function () { + describe('post redirect', () => { var jar; - before(function (done) { - helpers.loginUser('foo', 'barbar', function (err, _jar) { + before((done) => { + helpers.loginUser('foo', 'barbar', (err, _jar) => { assert.ifError(err); jar = _jar; done(); }); }); - it('should 404 for invalid pid', function (done) { - request(`${nconf.get('url')}/api/post/fail`, function (err, res) { + it('should 404 for invalid pid', (done) => { + request(`${nconf.get('url')}/api/post/fail`, (err, res) => { assert.ifError(err); assert.equal(res.statusCode, 404); done(); }); }); - it('should 403 if user does not have read privilege', function (done) { - privileges.categories.rescind(['groups:topics:read'], category.cid, 'registered-users', function (err) { + it('should 403 if user does not have read privilege', (done) => { + privileges.categories.rescind(['groups:topics:read'], category.cid, 'registered-users', (err) => { assert.ifError(err); - request(`${nconf.get('url')}/api/post/${pid}`, { jar: jar }, function (err, res) { + request(`${nconf.get('url')}/api/post/${pid}`, { jar: jar }, (err, res) => { assert.ifError(err); assert.equal(res.statusCode, 403); privileges.categories.give(['groups:topics:read'], category.cid, 'registered-users', done); @@ -1638,8 +1636,8 @@ describe('Controllers', function () { }); }); - it('should return correct post path', function (done) { - request(`${nconf.get('url')}/api/post/${pid}`, { json: true }, function (err, res, body) { + it('should return correct post path', (done) => { + request(`${nconf.get('url')}/api/post/${pid}`, { json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert.equal(res.headers['x-redirect'], '/topic/1/test-topic-title/1'); @@ -1649,9 +1647,9 @@ describe('Controllers', function () { }); }); - describe('cookie consent', function () { - it('should return relevant data in configs API route', function (done) { - request(`${nconf.get('url')}/api/config`, function (err, res, body) { + describe('cookie consent', () => { + it('should return relevant data in configs API route', (done) => { + request(`${nconf.get('url')}/api/config`, (err, res, body) => { var parsed; assert.ifError(err); assert.equal(res.statusCode, 200); @@ -1671,11 +1669,11 @@ describe('Controllers', function () { }); }); - it('response should be parseable when entries have apostrophes', function (done) { - meta.configs.set('cookieConsentMessage', 'Julian\'s Message', function (err) { + it('response should be parseable when entries have apostrophes', (done) => { + meta.configs.set('cookieConsentMessage', 'Julian\'s Message', (err) => { assert.ifError(err); - request(`${nconf.get('url')}/api/config`, function (err, res, body) { + request(`${nconf.get('url')}/api/config`, (err, res, body) => { var parsed; assert.ifError(err); assert.equal(res.statusCode, 200); @@ -1693,8 +1691,8 @@ describe('Controllers', function () { }); }); - it('should return osd data', function (done) { - request(`${nconf.get('url')}/osd.xml`, function (err, res, body) { + it('should return osd data', (done) => { + request(`${nconf.get('url')}/osd.xml`, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -1702,15 +1700,15 @@ describe('Controllers', function () { }); }); - describe('handle errors', function () { + describe('handle errors', () => { var plugins = require('../src/plugins'); - after(function (done) { + after((done) => { plugins.loadedHooks['filter:router.page'] = undefined; done(); }); - it('should handle topic malformed uri', function (done) { - request(`${nconf.get('url')}/topic/1/a%AFc`, function (err, res, body) { + it('should handle topic malformed uri', (done) => { + request(`${nconf.get('url')}/topic/1/a%AFc`, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -1718,8 +1716,8 @@ describe('Controllers', function () { }); }); - it('should handle category malformed uri', function (done) { - request(`${nconf.get('url')}/category/1/a%AFc`, function (err, res, body) { + it('should handle category malformed uri', (done) => { + request(`${nconf.get('url')}/category/1/a%AFc`, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -1727,8 +1725,8 @@ describe('Controllers', function () { }); }); - it('should handle malformed uri ', function (done) { - request(`${nconf.get('url')}/user/a%AFc`, function (err, res, body) { + it('should handle malformed uri ', (done) => { + request(`${nconf.get('url')}/user/a%AFc`, (err, res, body) => { assert.ifError(err); assert(body); assert.equal(res.statusCode, 400); @@ -1736,8 +1734,8 @@ describe('Controllers', function () { }); }); - it('should handle malformed uri in api', function (done) { - request(`${nconf.get('url')}/api/user/a%AFc`, { json: true }, function (err, res, body) { + it('should handle malformed uri in api', (done) => { + request(`${nconf.get('url')}/api/user/a%AFc`, { json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 400); assert.equal(body.error, '[[global:400.title]]'); @@ -1745,7 +1743,7 @@ describe('Controllers', function () { }); }); - it('should handle CSRF error', function (done) { + it('should handle CSRF error', (done) => { plugins.loadedHooks['filter:router.page'] = plugins.loadedHooks['filter:router.page'] || []; plugins.loadedHooks['filter:router.page'].push({ method: function (req, res, next) { @@ -1755,7 +1753,7 @@ describe('Controllers', function () { }, }); - request(`${nconf.get('url')}/users`, {}, function (err, res) { + request(`${nconf.get('url')}/users`, {}, (err, res) => { plugins.loadedHooks['filter:router.page'] = []; assert.ifError(err); assert.equal(res.statusCode, 403); @@ -1763,7 +1761,7 @@ describe('Controllers', function () { }); }); - it('should handle black-list error', function (done) { + it('should handle black-list error', (done) => { plugins.loadedHooks['filter:router.page'] = plugins.loadedHooks['filter:router.page'] || []; plugins.loadedHooks['filter:router.page'].push({ method: function (req, res, next) { @@ -1773,7 +1771,7 @@ describe('Controllers', function () { }, }); - request(`${nconf.get('url')}/users`, {}, function (err, res, body) { + request(`${nconf.get('url')}/users`, {}, (err, res, body) => { plugins.loadedHooks['filter:router.page'] = []; assert.ifError(err); assert.equal(res.statusCode, 403); @@ -1782,7 +1780,7 @@ describe('Controllers', function () { }); }); - it('should handle page redirect through error', function (done) { + it('should handle page redirect through error', (done) => { plugins.loadedHooks['filter:router.page'] = plugins.loadedHooks['filter:router.page'] || []; plugins.loadedHooks['filter:router.page'].push({ method: function (req, res, next) { @@ -1794,7 +1792,7 @@ describe('Controllers', function () { }, }); - request(`${nconf.get('url')}/users`, {}, function (err, res, body) { + request(`${nconf.get('url')}/users`, {}, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -1802,7 +1800,7 @@ describe('Controllers', function () { }); }); - it('should handle api page redirect through error', function (done) { + it('should handle api page redirect through error', (done) => { plugins.loadedHooks['filter:router.page'] = plugins.loadedHooks['filter:router.page'] || []; plugins.loadedHooks['filter:router.page'].push({ method: function (req, res, next) { @@ -1814,7 +1812,7 @@ describe('Controllers', function () { }, }); - request(`${nconf.get('url')}/api/users`, { json: true }, function (err, res, body) { + request(`${nconf.get('url')}/api/users`, { json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert.equal(res.headers['x-redirect'], '/api/popular'); @@ -1823,7 +1821,7 @@ describe('Controllers', function () { }); }); - it('should handle error page', function (done) { + it('should handle error page', (done) => { plugins.loadedHooks['filter:router.page'] = plugins.loadedHooks['filter:router.page'] || []; plugins.loadedHooks['filter:router.page'].push({ method: function (req, res, next) { @@ -1832,7 +1830,7 @@ describe('Controllers', function () { }, }); - request(`${nconf.get('url')}/users`, function (err, res, body) { + request(`${nconf.get('url')}/users`, (err, res, body) => { plugins.loadedHooks['filter:router.page'] = []; assert.ifError(err); assert.equal(res.statusCode, 500); @@ -1842,9 +1840,9 @@ describe('Controllers', function () { }); }); - describe('timeago locales', function () { - it('should load timeago locale', function (done) { - request(`${nconf.get('url')}/assets/src/modules/timeago/locales/jquery.timeago.af.js`, function (err, res, body) { + describe('timeago locales', () => { + it('should load timeago locale', (done) => { + request(`${nconf.get('url')}/assets/src/modules/timeago/locales/jquery.timeago.af.js`, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body.includes('"gelede"')); @@ -1852,16 +1850,16 @@ describe('Controllers', function () { }); }); - it('should return not found if NodeBB language exists but timeago locale does not exist', function (done) { - request(`${nconf.get('url')}/assets/src/modules/timeago/locales/jquery.timeago.ms.js`, function (err, res, body) { + it('should return not found if NodeBB language exists but timeago locale does not exist', (done) => { + request(`${nconf.get('url')}/assets/src/modules/timeago/locales/jquery.timeago.ms.js`, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 404); done(); }); }); - it('should return not found if NodeBB language does not exist', function (done) { - request(`${nconf.get('url')}/assets/src/modules/timeago/locales/jquery.timeago.muggle.js`, function (err, res, body) { + it('should return not found if NodeBB language does not exist', (done) => { + request(`${nconf.get('url')}/assets/src/modules/timeago/locales/jquery.timeago.muggle.js`, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 404); done(); @@ -1869,46 +1867,46 @@ describe('Controllers', function () { }); }); - describe('category', function () { + describe('category', () => { var jar; - before(function (done) { - helpers.loginUser('foo', 'barbar', function (err, _jar) { + before((done) => { + helpers.loginUser('foo', 'barbar', (err, _jar) => { assert.ifError(err); jar = _jar; done(); }); }); - it('should return 404 if cid is not a number', function (done) { - request(`${nconf.get('url')}/api/category/fail`, function (err, res) { + it('should return 404 if cid is not a number', (done) => { + request(`${nconf.get('url')}/api/category/fail`, (err, res) => { assert.ifError(err); assert.equal(res.statusCode, 404); done(); }); }); - it('should return 404 if topic index is not a number', function (done) { - request(`${nconf.get('url')}/api/category/${category.slug}/invalidtopicindex`, function (err, res) { + it('should return 404 if topic index is not a number', (done) => { + request(`${nconf.get('url')}/api/category/${category.slug}/invalidtopicindex`, (err, res) => { assert.ifError(err); assert.equal(res.statusCode, 404); done(); }); }); - it('should 404 if category does not exist', function (done) { - request(`${nconf.get('url')}/api/category/123123`, function (err, res) { + it('should 404 if category does not exist', (done) => { + request(`${nconf.get('url')}/api/category/123123`, (err, res) => { assert.ifError(err); assert.equal(res.statusCode, 404); done(); }); }); - it('should 404 if category is disabled', function (done) { - categories.create({ name: 'disabled' }, function (err, category) { + it('should 404 if category is disabled', (done) => { + categories.create({ name: 'disabled' }, (err, category) => { assert.ifError(err); - categories.setCategoryField(category.cid, 'disabled', 1, function (err) { + categories.setCategoryField(category.cid, 'disabled', 1, (err) => { assert.ifError(err); - request(`${nconf.get('url')}/api/category/${category.slug}`, function (err, res) { + request(`${nconf.get('url')}/api/category/${category.slug}`, (err, res) => { assert.ifError(err); assert.equal(res.statusCode, 404); done(); @@ -1917,12 +1915,12 @@ describe('Controllers', function () { }); }); - it('should return 401 if not allowed to read', function (done) { - categories.create({ name: 'hidden' }, function (err, category) { + it('should return 401 if not allowed to read', (done) => { + categories.create({ name: 'hidden' }, (err, category) => { assert.ifError(err); - privileges.categories.rescind(['groups:read'], category.cid, 'guests', function (err) { + privileges.categories.rescind(['groups:read'], category.cid, 'guests', (err) => { assert.ifError(err); - request(`${nconf.get('url')}/api/category/${category.slug}`, function (err, res) { + request(`${nconf.get('url')}/api/category/${category.slug}`, (err, res) => { assert.ifError(err); assert.equal(res.statusCode, 401); done(); @@ -1931,8 +1929,8 @@ describe('Controllers', function () { }); }); - it('should redirect if topic index is negative', function (done) { - request(`${nconf.get('url')}/api/category/${category.slug}/-10`, function (err, res) { + it('should redirect if topic index is negative', (done) => { + request(`${nconf.get('url')}/api/category/${category.slug}/-10`, (err, res) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert.ok(res.headers['x-redirect']); @@ -1940,10 +1938,10 @@ describe('Controllers', function () { }); }); - it('should 404 if page is not found', function (done) { - user.setSetting(fooUid, 'usePagination', 1, function (err) { + it('should 404 if page is not found', (done) => { + user.setSetting(fooUid, 'usePagination', 1, (err) => { assert.ifError(err); - request(`${nconf.get('url')}/api/category/${category.slug}?page=100`, { jar: jar, json: true }, function (err, res) { + request(`${nconf.get('url')}/api/category/${category.slug}?page=100`, { jar: jar, json: true }, (err, res) => { assert.ifError(err); assert.equal(res.statusCode, 404); done(); @@ -1951,8 +1949,8 @@ describe('Controllers', function () { }); }); - it('should load page 1 if req.query.page is not sent', function (done) { - request(`${nconf.get('url')}/api/category/${category.slug}`, { jar: jar, json: true }, function (err, res, body) { + it('should load page 1 if req.query.page is not sent', (done) => { + request(`${nconf.get('url')}/api/category/${category.slug}`, { jar: jar, json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert.equal(body.pagination.currentPage, 1); @@ -1960,7 +1958,7 @@ describe('Controllers', function () { }); }); - it('should sort topics by most posts', function (done) { + it('should sort topics by most posts', (done) => { async.waterfall([ function (next) { categories.create({ name: 'most-posts-category' }, next); @@ -1977,7 +1975,7 @@ describe('Controllers', function () { topics.reply({ uid: fooUid, content: 'topic 2 reply', tid: data.topicData.tid }, next); }, function (postData, next) { - request(`${nconf.get('url')}/api/category/${category.slug}?sort=most_posts`, { jar: jar, json: true }, function (err, res, body) { + request(`${nconf.get('url')}/api/category/${category.slug}?sort=most_posts`, { jar: jar, json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert.equal(body.topics[0].title, 'topic 2'); @@ -1986,14 +1984,14 @@ describe('Controllers', function () { next(); }); }, - ], function (err) { + ], (err) => { next(err); }); }, ], done); }); - it('should load a specific users topics from a category with tags', function (done) { + it('should load a specific users topics from a category with tags', (done) => { async.waterfall([ function (next) { categories.create({ name: 'filtered-category' }, next); @@ -2010,7 +2008,7 @@ describe('Controllers', function () { topics.post({ uid: fooUid, cid: category.cid, title: 'topic 3', content: 'topic 3 OP', tags: ['java', 'cpp', 'best'] }, next); }, function (data, next) { - request(`${nconf.get('url')}/api/category/${category.slug}?tag=node&author=foo`, { jar: jar, json: true }, function (err, res, body) { + request(`${nconf.get('url')}/api/category/${category.slug}?tag=node&author=foo`, { jar: jar, json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert.equal(body.topics[0].title, 'topic 2'); @@ -2018,7 +2016,7 @@ describe('Controllers', function () { }); }, function (next) { - request(`${nconf.get('url')}/api/category/${category.slug}?tag[]=java&tag[]=cpp`, { jar: jar, json: true }, function (err, res, body) { + request(`${nconf.get('url')}/api/category/${category.slug}?tag[]=java&tag[]=cpp`, { jar: jar, json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert.equal(body.topics[0].title, 'topic 3'); @@ -2026,14 +2024,14 @@ describe('Controllers', function () { next(); }); }, - ], function (err) { + ], (err) => { next(err); }); }, ], done); }); - it('should redirect if category is a link', function (done) { + it('should redirect if category is a link', (done) => { let cid; let category; async.waterfall([ @@ -2043,7 +2041,7 @@ describe('Controllers', function () { function (_category, next) { category = _category; cid = category.cid; - request(`${nconf.get('url')}/api/category/${category.slug}`, { jar: jar, json: true }, function (err, res, body) { + request(`${nconf.get('url')}/api/category/${category.slug}`, { jar: jar, json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert.equal(res.headers['x-redirect'], 'https://nodebb.org'); @@ -2055,7 +2053,7 @@ describe('Controllers', function () { categories.setCategoryField(cid, 'link', '/recent', next); }, function (next) { - request(`${nconf.get('url')}/api/category/${category.slug}`, { jar: jar, json: true }, function (err, res, body) { + request(`${nconf.get('url')}/api/category/${category.slug}`, { jar: jar, json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert.equal(res.headers['x-redirect'], '/recent'); @@ -2066,7 +2064,7 @@ describe('Controllers', function () { ], done); }); - it('should get recent topic replies from children categories', function (done) { + it('should get recent topic replies from children categories', (done) => { var parentCategory; var childCategory1; var childCategory2; @@ -2090,21 +2088,21 @@ describe('Controllers', function () { topics.post({ uid: fooUid, cid: childCategory2.cid, title: 'topic 1', content: 'topic 1 OP' }, next); }, function (data, next) { - request(`${nconf.get('url')}/api/category/${parentCategory.slug}`, { jar: jar, json: true }, function (err, res, body) { + request(`${nconf.get('url')}/api/category/${parentCategory.slug}`, { jar: jar, json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert.equal(body.children[1].posts[0].content, 'topic 1 OP'); next(); }); }, - ], function (err) { + ], (err) => { next(err); }); }, ], done); }); - it('should create 2 pages of topics', function (done) { + it('should create 2 pages of topics', (done) => { async.waterfall([ function (next) { categories.create({ name: 'category with 2 pages' }, next); @@ -2117,7 +2115,7 @@ describe('Controllers', function () { async.waterfall([ function (next) { - async.eachSeries(titles, function (title, next) { + async.eachSeries(titles, (title, next) => { topics.post({ uid: fooUid, cid: category.cid, title: title, content: 'does not really matter' }, next); }, next); }, @@ -2125,7 +2123,7 @@ describe('Controllers', function () { user.getSettings(fooUid, next); }, function (settings, next) { - request(`${nconf.get('url')}/api/category/${category.slug}`, { jar: jar, json: true }, function (err, res, body) { + request(`${nconf.get('url')}/api/category/${category.slug}`, { jar: jar, json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert.equal(body.topics.length, settings.topicsPerPage); @@ -2133,7 +2131,7 @@ describe('Controllers', function () { next(); }); }, - ], function (err) { + ], (err) => { next(err); }); }, @@ -2141,34 +2139,34 @@ describe('Controllers', function () { }); }); - describe('unread', function () { + describe('unread', () => { var jar; - before(function (done) { - helpers.loginUser('foo', 'barbar', function (err, _jar) { + before((done) => { + helpers.loginUser('foo', 'barbar', (err, _jar) => { assert.ifError(err); jar = _jar; done(); }); }); - it('should load unread page', function (done) { - request(`${nconf.get('url')}/api/unread`, { jar: jar }, function (err, res) { + it('should load unread page', (done) => { + request(`${nconf.get('url')}/api/unread`, { jar: jar }, (err, res) => { assert.ifError(err); assert.equal(res.statusCode, 200); done(); }); }); - it('should 404 if filter is invalid', function (done) { - request(`${nconf.get('url')}/api/unread/doesnotexist`, { jar: jar }, function (err, res) { + it('should 404 if filter is invalid', (done) => { + request(`${nconf.get('url')}/api/unread/doesnotexist`, { jar: jar }, (err, res) => { assert.ifError(err); assert.equal(res.statusCode, 404); done(); }); }); - it('should return total unread count', function (done) { - request(`${nconf.get('url')}/api/unread/total?filter=new`, { jar: jar }, function (err, res, body) { + it('should return total unread count', (done) => { + request(`${nconf.get('url')}/api/unread/total?filter=new`, { jar: jar }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert.equal(body, 0); @@ -2176,8 +2174,8 @@ describe('Controllers', function () { }); }); - it('should redirect if page is out of bounds', function (done) { - request(`${nconf.get('url')}/api/unread?page=-1`, { jar: jar, json: true }, function (err, res, body) { + it('should redirect if page is out of bounds', (done) => { + request(`${nconf.get('url')}/api/unread?page=-1`, { jar: jar, json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert.equal(res.headers['x-redirect'], '/unread?page=1'); @@ -2187,17 +2185,17 @@ describe('Controllers', function () { }); }); - describe('admin middlewares', function () { - it('should redirect to login', function (done) { - request(`${nconf.get('url')}//api/admin/advanced/database`, { json: true }, function (err, res, body) { + describe('admin middlewares', () => { + it('should redirect to login', (done) => { + request(`${nconf.get('url')}//api/admin/advanced/database`, { json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 401); done(); }); }); - it('should redirect to login', function (done) { - request(`${nconf.get('url')}//admin/advanced/database`, { json: true }, function (err, res, body) { + it('should redirect to login', (done) => { + request(`${nconf.get('url')}//admin/advanced/database`, { json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body.includes('Login to your account')); @@ -2206,12 +2204,12 @@ describe('Controllers', function () { }); }); - describe('composer', function () { + describe('composer', () => { var csrf_token; var jar; - before(function (done) { - helpers.loginUser('foo', 'barbar', function (err, _jar) { + before((done) => { + helpers.loginUser('foo', 'barbar', (err, _jar) => { assert.ifError(err); jar = _jar; @@ -2219,7 +2217,7 @@ describe('Controllers', function () { url: `${nconf.get('url')}/api/config`, json: true, jar: jar, - }, function (err, response, body) { + }, (err, response, body) => { assert.ifError(err); csrf_token = body.csrf_token; done(); @@ -2227,8 +2225,8 @@ describe('Controllers', function () { }); }); - it('should load the composer route', function (done) { - request(`${nconf.get('url')}/api/compose`, { json: true }, function (err, res, body) { + it('should load the composer route', (done) => { + request(`${nconf.get('url')}/api/compose`, { json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body.title); @@ -2238,7 +2236,7 @@ describe('Controllers', function () { }); }); - it('should load the composer route if disabled by plugin', function (done) { + it('should load the composer route if disabled by plugin', (done) => { function hookMethod(hookData, callback) { hookData.templateData.disabled = true; callback(null, hookData); @@ -2249,7 +2247,7 @@ describe('Controllers', function () { method: hookMethod, }); - request(`${nconf.get('url')}/api/compose`, { json: true }, function (err, res, body) { + request(`${nconf.get('url')}/api/compose`, { json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body.title); @@ -2261,7 +2259,7 @@ describe('Controllers', function () { }); }); - it('should 404 if plugin calls next', function (done) { + it('should 404 if plugin calls next', (done) => { function hookMethod(hookData, callback) { hookData.next(); } @@ -2271,7 +2269,7 @@ describe('Controllers', function () { method: hookMethod, }); - request(`${nconf.get('url')}/api/compose`, { json: true }, function (err, res, body) { + request(`${nconf.get('url')}/api/compose`, { json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 404); @@ -2281,7 +2279,7 @@ describe('Controllers', function () { }); - it('should error with invalid data', function (done) { + it('should error with invalid data', (done) => { request.post(`${nconf.get('url')}/compose`, { form: { content: 'a new reply', @@ -2290,7 +2288,7 @@ describe('Controllers', function () { headers: { 'x-csrf-token': csrf_token, }, - }, function (err, res, body) { + }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 400); request.post(`${nconf.get('url')}/compose`, { @@ -2301,7 +2299,7 @@ describe('Controllers', function () { headers: { 'x-csrf-token': csrf_token, }, - }, function (err, res, body) { + }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 400); done(); @@ -2309,7 +2307,7 @@ describe('Controllers', function () { }); }); - it('should create a new topic and reply by composer route', function (done) { + it('should create a new topic and reply by composer route', (done) => { var data = { cid: cid, title: 'no js is good', @@ -2321,7 +2319,7 @@ describe('Controllers', function () { headers: { 'x-csrf-token': csrf_token, }, - }, function (err, res) { + }, (err, res) => { assert.ifError(err); assert.equal(res.statusCode, 302); request.post(`${nconf.get('url')}/compose`, { @@ -2333,7 +2331,7 @@ describe('Controllers', function () { headers: { 'x-csrf-token': csrf_token, }, - }, function (err, res, body) { + }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 302); done(); @@ -2342,7 +2340,7 @@ describe('Controllers', function () { }); }); - after(function (done) { + after((done) => { var analytics = require('../src/analytics'); analytics.writeData(done); }); diff --git a/test/coverPhoto.js b/test/coverPhoto.js index d70690076f..498a5d56dd 100644 --- a/test/coverPhoto.js +++ b/test/coverPhoto.js @@ -7,15 +7,15 @@ var db = require('./mocks/databasemock'); var coverPhoto = require('../src/coverPhoto'); var meta = require('../src/meta'); -describe('coverPhoto', function () { - it('should get default group cover', function (done) { +describe('coverPhoto', () => { + it('should get default group cover', (done) => { meta.config['groups:defaultCovers'] = '/assets/image1.png, /assets/image2.png'; var result = coverPhoto.getDefaultGroupCover('registered-users'); assert.equal(result, `${nconf.get('relative_path')}/assets/image2.png`); done(); }); - it('should get default default profile cover', function (done) { + it('should get default default profile cover', (done) => { meta.config['profile:defaultCovers'] = ' /assets/image1.png, /assets/image2.png '; var result = coverPhoto.getDefaultProfileCover(1); assert.equal(result, `${nconf.get('relative_path')}/assets/image2.png`); diff --git a/test/database.js b/test/database.js index e54103fff5..0440c7602d 100644 --- a/test/database.js +++ b/test/database.js @@ -6,24 +6,24 @@ var nconf = require('nconf'); var db = require('./mocks/databasemock'); -describe('Test database', function () { - it('should work', function () { - assert.doesNotThrow(function () { +describe('Test database', () => { + it('should work', () => { + assert.doesNotThrow(() => { require('./mocks/databasemock'); }); }); - describe('info', function () { - it('should return info about database', function (done) { - db.info(db.client, function (err, info) { + describe('info', () => { + it('should return info about database', (done) => { + db.info(db.client, (err, info) => { assert.ifError(err); assert(info); done(); }); }); - it('should not error and return info if client is falsy', function (done) { - db.info(null, function (err, info) { + it('should not error and return info if client is falsy', (done) => { + db.info(null, (err, info) => { assert.ifError(err); assert(info); done(); @@ -31,25 +31,25 @@ describe('Test database', function () { }); }); - describe('checkCompatibility', function () { - it('should not throw', function (done) { + describe('checkCompatibility', () => { + it('should not throw', (done) => { db.checkCompatibility(done); }); - it('should return error with a too low version', function (done) { + it('should return error with a too low version', (done) => { var dbName = nconf.get('database'); if (dbName === 'redis') { - db.checkCompatibilityVersion('2.4.0', function (err) { + db.checkCompatibilityVersion('2.4.0', (err) => { assert.equal(err.message, 'Your Redis version is not new enough to support NodeBB, please upgrade Redis to v2.8.9 or higher.'); done(); }); } else if (dbName === 'mongo') { - db.checkCompatibilityVersion('1.8.0', function (err) { + db.checkCompatibilityVersion('1.8.0', (err) => { assert.equal(err.message, 'The `mongodb` package is out-of-date, please run `./nodebb setup` again.'); done(); }); } else if (dbName === 'postgres') { - db.checkCompatibilityVersion('6.3.0', function (err) { + db.checkCompatibilityVersion('6.3.0', (err) => { assert.equal(err.message, 'The `pg` package is out-of-date, please run `./nodebb setup` again.'); done(); }); diff --git a/test/database/hash.js b/test/database/hash.js index ef1eded4e9..c92e42798e 100644 --- a/test/database/hash.js +++ b/test/database/hash.js @@ -5,19 +5,19 @@ var async = require('async'); var assert = require('assert'); var db = require('../mocks/databasemock'); -describe('Hash methods', function () { +describe('Hash methods', () => { var testData = { name: 'baris', lastname: 'usakli', age: 99, }; - beforeEach(function (done) { + beforeEach((done) => { db.setObject('hashTestObject', testData, done); }); - describe('setObject()', function () { - it('should create a object', function (done) { + describe('setObject()', () => { + it('should create a object', (done) => { db.setObject('testObject1', { foo: 'baris', bar: 99 }, function (err) { assert.ifError(err); assert(arguments.length < 2); @@ -25,7 +25,7 @@ describe('Hash methods', function () { }); }); - it('should set two objects to same data', async function () { + it('should set two objects to same data', async () => { const data = { foo: 'baz', test: '1' }; await db.setObject(['multiObject1', 'multiObject2'], data); const result = await db.getObjects(['multiObject1', 'multiObject2']); @@ -33,17 +33,17 @@ describe('Hash methods', function () { assert.deepStrictEqual(result[1], data); }); - it('should do nothing if key is falsy', function (done) { - db.setObject('', { foo: 1, derp: 2 }, function (err) { + it('should do nothing if key is falsy', (done) => { + db.setObject('', { foo: 1, derp: 2 }, (err) => { assert.ifError(err); done(); }); }); - it('should do nothing if data is falsy', function (done) { - db.setObject('falsy', null, function (err) { + it('should do nothing if data is falsy', (done) => { + db.setObject('falsy', null, (err) => { assert.ifError(err); - db.exists('falsy', function (err, exists) { + db.exists('falsy', (err, exists) => { assert.ifError(err); assert.equal(exists, false); done(); @@ -51,20 +51,20 @@ describe('Hash methods', function () { }); }); - it('should not error if a key is empty string', function (done) { - db.setObject('emptyField', { '': '', b: 1 }, function (err) { + it('should not error if a key is empty string', (done) => { + db.setObject('emptyField', { '': '', b: 1 }, (err) => { assert.ifError(err); - db.getObject('emptyField', function (err, data) { + db.getObject('emptyField', (err, data) => { assert.ifError(err); done(); }); }); }); - it('should work for field names with "." in them', function (done) { - db.setObject('dotObject', { 'my.dot.field': 'foo' }, function (err) { + it('should work for field names with "." in them', (done) => { + db.setObject('dotObject', { 'my.dot.field': 'foo' }, (err) => { assert.ifError(err); - db.getObject('dotObject', function (err, data) { + db.getObject('dotObject', (err, data) => { assert.ifError(err); assert.equal(data['my.dot.field'], 'foo'); done(); @@ -72,7 +72,7 @@ describe('Hash methods', function () { }); }); - it('should set multiple keys to different okjects', async function () { + it('should set multiple keys to different okjects', async () => { const keys = ['bulkKey1', 'bulkKey2']; const data = [{ foo: '1' }, { baz: 'baz' }]; @@ -82,8 +82,8 @@ describe('Hash methods', function () { }); }); - describe('setObjectField()', function () { - it('should create a new object with field', function (done) { + describe('setObjectField()', () => { + it('should create a new object with field', (done) => { db.setObjectField('testObject2', 'name', 'ginger', function (err) { assert.ifError(err); assert(arguments.length < 2); @@ -91,7 +91,7 @@ describe('Hash methods', function () { }); }); - it('should add a new field to an object', function (done) { + it('should add a new field to an object', (done) => { db.setObjectField('testObject2', 'type', 'cat', function (err) { assert.ifError(err, null); assert(arguments.length < 2); @@ -99,7 +99,7 @@ describe('Hash methods', function () { }); }); - it('should set two objects fields to same data', async function () { + it('should set two objects fields to same data', async () => { const data = { foo: 'baz', test: '1' }; await db.setObjectField(['multiObject1', 'multiObject2'], 'myField', '2'); const result = await db.getObjects(['multiObject1', 'multiObject2']); @@ -107,10 +107,10 @@ describe('Hash methods', function () { assert.deepStrictEqual(result[1].myField, '2'); }); - it('should work for field names with "." in them', function (done) { - db.setObjectField('dotObject2', 'my.dot.field', 'foo2', function (err) { + it('should work for field names with "." in them', (done) => { + db.setObjectField('dotObject2', 'my.dot.field', 'foo2', (err) => { assert.ifError(err); - db.getObjectField('dotObject2', 'my.dot.field', function (err, value) { + db.getObjectField('dotObject2', 'my.dot.field', (err, value) => { assert.ifError(err); assert.equal(value, 'foo2'); done(); @@ -118,12 +118,12 @@ describe('Hash methods', function () { }); }); - it('should work for field names with "." in them when they are cached', function (done) { - db.setObjectField('dotObject3', 'my.dot.field', 'foo2', function (err) { + it('should work for field names with "." in them when they are cached', (done) => { + db.setObjectField('dotObject3', 'my.dot.field', 'foo2', (err) => { assert.ifError(err); - db.getObject('dotObject3', function (err, data) { + db.getObject('dotObject3', (err, data) => { assert.ifError(err); - db.getObjectField('dotObject3', 'my.dot.field', function (err, value) { + db.getObjectField('dotObject3', 'my.dot.field', (err, value) => { assert.ifError(err); assert.equal(value, 'foo2'); done(); @@ -133,8 +133,8 @@ describe('Hash methods', function () { }); }); - describe('getObject()', function () { - it('should return falsy if object does not exist', function (done) { + describe('getObject()', () => { + it('should return falsy if object does not exist', (done) => { db.getObject('doesnotexist', function (err, data) { assert.equal(err, null); assert.equal(arguments.length, 2); @@ -143,8 +143,8 @@ describe('Hash methods', function () { }); }); - it('should retrieve an object', function (done) { - db.getObject('hashTestObject', function (err, data) { + it('should retrieve an object', (done) => { + db.getObject('hashTestObject', (err, data) => { assert.equal(err, null); assert.equal(data.name, testData.name); assert.equal(data.age, testData.age); @@ -153,7 +153,7 @@ describe('Hash methods', function () { }); }); - it('should return null if key is falsy', function (done) { + it('should return null if key is falsy', (done) => { db.getObject(null, function (err, data) { assert.ifError(err); assert.equal(arguments.length, 2); @@ -163,15 +163,15 @@ describe('Hash methods', function () { }); }); - describe('getObjects()', function () { - before(function (done) { + describe('getObjects()', () => { + before((done) => { async.parallel([ async.apply(db.setObject, 'testObject4', { name: 'baris' }), async.apply(db.setObjectField, 'testObject5', 'name', 'ginger'), ], done); }); - it('should return 3 objects with correct data', function (done) { + it('should return 3 objects with correct data', (done) => { db.getObjects(['testObject4', 'testObject5', 'doesnotexist'], function (err, objects) { assert.equal(err, null); assert.equal(arguments.length, 2); @@ -184,8 +184,8 @@ describe('Hash methods', function () { }); }); - describe('getObjectField()', function () { - it('should return falsy if object does not exist', function (done) { + describe('getObjectField()', () => { + it('should return falsy if object does not exist', (done) => { db.getObjectField('doesnotexist', 'fieldName', function (err, value) { assert.equal(err, null); assert.equal(arguments.length, 2); @@ -194,7 +194,7 @@ describe('Hash methods', function () { }); }); - it('should return falsy if field does not exist', function (done) { + it('should return falsy if field does not exist', (done) => { db.getObjectField('hashTestObject', 'fieldName', function (err, value) { assert.equal(err, null); assert.equal(arguments.length, 2); @@ -203,7 +203,7 @@ describe('Hash methods', function () { }); }); - it('should get an objects field', function (done) { + it('should get an objects field', (done) => { db.getObjectField('hashTestObject', 'lastname', function (err, value) { assert.equal(err, null); assert.equal(arguments.length, 2); @@ -212,7 +212,7 @@ describe('Hash methods', function () { }); }); - it('should return null if key is falsy', function (done) { + it('should return null if key is falsy', (done) => { db.getObjectField(null, 'test', function (err, data) { assert.ifError(err); assert.equal(arguments.length, 2); @@ -227,8 +227,8 @@ describe('Hash methods', function () { }); }); - describe('getObjectFields()', function () { - it('should return an object with falsy values', function (done) { + describe('getObjectFields()', () => { + it('should return an object with falsy values', (done) => { db.getObjectFields('doesnotexist', ['field1', 'field2'], function (err, object) { assert.equal(err, null); assert.equal(arguments.length, 2); @@ -239,7 +239,7 @@ describe('Hash methods', function () { }); }); - it('should return an object with correct fields', function (done) { + it('should return an object with correct fields', (done) => { db.getObjectFields('hashTestObject', ['lastname', 'age', 'field1'], function (err, object) { assert.equal(err, null); assert.equal(arguments.length, 2); @@ -251,7 +251,7 @@ describe('Hash methods', function () { }); }); - it('should return null if key is falsy', function (done) { + it('should return null if key is falsy', (done) => { db.getObjectFields(null, ['test', 'foo'], function (err, data) { assert.ifError(err); assert.equal(arguments.length, 2); @@ -261,15 +261,15 @@ describe('Hash methods', function () { }); }); - describe('getObjectsFields()', function () { - before(function (done) { + describe('getObjectsFields()', () => { + before((done) => { async.parallel([ async.apply(db.setObject, 'testObject8', { name: 'baris', age: 99 }), async.apply(db.setObject, 'testObject9', { name: 'ginger', age: 3 }), ], done); }); - it('should return an array of objects with correct values', function (done) { + it('should return an array of objects with correct values', (done) => { db.getObjectsFields(['testObject8', 'testObject9', 'doesnotexist'], ['name', 'age'], function (err, objects) { assert.equal(err, null); assert.equal(arguments.length, 2); @@ -284,8 +284,8 @@ describe('Hash methods', function () { }); }); - it('should return undefined for all fields if object does not exist', function (done) { - db.getObjectsFields(['doesnotexist1', 'doesnotexist2'], ['name', 'age'], function (err, data) { + it('should return undefined for all fields if object does not exist', (done) => { + db.getObjectsFields(['doesnotexist1', 'doesnotexist2'], ['name', 'age'], (err, data) => { assert.ifError(err); assert(Array.isArray(data)); assert.equal(data[0].name, null); @@ -297,8 +297,8 @@ describe('Hash methods', function () { }); }); - describe('getObjectKeys()', function () { - it('should return an empty array for a object that does not exist', function (done) { + describe('getObjectKeys()', () => { + it('should return an empty array for a object that does not exist', (done) => { db.getObjectKeys('doesnotexist', function (err, keys) { assert.equal(err, null); assert.equal(arguments.length, 2); @@ -307,12 +307,12 @@ describe('Hash methods', function () { }); }); - it('should return an array of keys for the object\'s fields', function (done) { + it('should return an array of keys for the object\'s fields', (done) => { db.getObjectKeys('hashTestObject', function (err, keys) { assert.equal(err, null); assert.equal(arguments.length, 2); assert.equal(Array.isArray(keys) && keys.length === 3, true); - keys.forEach(function (key) { + keys.forEach((key) => { assert.notEqual(['name', 'lastname', 'age'].indexOf(key), -1); }); done(); @@ -320,8 +320,8 @@ describe('Hash methods', function () { }); }); - describe('getObjectValues()', function () { - it('should return an empty array for a object that does not exist', function (done) { + describe('getObjectValues()', () => { + it('should return an empty array for a object that does not exist', (done) => { db.getObjectValues('doesnotexist', function (err, values) { assert.equal(err, null); assert.equal(arguments.length, 2); @@ -330,7 +330,7 @@ describe('Hash methods', function () { }); }); - it('should return an array of values for the object\'s fields', function (done) { + it('should return an array of values for the object\'s fields', (done) => { db.getObjectValues('hashTestObject', function (err, values) { assert.equal(err, null); assert.equal(arguments.length, 2); @@ -341,8 +341,8 @@ describe('Hash methods', function () { }); }); - describe('isObjectField()', function () { - it('should return false if object does not exist', function (done) { + describe('isObjectField()', () => { + it('should return false if object does not exist', (done) => { db.isObjectField('doesnotexist', 'field1', function (err, value) { assert.equal(err, null); assert.equal(arguments.length, 2); @@ -351,7 +351,7 @@ describe('Hash methods', function () { }); }); - it('should return false if field does not exist', function (done) { + it('should return false if field does not exist', (done) => { db.isObjectField('hashTestObject', 'field1', function (err, value) { assert.equal(err, null); assert.equal(arguments.length, 2); @@ -360,7 +360,7 @@ describe('Hash methods', function () { }); }); - it('should return true if field exists', function (done) { + it('should return true if field exists', (done) => { db.isObjectField('hashTestObject', 'name', function (err, value) { assert.equal(err, null); assert.equal(arguments.length, 2); @@ -371,8 +371,8 @@ describe('Hash methods', function () { }); - describe('isObjectFields()', function () { - it('should return an array of false if object does not exist', function (done) { + describe('isObjectFields()', () => { + it('should return an array of false if object does not exist', (done) => { db.isObjectFields('doesnotexist', ['field1', 'field2'], function (err, values) { assert.equal(err, null); assert.equal(arguments.length, 2); @@ -381,7 +381,7 @@ describe('Hash methods', function () { }); }); - it('should return false if field does not exist', function (done) { + it('should return false if field does not exist', (done) => { db.isObjectFields('hashTestObject', ['name', 'age', 'field1'], function (err, values) { assert.equal(err, null); assert.equal(arguments.length, 2); @@ -391,16 +391,16 @@ describe('Hash methods', function () { }); }); - describe('deleteObjectField()', function () { - before(function (done) { + describe('deleteObjectField()', () => { + before((done) => { db.setObject('testObject10', { foo: 'bar', delete: 'this', delete1: 'this', delete2: 'this' }, done); }); - it('should delete an objects field', function (done) { + it('should delete an objects field', (done) => { db.deleteObjectField('testObject10', 'delete', function (err) { assert.ifError(err); assert(arguments.length < 2); - db.isObjectField('testObject10', 'delete', function (err, isField) { + db.isObjectField('testObject10', 'delete', (err, isField) => { assert.ifError(err); assert.equal(isField, false); done(); @@ -408,14 +408,14 @@ describe('Hash methods', function () { }); }); - it('should delete multiple fields of the object', function (done) { + it('should delete multiple fields of the object', (done) => { db.deleteObjectFields('testObject10', ['delete1', 'delete2'], function (err) { assert.ifError(err); assert(arguments.length < 2); async.parallel({ delete1: async.apply(db.isObjectField, 'testObject10', 'delete1'), delete2: async.apply(db.isObjectField, 'testObject10', 'delete2'), - }, function (err, results) { + }, (err, results) => { assert.ifError(err); assert.equal(results.delete1, false); assert.equal(results.delete2, false); @@ -424,7 +424,7 @@ describe('Hash methods', function () { }); }); - it('should delete multiple fields of multiple objects', async function () { + it('should delete multiple fields of multiple objects', async () => { await db.setObject('deleteFields1', { foo: 'foo1', baz: '2' }); await db.setObject('deleteFields2', { foo: 'foo2', baz: '3' }); await db.deleteObjectFields(['deleteFields1', 'deleteFields2'], ['baz']); @@ -438,45 +438,45 @@ describe('Hash methods', function () { await db.deleteObjectFields('someKey', []); }); - it('should not error if key is undefined', function (done) { - db.deleteObjectField(undefined, 'someField', function (err) { + it('should not error if key is undefined', (done) => { + db.deleteObjectField(undefined, 'someField', (err) => { assert.ifError(err); done(); }); }); - it('should not error if key is null', function (done) { - db.deleteObjectField(null, 'someField', function (err) { + it('should not error if key is null', (done) => { + db.deleteObjectField(null, 'someField', (err) => { assert.ifError(err); done(); }); }); - it('should not error if field is undefined', function (done) { - db.deleteObjectField('someKey', undefined, function (err) { + it('should not error if field is undefined', (done) => { + db.deleteObjectField('someKey', undefined, (err) => { assert.ifError(err); done(); }); }); - it('should not error if one of the fields is undefined', async function () { + it('should not error if one of the fields is undefined', async () => { await db.deleteObjectFields('someKey', ['best', undefined]); }); - it('should not error if field is null', function (done) { - db.deleteObjectField('someKey', null, function (err) { + it('should not error if field is null', (done) => { + db.deleteObjectField('someKey', null, (err) => { assert.ifError(err); done(); }); }); }); - describe('incrObjectField()', function () { - before(function (done) { + describe('incrObjectField()', () => { + before((done) => { db.setObject('testObject11', { age: 99 }, done); }); - it('should set an objects field to 1 if object does not exist', function (done) { + it('should set an objects field to 1 if object does not exist', (done) => { db.incrObjectField('testObject12', 'field1', function (err, newValue) { assert.equal(err, null); assert.equal(arguments.length, 2); @@ -485,7 +485,7 @@ describe('Hash methods', function () { }); }); - it('should increment an object fields by 1 and return it', function (done) { + it('should increment an object fields by 1 and return it', (done) => { db.incrObjectField('testObject11', 'age', function (err, newValue) { assert.equal(err, null); assert.equal(arguments.length, 2); @@ -495,12 +495,12 @@ describe('Hash methods', function () { }); }); - describe('decrObjectField()', function () { - before(function (done) { + describe('decrObjectField()', () => { + before((done) => { db.setObject('testObject13', { age: 99 }, done); }); - it('should set an objects field to -1 if object does not exist', function (done) { + it('should set an objects field to -1 if object does not exist', (done) => { db.decrObjectField('testObject14', 'field1', function (err, newValue) { assert.equal(err, null); assert.equal(arguments.length, 2); @@ -509,7 +509,7 @@ describe('Hash methods', function () { }); }); - it('should decrement an object fields by 1 and return it', function (done) { + it('should decrement an object fields by 1 and return it', (done) => { db.decrObjectField('testObject13', 'age', function (err, newValue) { assert.equal(err, null); assert.equal(arguments.length, 2); @@ -518,8 +518,8 @@ describe('Hash methods', function () { }); }); - it('should decrement multiple objects field by 1 and return an array of new values', function (done) { - db.decrObjectField(['testObject13', 'testObject14', 'decrTestObject'], 'age', function (err, data) { + it('should decrement multiple objects field by 1 and return an array of new values', (done) => { + db.decrObjectField(['testObject13', 'testObject14', 'decrTestObject'], 'age', (err, data) => { assert.ifError(err); assert.equal(data[0], 97); assert.equal(data[1], -1); @@ -529,12 +529,12 @@ describe('Hash methods', function () { }); }); - describe('incrObjectFieldBy()', function () { - before(function (done) { + describe('incrObjectFieldBy()', () => { + before((done) => { db.setObject('testObject15', { age: 100 }, done); }); - it('should set an objects field to 5 if object does not exist', function (done) { + it('should set an objects field to 5 if object does not exist', (done) => { db.incrObjectFieldBy('testObject16', 'field1', 5, function (err, newValue) { assert.ifError(err); assert.equal(arguments.length, 2); @@ -543,7 +543,7 @@ describe('Hash methods', function () { }); }); - it('should increment an object fields by passed in value and return it', function (done) { + it('should increment an object fields by passed in value and return it', (done) => { db.incrObjectFieldBy('testObject15', 'age', 11, function (err, newValue) { assert.ifError(err); assert.equal(arguments.length, 2); @@ -552,19 +552,19 @@ describe('Hash methods', function () { }); }); - it('should increment an object fields by passed in value and return it', function (done) { - db.incrObjectFieldBy('testObject15', 'age', '11', function (err, newValue) { + it('should increment an object fields by passed in value and return it', (done) => { + db.incrObjectFieldBy('testObject15', 'age', '11', (err, newValue) => { assert.ifError(err); assert.equal(newValue, 122); done(); }); }); - it('should return null if value is NaN', function (done) { - db.incrObjectFieldBy('testObject15', 'lastonline', 'notanumber', function (err, newValue) { + it('should return null if value is NaN', (done) => { + db.incrObjectFieldBy('testObject15', 'lastonline', 'notanumber', (err, newValue) => { assert.ifError(err); assert.strictEqual(newValue, null); - db.isObjectField('testObject15', 'lastonline', function (err, isField) { + db.isObjectField('testObject15', 'lastonline', (err, isField) => { assert.ifError(err); assert(!isField); done(); diff --git a/test/database/keys.js b/test/database/keys.js index bff084376f..1d21d2ecd2 100644 --- a/test/database/keys.js +++ b/test/database/keys.js @@ -5,12 +5,12 @@ var async = require('async'); var assert = require('assert'); var db = require('../mocks/databasemock'); -describe('Key methods', function () { - beforeEach(function (done) { +describe('Key methods', () => { + beforeEach((done) => { db.set('testKey', 'testValue', done); }); - it('should set a key without error', function (done) { + it('should set a key without error', (done) => { db.set('testKey', 'testValue', function (err) { assert.ifError(err); assert(arguments.length < 2); @@ -18,7 +18,7 @@ describe('Key methods', function () { }); }); - it('should get a key without error', function (done) { + it('should get a key without error', (done) => { db.get('testKey', function (err, value) { assert.ifError(err); assert.equal(arguments.length, 2); @@ -27,15 +27,15 @@ describe('Key methods', function () { }); }); - it('should return null if key does not exist', function (done) { - db.get('doesnotexist', function (err, value) { + it('should return null if key does not exist', (done) => { + db.get('doesnotexist', (err, value) => { assert.ifError(err); assert.equal(value, null); done(); }); }); - it('should return true if key exist', function (done) { + it('should return true if key exist', (done) => { db.exists('testKey', function (err, exists) { assert.ifError(err); assert.equal(arguments.length, 2); @@ -44,7 +44,7 @@ describe('Key methods', function () { }); }); - it('should return false if key does not exist', function (done) { + it('should return false if key does not exist', (done) => { db.exists('doesnotexist', function (err, exists) { assert.ifError(err); assert.equal(arguments.length, 2); @@ -53,16 +53,16 @@ describe('Key methods', function () { }); }); - it('should work for an array of keys', function (done) { - db.exists(['testKey', 'doesnotexist'], function (err, exists) { + it('should work for an array of keys', (done) => { + db.exists(['testKey', 'doesnotexist'], (err, exists) => { assert.ifError(err); assert.deepStrictEqual(exists, [true, false]); done(); }); }); - describe('scan', function () { - it('should scan keys for pattern', async function () { + describe('scan', () => { + it('should scan keys for pattern', async () => { await db.sortedSetAdd('ip:123:uid', 1, 'a'); await db.sortedSetAdd('ip:123:uid', 2, 'b'); await db.sortedSetAdd('ip:124:uid', 2, 'b'); @@ -76,12 +76,12 @@ describe('Key methods', function () { }); }); - it('should delete a key without error', function (done) { + it('should delete a key without error', (done) => { db.delete('testKey', function (err) { assert.ifError(err); assert(arguments.length < 2); - db.get('testKey', function (err, value) { + db.get('testKey', (err, value) => { assert.ifError(err); assert.equal(false, !!value); done(); @@ -89,11 +89,11 @@ describe('Key methods', function () { }); }); - it('should return false if key was deleted', function (done) { + it('should return false if key was deleted', (done) => { db.delete('testKey', function (err) { assert.ifError(err); assert(arguments.length < 2); - db.exists('testKey', function (err, exists) { + db.exists('testKey', (err, exists) => { assert.ifError(err); assert.strictEqual(exists, false); done(); @@ -101,7 +101,7 @@ describe('Key methods', function () { }); }); - it('should delete all keys passed in', function (done) { + it('should delete all keys passed in', (done) => { async.parallel([ function (next) { db.set('key1', 'value1', next); @@ -109,7 +109,7 @@ describe('Key methods', function () { function (next) { db.set('key2', 'value2', next); }, - ], function (err) { + ], (err) => { if (err) { return done(err); } @@ -123,7 +123,7 @@ describe('Key methods', function () { key2exists: function (next) { db.exists('key2', next); }, - }, function (err, results) { + }, (err, results) => { assert.ifError(err); assert.equal(results.key1exists, false); assert.equal(results.key2exists, false); @@ -133,7 +133,7 @@ describe('Key methods', function () { }); }); - it('should delete all sorted set elements', function (done) { + it('should delete all sorted set elements', (done) => { async.parallel([ function (next) { db.sortedSetAdd('deletezset', 1, 'value1', next); @@ -141,11 +141,11 @@ describe('Key methods', function () { function (next) { db.sortedSetAdd('deletezset', 2, 'value2', next); }, - ], function (err) { + ], (err) => { if (err) { return done(err); } - db.delete('deletezset', function (err) { + db.delete('deletezset', (err) => { assert.ifError(err); async.parallel({ key1exists: function (next) { @@ -154,7 +154,7 @@ describe('Key methods', function () { key2exists: function (next) { db.isSortedSetMember('deletezset', 'value2', next); }, - }, function (err, results) { + }, (err, results) => { assert.ifError(err); assert.equal(results.key1exists, false); assert.equal(results.key2exists, false); @@ -164,30 +164,30 @@ describe('Key methods', function () { }); }); - describe('increment', function () { - it('should initialize key to 1', function (done) { - db.increment('keyToIncrement', function (err, value) { + describe('increment', () => { + it('should initialize key to 1', (done) => { + db.increment('keyToIncrement', (err, value) => { assert.ifError(err); assert.strictEqual(parseInt(value, 10), 1); done(); }); }); - it('should increment key to 2', function (done) { - db.increment('keyToIncrement', function (err, value) { + it('should increment key to 2', (done) => { + db.increment('keyToIncrement', (err, value) => { assert.ifError(err); assert.strictEqual(parseInt(value, 10), 2); done(); }); }); - it('should set then increment a key', function (done) { - db.set('myIncrement', 1, function (err) { + it('should set then increment a key', (done) => { + db.set('myIncrement', 1, (err) => { assert.ifError(err); - db.increment('myIncrement', function (err, value) { + db.increment('myIncrement', (err, value) => { assert.ifError(err); assert.equal(value, 2); - db.get('myIncrement', function (err, value) { + db.get('myIncrement', (err, value) => { assert.ifError(err); assert.equal(value, 2); done(); @@ -196,15 +196,15 @@ describe('Key methods', function () { }); }); - it('should return the correct value', function (done) { - db.increment('testingCache', function (err) { + it('should return the correct value', (done) => { + db.increment('testingCache', (err) => { assert.ifError(err); - db.get('testingCache', function (err, value) { + db.get('testingCache', (err, value) => { assert.ifError(err); assert.equal(value, 1); - db.increment('testingCache', function (err) { + db.increment('testingCache', (err) => { assert.ifError(err); - db.get('testingCache', function (err, value) { + db.get('testingCache', (err, value) => { assert.ifError(err); assert.equal(value, 2); done(); @@ -215,9 +215,9 @@ describe('Key methods', function () { }); }); - describe('rename', function () { - it('should rename key to new name', function (done) { - db.set('keyOldName', 'renamedKeyValue', function (err) { + describe('rename', () => { + it('should rename key to new name', (done) => { + db.set('keyOldName', 'renamedKeyValue', (err) => { if (err) { return done(err); } @@ -225,7 +225,7 @@ describe('Key methods', function () { assert.ifError(err); assert(arguments.length < 2); - db.get('keyNewName', function (err, value) { + db.get('keyNewName', (err, value) => { assert.ifError(err); assert.equal(value, 'renamedKeyValue'); done(); @@ -234,15 +234,15 @@ describe('Key methods', function () { }); }); - it('should rename multiple keys', function (done) { - db.sortedSetAdd('zsettorename', [1, 2, 3], ['value1', 'value2', 'value3'], function (err) { + it('should rename multiple keys', (done) => { + db.sortedSetAdd('zsettorename', [1, 2, 3], ['value1', 'value2', 'value3'], (err) => { assert.ifError(err); - db.rename('zsettorename', 'newzsetname', function (err) { + db.rename('zsettorename', 'newzsetname', (err) => { assert.ifError(err); - db.exists('zsettorename', function (err, exists) { + db.exists('zsettorename', (err, exists) => { assert.ifError(err); assert(!exists); - db.getSortedSetRange('newzsetname', 0, -1, function (err, values) { + db.getSortedSetRange('newzsetname', 0, -1, (err, values) => { assert.ifError(err); assert.deepEqual(['value1', 'value2', 'value3'], values); done(); @@ -252,10 +252,10 @@ describe('Key methods', function () { }); }); - it('should not error if old key does not exist', function (done) { - db.rename('doesnotexist', 'anotherdoesnotexist', function (err) { + it('should not error if old key does not exist', (done) => { + db.rename('doesnotexist', 'anotherdoesnotexist', (err) => { assert.ifError(err); - db.exists('anotherdoesnotexist', function (err, exists) { + db.exists('anotherdoesnotexist', (err, exists) => { assert.ifError(err); assert(!exists); done(); @@ -264,19 +264,19 @@ describe('Key methods', function () { }); }); - describe('type', function () { - it('should return null if key does not exist', function (done) { - db.type('doesnotexist', function (err, type) { + describe('type', () => { + it('should return null if key does not exist', (done) => { + db.type('doesnotexist', (err, type) => { assert.ifError(err); assert.strictEqual(type, null); done(); }); }); - it('should return hash as type', function (done) { - db.setObject('typeHash', { foo: 1 }, function (err) { + it('should return hash as type', (done) => { + db.setObject('typeHash', { foo: 1 }, (err) => { assert.ifError(err); - db.type('typeHash', function (err, type) { + db.type('typeHash', (err, type) => { assert.ifError(err); assert.equal(type, 'hash'); done(); @@ -284,10 +284,10 @@ describe('Key methods', function () { }); }); - it('should return zset as type', function (done) { - db.sortedSetAdd('typeZset', 123, 'value1', function (err) { + it('should return zset as type', (done) => { + db.sortedSetAdd('typeZset', 123, 'value1', (err) => { assert.ifError(err); - db.type('typeZset', function (err, type) { + db.type('typeZset', (err, type) => { assert.ifError(err); assert.equal(type, 'zset'); done(); @@ -295,10 +295,10 @@ describe('Key methods', function () { }); }); - it('should return set as type', function (done) { - db.setAdd('typeSet', 'value1', function (err) { + it('should return set as type', (done) => { + db.setAdd('typeSet', 'value1', (err) => { assert.ifError(err); - db.type('typeSet', function (err, type) { + db.type('typeSet', (err, type) => { assert.ifError(err); assert.equal(type, 'set'); done(); @@ -306,10 +306,10 @@ describe('Key methods', function () { }); }); - it('should return list as type', function (done) { - db.listAppend('typeList', 'value1', function (err) { + it('should return list as type', (done) => { + db.listAppend('typeList', 'value1', (err) => { assert.ifError(err); - db.type('typeList', function (err, type) { + db.type('typeList', (err, type) => { assert.ifError(err); assert.equal(type, 'list'); done(); @@ -317,10 +317,10 @@ describe('Key methods', function () { }); }); - it('should return string as type', function (done) { - db.set('typeString', 'value1', function (err) { + it('should return string as type', (done) => { + db.set('typeString', 'value1', (err) => { assert.ifError(err); - db.type('typeString', function (err, type) { + db.type('typeString', (err, type) => { assert.ifError(err); assert.equal(type, 'string'); done(); @@ -328,10 +328,10 @@ describe('Key methods', function () { }); }); - it('should expire a key using seconds', function (done) { - db.expire('testKey', 86400, function (err) { + it('should expire a key using seconds', (done) => { + db.expire('testKey', 86400, (err) => { assert.ifError(err); - db.ttl('testKey', function (err, ttl) { + db.ttl('testKey', (err, ttl) => { assert.ifError(err); assert.equal(Math.round(86400 / 1000), Math.round(ttl / 1000)); done(); @@ -339,10 +339,10 @@ describe('Key methods', function () { }); }); - it('should expire a key using milliseconds', function (done) { - db.pexpire('testKey', 86400000, function (err) { + it('should expire a key using milliseconds', (done) => { + db.pexpire('testKey', 86400000, (err) => { assert.ifError(err); - db.pttl('testKey', function (err, pttl) { + db.pttl('testKey', (err, pttl) => { assert.ifError(err); assert.equal(Math.round(86400000 / 1000000), Math.round(pttl / 1000000)); done(); diff --git a/test/database/list.js b/test/database/list.js index b432099709..008dc98384 100644 --- a/test/database/list.js +++ b/test/database/list.js @@ -5,9 +5,9 @@ var async = require('async'); var assert = require('assert'); var db = require('../mocks/databasemock'); -describe('List methods', function () { - describe('listAppend()', function () { - it('should append to a list', function (done) { +describe('List methods', () => { + describe('listAppend()', () => { + it('should append to a list', (done) => { db.listAppend('testList1', 5, function (err) { assert.ifError(err); assert.equal(arguments.length, 1); @@ -15,16 +15,16 @@ describe('List methods', function () { }); }); - it('should not add anyhing if key is falsy', function (done) { - db.listAppend(null, 3, function (err) { + it('should not add anyhing if key is falsy', (done) => { + db.listAppend(null, 3, (err) => { assert.ifError(err); done(); }); }); }); - describe('listPrepend()', function () { - it('should prepend to a list', function (done) { + describe('listPrepend()', () => { + it('should prepend to a list', (done) => { db.listPrepend('testList2', 3, function (err) { assert.equal(err, null); assert.equal(arguments.length, 1); @@ -32,7 +32,7 @@ describe('List methods', function () { }); }); - it('should prepend 2 more elements to a list', function (done) { + it('should prepend 2 more elements to a list', (done) => { async.series([ function (next) { db.listPrepend('testList2', 2, next); @@ -40,22 +40,22 @@ describe('List methods', function () { function (next) { db.listPrepend('testList2', 1, next); }, - ], function (err) { + ], (err) => { assert.equal(err, null); done(); }); }); - it('should not add anyhing if key is falsy', function (done) { - db.listPrepend(null, 3, function (err) { + it('should not add anyhing if key is falsy', (done) => { + db.listPrepend(null, 3, (err) => { assert.ifError(err); done(); }); }); }); - describe('getListRange()', function () { - before(function (done) { + describe('getListRange()', () => { + before((done) => { async.series([ function (next) { db.listAppend('testList3', 7, next); @@ -69,7 +69,7 @@ describe('List methods', function () { ], done); }); - it('should return an empty list', function (done) { + it('should return an empty list', (done) => { db.getListRange('doesnotexist', 0, -1, function (err, list) { assert.equal(err, null); assert.equal(arguments.length, 2); @@ -79,8 +79,8 @@ describe('List methods', function () { }); }); - it('should return a list with one element', function (done) { - db.getListRange('testList4', 0, 0, function (err, list) { + it('should return a list with one element', (done) => { + db.getListRange('testList4', 0, 0, (err, list) => { assert.equal(err, null); assert.equal(Array.isArray(list), true); assert.equal(list[0], 5); @@ -88,8 +88,8 @@ describe('List methods', function () { }); }); - it('should return a list with 2 elements 3, 7', function (done) { - db.getListRange('testList3', 0, -1, function (err, list) { + it('should return a list with 2 elements 3, 7', (done) => { + db.getListRange('testList3', 0, -1, (err, list) => { assert.equal(err, null); assert.equal(Array.isArray(list), true); assert.equal(list.length, 2); @@ -98,8 +98,8 @@ describe('List methods', function () { }); }); - it('should not get anything if key is falsy', function (done) { - db.getListRange(null, 0, -1, function (err, data) { + it('should not get anything if key is falsy', (done) => { + db.getListRange(null, 0, -1, (err, data) => { assert.ifError(err); assert.equal(data, undefined); done(); @@ -107,8 +107,8 @@ describe('List methods', function () { }); }); - describe('listRemoveLast()', function () { - before(function (done) { + describe('listRemoveLast()', () => { + before((done) => { async.series([ function (next) { db.listAppend('testList7', 12, next); @@ -119,7 +119,7 @@ describe('List methods', function () { ], done); }); - it('should remove the last element of list and return it', function (done) { + it('should remove the last element of list and return it', (done) => { db.listRemoveLast('testList7', function (err, lastElement) { assert.equal(err, null); assert.equal(arguments.length, 2); @@ -128,16 +128,16 @@ describe('List methods', function () { }); }); - it('should not remove anyhing if key is falsy', function (done) { - db.listRemoveLast(null, function (err) { + it('should not remove anyhing if key is falsy', (done) => { + db.listRemoveLast(null, (err) => { assert.ifError(err); done(); }); }); }); - describe('listRemoveAll()', function () { - before(function (done) { + describe('listRemoveAll()', () => { + before((done) => { async.series([ async.apply(db.listAppend, 'testList5', 1), async.apply(db.listAppend, 'testList5', 1), @@ -147,12 +147,12 @@ describe('List methods', function () { ], done); }); - it('should remove all the matching elements of list', function (done) { + it('should remove all the matching elements of list', (done) => { db.listRemoveAll('testList5', '1', function (err) { assert.equal(err, null); assert.equal(arguments.length, 1); - db.getListRange('testList5', 0, -1, function (err, list) { + db.getListRange('testList5', 0, -1, (err, list) => { assert.equal(err, null); assert.equal(Array.isArray(list), true); assert.equal(list.length, 2); @@ -162,20 +162,20 @@ describe('List methods', function () { }); }); - it('should not remove anyhing if key is falsy', function (done) { - db.listRemoveAll(null, 3, function (err) { + it('should not remove anyhing if key is falsy', (done) => { + db.listRemoveAll(null, 3, (err) => { assert.ifError(err); done(); }); }); }); - describe('listTrim()', function () { - it('should trim list to a certain range', function (done) { + describe('listTrim()', () => { + it('should trim list to a certain range', (done) => { var list = ['1', '2', '3', '4', '5']; - async.eachSeries(list, function (value, next) { + async.eachSeries(list, (value, next) => { db.listAppend('testList6', value, next); - }, function (err) { + }, (err) => { if (err) { return done(err); } @@ -183,7 +183,7 @@ describe('List methods', function () { db.listTrim('testList6', 0, 2, function (err) { assert.equal(err, null); assert.equal(arguments.length, 1); - db.getListRange('testList6', 0, -1, function (err, list) { + db.getListRange('testList6', 0, -1, (err, list) => { assert.equal(err, null); assert.equal(list.length, 3); assert.deepEqual(list, ['1', '2', '3']); @@ -193,21 +193,21 @@ describe('List methods', function () { }); }); - it('should not add anyhing if key is falsy', function (done) { - db.listTrim(null, 0, 3, function (err) { + it('should not add anyhing if key is falsy', (done) => { + db.listTrim(null, 0, 3, (err) => { assert.ifError(err); done(); }); }); }); - describe('listLength', function () { - it('should get the length of a list', function (done) { - db.listAppend('getLengthList', 1, function (err) { + describe('listLength', () => { + it('should get the length of a list', (done) => { + db.listAppend('getLengthList', 1, (err) => { assert.ifError(err); - db.listAppend('getLengthList', 2, function (err) { + db.listAppend('getLengthList', 2, (err) => { assert.ifError(err); - db.listLength('getLengthList', function (err, length) { + db.listLength('getLengthList', (err, length) => { assert.ifError(err); assert.equal(length, 2); done(); @@ -216,8 +216,8 @@ describe('List methods', function () { }); }); - it('should return 0 if list does not have any elements', function (done) { - db.listLength('doesnotexist', function (err, length) { + it('should return 0 if list does not have any elements', (done) => { + db.listLength('doesnotexist', (err, length) => { assert.ifError(err); assert.strictEqual(length, 0); done(); diff --git a/test/database/sets.js b/test/database/sets.js index 2ddc465f58..8f2e8d3832 100644 --- a/test/database/sets.js +++ b/test/database/sets.js @@ -5,9 +5,9 @@ var async = require('async'); var assert = require('assert'); var db = require('../mocks/databasemock'); -describe('Set methods', function () { - describe('setAdd()', function () { - it('should add to a set', function (done) { +describe('Set methods', () => { + describe('setAdd()', () => { + it('should add to a set', (done) => { db.setAdd('testSet1', 5, function (err) { assert.equal(err, null); assert.equal(arguments.length, 1); @@ -15,7 +15,7 @@ describe('Set methods', function () { }); }); - it('should add an array to a set', function (done) { + it('should add an array to a set', (done) => { db.setAdd('testSet1', [1, 2, 3, 4], function (err) { assert.equal(err, null); assert.equal(arguments.length, 1); @@ -23,7 +23,7 @@ describe('Set methods', function () { }); }); - it('should not do anything if values array is empty', async function () { + it('should not do anything if values array is empty', async () => { await db.setAdd('emptyArraySet', []); const members = await db.getSetMembers('emptyArraySet'); const exists = await db.exists('emptyArraySet'); @@ -32,12 +32,12 @@ describe('Set methods', function () { }); }); - describe('getSetMembers()', function () { - before(function (done) { + describe('getSetMembers()', () => { + before((done) => { db.setAdd('testSet2', [1, 2, 3, 4, 5], done); }); - it('should return an empty set', function (done) { + it('should return an empty set', (done) => { db.getSetMembers('doesnotexist', function (err, set) { assert.equal(err, null); assert.equal(arguments.length, 2); @@ -47,11 +47,11 @@ describe('Set methods', function () { }); }); - it('should return a set with all elements', function (done) { - db.getSetMembers('testSet2', function (err, set) { + it('should return a set with all elements', (done) => { + db.getSetMembers('testSet2', (err, set) => { assert.equal(err, null); assert.equal(set.length, 5); - set.forEach(function (value) { + set.forEach((value) => { assert.notEqual(['1', '2', '3', '4', '5'].indexOf(value), -1); }); @@ -60,8 +60,8 @@ describe('Set methods', function () { }); }); - describe('setsAdd()', function () { - it('should add to multiple sets', function (done) { + describe('setsAdd()', () => { + it('should add to multiple sets', (done) => { db.setsAdd(['set1', 'set2'], 'value', function (err) { assert.equal(err, null); assert.equal(arguments.length, 1); @@ -69,20 +69,20 @@ describe('Set methods', function () { }); }); - it('should not error if keys is empty array', function (done) { - db.setsAdd([], 'value', function (err) { + it('should not error if keys is empty array', (done) => { + db.setsAdd([], 'value', (err) => { assert.ifError(err); done(); }); }); }); - describe('getSetsMembers()', function () { - before(function (done) { + describe('getSetsMembers()', () => { + before((done) => { db.setsAdd(['set3', 'set4'], 'value', done); }); - it('should return members of two sets', function (done) { + it('should return members of two sets', (done) => { db.getSetsMembers(['set3', 'set4'], function (err, sets) { assert.equal(err, null); assert.equal(Array.isArray(sets), true); @@ -95,12 +95,12 @@ describe('Set methods', function () { }); }); - describe('isSetMember()', function () { - before(function (done) { + describe('isSetMember()', () => { + before((done) => { db.setAdd('testSet3', 5, done); }); - it('should return false if element is not member of set', function (done) { + it('should return false if element is not member of set', (done) => { db.isSetMember('testSet3', 10, function (err, isMember) { assert.equal(err, null); assert.equal(arguments.length, 2); @@ -109,7 +109,7 @@ describe('Set methods', function () { }); }); - it('should return true if element is a member of set', function (done) { + it('should return true if element is a member of set', (done) => { db.isSetMember('testSet3', 5, function (err, isMember) { assert.equal(err, null); assert.equal(arguments.length, 2); @@ -119,12 +119,12 @@ describe('Set methods', function () { }); }); - describe('isSetMembers()', function () { - before(function (done) { + describe('isSetMembers()', () => { + before((done) => { db.setAdd('testSet4', [1, 2, 3, 4, 5], done); }); - it('should return an array of booleans', function (done) { + it('should return an array of booleans', (done) => { db.isSetMembers('testSet4', ['1', '2', '10', '3'], function (err, members) { assert.equal(err, null); assert.equal(arguments.length, 2); @@ -135,12 +135,12 @@ describe('Set methods', function () { }); }); - describe('isMemberOfSets()', function () { - before(function (done) { + describe('isMemberOfSets()', () => { + before((done) => { db.setsAdd(['set1', 'set2'], 'value', done); }); - it('should return an array of booleans', function (done) { + it('should return an array of booleans', (done) => { db.isMemberOfSets(['set1', 'testSet1', 'set2', 'doesnotexist'], 'value', function (err, members) { assert.equal(err, null); assert.equal(arguments.length, 2); @@ -151,12 +151,12 @@ describe('Set methods', function () { }); }); - describe('setCount()', function () { - before(function (done) { + describe('setCount()', () => { + before((done) => { db.setAdd('testSet5', [1, 2, 3, 4, 5], done); }); - it('should return the element count of set', function (done) { + it('should return the element count of set', (done) => { db.setCount('testSet5', function (err, count) { assert.equal(err, null); assert.equal(arguments.length, 2); @@ -165,8 +165,8 @@ describe('Set methods', function () { }); }); - it('should return 0 if set does not exist', function (done) { - db.setCount('doesnotexist', function (err, count) { + it('should return 0 if set does not exist', (done) => { + db.setCount('doesnotexist', (err, count) => { assert.ifError(err); assert.strictEqual(count, 0); done(); @@ -174,8 +174,8 @@ describe('Set methods', function () { }); }); - describe('setsCount()', function () { - before(function (done) { + describe('setsCount()', () => { + before((done) => { async.parallel([ async.apply(db.setAdd, 'set5', [1, 2, 3, 4, 5]), async.apply(db.setAdd, 'set6', 1), @@ -183,7 +183,7 @@ describe('Set methods', function () { ], done); }); - it('should return the element count of sets', function (done) { + it('should return the element count of sets', (done) => { db.setsCount(['set5', 'set6', 'set7', 'doesnotexist'], function (err, counts) { assert.equal(err, null); assert.equal(arguments.length, 2); @@ -194,17 +194,17 @@ describe('Set methods', function () { }); }); - describe('setRemove()', function () { - before(function (done) { + describe('setRemove()', () => { + before((done) => { db.setAdd('testSet6', [1, 2], done); }); - it('should remove a element from set', function (done) { + it('should remove a element from set', (done) => { db.setRemove('testSet6', '2', function (err) { assert.equal(err, null); assert.equal(arguments.length, 1); - db.isSetMember('testSet6', '2', function (err, isMember) { + db.isSetMember('testSet6', '2', (err, isMember) => { assert.equal(err, null); assert.equal(isMember, false); done(); @@ -212,12 +212,12 @@ describe('Set methods', function () { }); }); - it('should remove multiple elements from set', function (done) { - db.setAdd('multiRemoveSet', [1, 2, 3, 4, 5], function (err) { + it('should remove multiple elements from set', (done) => { + db.setAdd('multiRemoveSet', [1, 2, 3, 4, 5], (err) => { assert.ifError(err); - db.setRemove('multiRemoveSet', [1, 3, 5], function (err) { + db.setRemove('multiRemoveSet', [1, 3, 5], (err) => { assert.ifError(err); - db.getSetMembers('multiRemoveSet', function (err, members) { + db.getSetMembers('multiRemoveSet', (err, members) => { assert.ifError(err); assert(members.includes('2')); assert(members.includes('4')); @@ -227,14 +227,14 @@ describe('Set methods', function () { }); }); - it('should remove multiple values from multiple keys', function (done) { - db.setAdd('multiSetTest1', ['one', 'two', 'three', 'four'], function (err) { + it('should remove multiple values from multiple keys', (done) => { + db.setAdd('multiSetTest1', ['one', 'two', 'three', 'four'], (err) => { assert.ifError(err); - db.setAdd('multiSetTest2', ['three', 'four', 'five', 'six'], function (err) { + db.setAdd('multiSetTest2', ['three', 'four', 'five', 'six'], (err) => { assert.ifError(err); - db.setRemove(['multiSetTest1', 'multiSetTest2'], ['three', 'four', 'five', 'doesnt exist'], function (err) { + db.setRemove(['multiSetTest1', 'multiSetTest2'], ['three', 'four', 'five', 'doesnt exist'], (err) => { assert.ifError(err); - db.getSetsMembers(['multiSetTest1', 'multiSetTest2'], function (err, members) { + db.getSetsMembers(['multiSetTest1', 'multiSetTest2'], (err, members) => { assert.ifError(err); assert.equal(members[0].length, 2); assert.equal(members[1].length, 1); @@ -249,16 +249,16 @@ describe('Set methods', function () { }); }); - describe('setsRemove()', function () { - before(function (done) { + describe('setsRemove()', () => { + before((done) => { db.setsAdd(['set1', 'set2'], 'value', done); }); - it('should remove a element from multiple sets', function (done) { + it('should remove a element from multiple sets', (done) => { db.setsRemove(['set1', 'set2'], 'value', function (err) { assert.equal(err, null); assert.equal(arguments.length, 1); - db.isMemberOfSets(['set1', 'set2'], 'value', function (err, members) { + db.isMemberOfSets(['set1', 'set2'], 'value', (err, members) => { assert.equal(err, null); assert.deepEqual(members, [false, false]); done(); @@ -267,17 +267,17 @@ describe('Set methods', function () { }); }); - describe('setRemoveRandom()', function () { - before(function (done) { + describe('setRemoveRandom()', () => { + before((done) => { db.setAdd('testSet7', [1, 2, 3, 4, 5], done); }); - it('should remove a random element from set', function (done) { + it('should remove a random element from set', (done) => { db.setRemoveRandom('testSet7', function (err, element) { assert.equal(err, null); assert.equal(arguments.length, 2); - db.isSetMember('testSet', element, function (err, ismember) { + db.isSetMember('testSet', element, (err, ismember) => { assert.equal(err, null); assert.equal(ismember, false); done(); diff --git a/test/database/sorted.js b/test/database/sorted.js index 71bc9cd8bd..11750aba70 100644 --- a/test/database/sorted.js +++ b/test/database/sorted.js @@ -5,8 +5,8 @@ var async = require('async'); var assert = require('assert'); var db = require('../mocks/databasemock'); -describe('Sorted Set methods', function () { - before(function (done) { +describe('Sorted Set methods', () => { + before((done) => { async.parallel([ function (next) { db.sortedSetAdd('sortedSetTest1', [1.1, 1.2, 1.3], ['value1', 'value2', 'value3'], next); @@ -26,7 +26,7 @@ describe('Sorted Set methods', function () { ], done); }); - describe('sortedSetScan', function () { + describe('sortedSetScan', () => { it('should find matches in sorted set containing substring', async () => { await db.sortedSetAdd('scanzset', [1, 2, 3, 4, 5, 6], ['aaaa', 'bbbb', 'bbcc', 'ddd', 'dddd', 'fghbc']); const data = await db.getSortedSetScan({ @@ -91,8 +91,8 @@ describe('Sorted Set methods', function () { }); }); - describe('sortedSetAdd()', function () { - it('should add an element to a sorted set', function (done) { + describe('sortedSetAdd()', () => { + it('should add an element to a sorted set', (done) => { db.sortedSetAdd('sorted1', 1, 'value1', function (err) { assert.equal(err, null); assert.equal(arguments.length, 1); @@ -100,7 +100,7 @@ describe('Sorted Set methods', function () { }); }); - it('should add two elements to a sorted set', function (done) { + it('should add two elements to a sorted set', (done) => { db.sortedSetAdd('sorted2', [1, 2], ['value1', 'value2'], function (err) { assert.equal(err, null); assert.equal(arguments.length, 1); @@ -108,7 +108,7 @@ describe('Sorted Set methods', function () { }); }); - it('should gracefully handle adding the same element twice', function (done) { + it('should gracefully handle adding the same element twice', (done) => { db.sortedSetAdd('sorted2', [1, 2], ['value1', 'value1'], function (err) { assert.equal(err, null); assert.equal(arguments.length, 1); @@ -123,24 +123,24 @@ describe('Sorted Set methods', function () { }); }); - it('should error if score is null', function (done) { - db.sortedSetAdd('errorScore', null, 'value1', function (err) { + it('should error if score is null', (done) => { + db.sortedSetAdd('errorScore', null, 'value1', (err) => { assert.equal(err.message, '[[error:invalid-score, null]]'); done(); }); }); - it('should error if any score is undefined', function (done) { - db.sortedSetAdd('errorScore', [1, undefined], ['value1', 'value2'], function (err) { + it('should error if any score is undefined', (done) => { + db.sortedSetAdd('errorScore', [1, undefined], ['value1', 'value2'], (err) => { assert.equal(err.message, '[[error:invalid-score, undefined]]'); done(); }); }); - it('should add null value as `null` string', function (done) { - db.sortedSetAdd('nullValueZSet', 1, null, function (err) { + it('should add null value as `null` string', (done) => { + db.sortedSetAdd('nullValueZSet', 1, null, (err) => { assert.ifError(err); - db.getSortedSetRange('nullValueZSet', 0, -1, function (err, values) { + db.getSortedSetRange('nullValueZSet', 0, -1, (err, values) => { assert.ifError(err); assert.strictEqual(values[0], 'null'); done(); @@ -149,8 +149,8 @@ describe('Sorted Set methods', function () { }); }); - describe('sortedSetsAdd()', function () { - it('should add an element to two sorted sets', function (done) { + describe('sortedSetsAdd()', () => { + it('should add an element to two sorted sets', (done) => { db.sortedSetsAdd(['sorted1', 'sorted2'], 3, 'value3', function (err) { assert.equal(err, null); assert.equal(arguments.length, 1); @@ -158,10 +158,10 @@ describe('Sorted Set methods', function () { }); }); - it('should add an element to two sorted sets with different scores', function (done) { - db.sortedSetsAdd(['sorted1', 'sorted2'], [4, 5], 'value4', function (err) { + it('should add an element to two sorted sets with different scores', (done) => { + db.sortedSetsAdd(['sorted1', 'sorted2'], [4, 5], 'value4', (err) => { assert.ifError(err); - db.sortedSetsScore(['sorted1', 'sorted2'], 'value4', function (err, scores) { + db.sortedSetsScore(['sorted1', 'sorted2'], 'value4', (err, scores) => { assert.ifError(err); assert.deepStrictEqual(scores, [4, 5]); done(); @@ -170,21 +170,21 @@ describe('Sorted Set methods', function () { }); - it('should error if keys.length is different than scores.length', function (done) { - db.sortedSetsAdd(['sorted1', 'sorted2'], [4], 'value4', function (err) { + it('should error if keys.length is different than scores.length', (done) => { + db.sortedSetsAdd(['sorted1', 'sorted2'], [4], 'value4', (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); }); - it('should error if score is null', function (done) { - db.sortedSetsAdd(['sorted1', 'sorted2'], null, 'value1', function (err) { + it('should error if score is null', (done) => { + db.sortedSetsAdd(['sorted1', 'sorted2'], null, 'value1', (err) => { assert.equal(err.message, '[[error:invalid-score, null]]'); done(); }); }); - it('should error if scores has null', async function () { + it('should error if scores has null', async () => { let err; try { await db.sortedSetsAdd(['sorted1', 'sorted2'], [1, null], 'dontadd'); @@ -197,8 +197,8 @@ describe('Sorted Set methods', function () { }); }); - describe('sortedSetAddMulti()', function () { - it('should add elements into multiple sorted sets with different scores', function (done) { + describe('sortedSetAddMulti()', () => { + it('should add elements into multiple sorted sets with different scores', (done) => { db.sortedSetAddBulk([ ['bulk1', 1, 'item1'], ['bulk2', 2, 'item1'], @@ -207,7 +207,7 @@ describe('Sorted Set methods', function () { ], function (err) { assert.ifError(err); assert.equal(arguments.length, 1); - db.getSortedSetRevRangeWithScores(['bulk1', 'bulk2', 'bulk3'], 0, -1, function (err, data) { + db.getSortedSetRevRangeWithScores(['bulk1', 'bulk2', 'bulk3'], 0, -1, (err, data) => { assert.ifError(err); assert.deepStrictEqual(data, [{ value: 'item3', score: 4 }, { value: 'item2', score: 3 }, @@ -217,14 +217,14 @@ describe('Sorted Set methods', function () { }); }); }); - it('should not error if data is undefined', function (done) { - db.sortedSetAddBulk(undefined, function (err) { + it('should not error if data is undefined', (done) => { + db.sortedSetAddBulk(undefined, (err) => { assert.ifError(err); done(); }); }); - it('should error if score is null', async function () { + it('should error if score is null', async () => { let err; try { await db.sortedSetAddBulk([ @@ -240,8 +240,8 @@ describe('Sorted Set methods', function () { }); }); - describe('getSortedSetRange()', function () { - it('should return the lowest scored element', function (done) { + describe('getSortedSetRange()', () => { + it('should return the lowest scored element', (done) => { db.getSortedSetRange('sortedSetTest1', 0, 0, function (err, value) { assert.equal(err, null); assert.equal(arguments.length, 2); @@ -250,7 +250,7 @@ describe('Sorted Set methods', function () { }); }); - it('should return elements sorted by score lowest to highest', function (done) { + it('should return elements sorted by score lowest to highest', (done) => { db.getSortedSetRange('sortedSetTest1', 0, -1, function (err, values) { assert.equal(err, null); assert.equal(arguments.length, 2); @@ -259,8 +259,8 @@ describe('Sorted Set methods', function () { }); }); - it('should return empty array if set does not exist', function (done) { - db.getSortedSetRange('doesnotexist', 0, -1, function (err, values) { + it('should return empty array if set does not exist', (done) => { + db.getSortedSetRange('doesnotexist', 0, -1, (err, values) => { assert.ifError(err); assert(Array.isArray(values)); assert.equal(values.length, 0); @@ -268,10 +268,10 @@ describe('Sorted Set methods', function () { }); }); - it('should handle negative start/stop', function (done) { - db.sortedSetAdd('negatives', [1, 2, 3, 4, 5], ['1', '2', '3', '4', '5'], function (err) { + it('should handle negative start/stop', (done) => { + db.sortedSetAdd('negatives', [1, 2, 3, 4, 5], ['1', '2', '3', '4', '5'], (err) => { assert.ifError(err); - db.getSortedSetRange('negatives', -2, -4, function (err, data) { + db.getSortedSetRange('negatives', -2, -4, (err, data) => { assert.ifError(err); assert.deepEqual(data, []); done(); @@ -279,54 +279,54 @@ describe('Sorted Set methods', function () { }); }); - it('should handle negative start/stop', function (done) { - db.getSortedSetRange('negatives', -4, -2, function (err, data) { + it('should handle negative start/stop', (done) => { + db.getSortedSetRange('negatives', -4, -2, (err, data) => { assert.ifError(err); assert.deepEqual(data, ['2', '3', '4']); done(); }); }); - it('should handle negative start/stop', function (done) { - db.getSortedSetRevRange('negatives', -4, -2, function (err, data) { + it('should handle negative start/stop', (done) => { + db.getSortedSetRevRange('negatives', -4, -2, (err, data) => { assert.ifError(err); assert.deepEqual(data, ['4', '3', '2']); done(); }); }); - it('should handle negative start/stop', function (done) { - db.getSortedSetRange('negatives', -5, -1, function (err, data) { + it('should handle negative start/stop', (done) => { + db.getSortedSetRange('negatives', -5, -1, (err, data) => { assert.ifError(err); assert.deepEqual(data, ['1', '2', '3', '4', '5']); done(); }); }); - it('should handle negative start/stop', function (done) { - db.getSortedSetRange('negatives', 0, -2, function (err, data) { + it('should handle negative start/stop', (done) => { + db.getSortedSetRange('negatives', 0, -2, (err, data) => { assert.ifError(err); assert.deepEqual(data, ['1', '2', '3', '4']); done(); }); }); - it('should return empty array if keys is empty array', function (done) { - db.getSortedSetRange([], 0, -1, function (err, data) { + it('should return empty array if keys is empty array', (done) => { + db.getSortedSetRange([], 0, -1, (err, data) => { assert.ifError(err); assert.deepStrictEqual(data, []); done(); }); }); - it('should return duplicates if two sets have same elements', async function () { + it('should return duplicates if two sets have same elements', async () => { await db.sortedSetAdd('dupezset1', [1, 2], ['value 1', 'value 2']); await db.sortedSetAdd('dupezset2', [2, 3], ['value 2', 'value 3']); const data = await db.getSortedSetRange(['dupezset1', 'dupezset2'], 0, -1); assert.deepStrictEqual(data, ['value 1', 'value 2', 'value 2', 'value 3']); }); - it('should return correct number of elements', async function () { + it('should return correct number of elements', async () => { await db.sortedSetAdd('dupezset3', [1, 2, 3], ['value 1', 'value 2', 'value3']); await db.sortedSetAdd('dupezset4', [0, 5], ['value 0', 'value5']); const data = await db.getSortedSetRevRange(['dupezset3', 'dupezset4'], 0, 1); @@ -365,8 +365,8 @@ describe('Sorted Set methods', function () { }); }); - describe('getSortedSetRevRange()', function () { - it('should return the highest scored element', function (done) { + describe('getSortedSetRevRange()', () => { + it('should return the highest scored element', (done) => { db.getSortedSetRevRange('sortedSetTest1', 0, 0, function (err, value) { assert.equal(err, null); assert.equal(arguments.length, 2); @@ -375,7 +375,7 @@ describe('Sorted Set methods', function () { }); }); - it('should return elements sorted by score highest to lowest', function (done) { + it('should return elements sorted by score highest to lowest', (done) => { db.getSortedSetRevRange('sortedSetTest1', 0, -1, function (err, values) { assert.equal(err, null); assert.equal(arguments.length, 2); @@ -385,8 +385,8 @@ describe('Sorted Set methods', function () { }); }); - describe('getSortedSetRangeWithScores()', function () { - it('should return array of elements sorted by score lowest to highest with scores', function (done) { + describe('getSortedSetRangeWithScores()', () => { + it('should return array of elements sorted by score lowest to highest with scores', (done) => { db.getSortedSetRangeWithScores('sortedSetTest1', 0, -1, function (err, values) { assert.equal(err, null); assert.equal(arguments.length, 2); @@ -396,8 +396,8 @@ describe('Sorted Set methods', function () { }); }); - describe('getSortedSetRevRangeWithScores()', function () { - it('should return array of elements sorted by score highest to lowest with scores', function (done) { + describe('getSortedSetRevRangeWithScores()', () => { + it('should return array of elements sorted by score highest to lowest with scores', (done) => { db.getSortedSetRevRangeWithScores('sortedSetTest1', 0, -1, function (err, values) { assert.equal(err, null); assert.equal(arguments.length, 2); @@ -407,8 +407,8 @@ describe('Sorted Set methods', function () { }); }); - describe('getSortedSetRangeByScore()', function () { - it('should get count elements with score between min max sorted by score lowest to highest', function (done) { + describe('getSortedSetRangeByScore()', () => { + it('should get count elements with score between min max sorted by score lowest to highest', (done) => { db.getSortedSetRangeByScore('sortedSetTest1', 0, -1, '-inf', 1.2, function (err, values) { assert.equal(err, null); assert.equal(arguments.length, 2); @@ -417,8 +417,8 @@ describe('Sorted Set methods', function () { }); }); - it('should return empty array if set does not exist', function (done) { - db.getSortedSetRangeByScore('doesnotexist', 0, -1, '-inf', 0, function (err, values) { + it('should return empty array if set does not exist', (done) => { + db.getSortedSetRangeByScore('doesnotexist', 0, -1, '-inf', 0, (err, values) => { assert.ifError(err); assert(Array.isArray(values)); assert.equal(values.length, 0); @@ -426,26 +426,26 @@ describe('Sorted Set methods', function () { }); }); - it('should return empty array if count is 0', function (done) { - db.getSortedSetRevRangeByScore('sortedSetTest1', 0, 0, '+inf', '-inf', function (err, values) { + it('should return empty array if count is 0', (done) => { + db.getSortedSetRevRangeByScore('sortedSetTest1', 0, 0, '+inf', '-inf', (err, values) => { assert.ifError(err); assert.deepEqual(values, []); done(); }); }); - it('should return elements from 1 to end', function (done) { - db.getSortedSetRevRangeByScore('sortedSetTest1', 1, -1, '+inf', '-inf', function (err, values) { + it('should return elements from 1 to end', (done) => { + db.getSortedSetRevRangeByScore('sortedSetTest1', 1, -1, '+inf', '-inf', (err, values) => { assert.ifError(err); assert.deepEqual(values, ['value2', 'value1']); done(); }); }); - it('should return elements from 3 to last', function (done) { - db.sortedSetAdd('partialZset', [1, 2, 3, 4, 5], ['value1', 'value2', 'value3', 'value4', 'value5'], function (err) { + it('should return elements from 3 to last', (done) => { + db.sortedSetAdd('partialZset', [1, 2, 3, 4, 5], ['value1', 'value2', 'value3', 'value4', 'value5'], (err) => { assert.ifError(err); - db.getSortedSetRangeByScore('partialZset', 3, 10, '-inf', '+inf', function (err, data) { + db.getSortedSetRangeByScore('partialZset', 3, 10, '-inf', '+inf', (err, data) => { assert.ifError(err); assert.deepStrictEqual(data, ['value4', 'value5']); done(); @@ -454,8 +454,8 @@ describe('Sorted Set methods', function () { }); }); - describe('getSortedSetRevRangeByScore()', function () { - it('should get count elements with score between max min sorted by score highest to lowest', function (done) { + describe('getSortedSetRevRangeByScore()', () => { + it('should get count elements with score between max min sorted by score highest to lowest', (done) => { db.getSortedSetRevRangeByScore('sortedSetTest1', 0, -1, '+inf', 1.2, function (err, values) { assert.equal(err, null); assert.equal(arguments.length, 2); @@ -465,8 +465,8 @@ describe('Sorted Set methods', function () { }); }); - describe('getSortedSetRangeByScoreWithScores()', function () { - it('should get count elements with score between min max sorted by score lowest to highest with scores', function (done) { + describe('getSortedSetRangeByScoreWithScores()', () => { + it('should get count elements with score between min max sorted by score lowest to highest with scores', (done) => { db.getSortedSetRangeByScoreWithScores('sortedSetTest1', 0, -1, '-inf', 1.2, function (err, values) { assert.equal(err, null); assert.equal(arguments.length, 2); @@ -476,8 +476,8 @@ describe('Sorted Set methods', function () { }); }); - describe('getSortedSetRevRangeByScoreWithScores()', function () { - it('should get count elements with score between max min sorted by score highest to lowest', function (done) { + describe('getSortedSetRevRangeByScoreWithScores()', () => { + it('should get count elements with score between max min sorted by score highest to lowest', (done) => { db.getSortedSetRevRangeByScoreWithScores('sortedSetTest1', 0, -1, '+inf', 1.2, function (err, values) { assert.equal(err, null); assert.equal(arguments.length, 2); @@ -486,7 +486,7 @@ describe('Sorted Set methods', function () { }); }); - it('should work with an array of keys', async function () { + it('should work with an array of keys', async () => { await db.sortedSetAddBulk([ ['byScoreWithScoresKeys1', 1, 'value1'], ['byScoreWithScoresKeys2', 2, 'value2'], @@ -496,8 +496,8 @@ describe('Sorted Set methods', function () { }); }); - describe('sortedSetCount()', function () { - it('should return 0 for a sorted set that does not exist', function (done) { + describe('sortedSetCount()', () => { + it('should return 0 for a sorted set that does not exist', (done) => { db.sortedSetCount('doesnotexist', 0, 10, function (err, count) { assert.equal(err, null); assert.equal(arguments.length, 2); @@ -506,7 +506,7 @@ describe('Sorted Set methods', function () { }); }); - it('should return number of elements between scores min max inclusive', function (done) { + it('should return number of elements between scores min max inclusive', (done) => { db.sortedSetCount('sortedSetTest1', '-inf', 1.2, function (err, count) { assert.equal(err, null); assert.equal(arguments.length, 2); @@ -515,7 +515,7 @@ describe('Sorted Set methods', function () { }); }); - it('should return number of elements between scores -inf +inf inclusive', function (done) { + it('should return number of elements between scores -inf +inf inclusive', (done) => { db.sortedSetCount('sortedSetTest1', '-inf', '+inf', function (err, count) { assert.equal(err, null); assert.equal(arguments.length, 2); @@ -525,8 +525,8 @@ describe('Sorted Set methods', function () { }); }); - describe('sortedSetCard()', function () { - it('should return 0 for a sorted set that does not exist', function (done) { + describe('sortedSetCard()', () => { + it('should return 0 for a sorted set that does not exist', (done) => { db.sortedSetCard('doesnotexist', function (err, count) { assert.equal(err, null); assert.equal(arguments.length, 2); @@ -535,7 +535,7 @@ describe('Sorted Set methods', function () { }); }); - it('should return number of elements in a sorted set', function (done) { + it('should return number of elements in a sorted set', (done) => { db.sortedSetCard('sortedSetTest1', function (err, count) { assert.equal(err, null); assert.equal(arguments.length, 2); @@ -545,8 +545,8 @@ describe('Sorted Set methods', function () { }); }); - describe('sortedSetsCard()', function () { - it('should return the number of elements in sorted sets', function (done) { + describe('sortedSetsCard()', () => { + it('should return the number of elements in sorted sets', (done) => { db.sortedSetsCard(['sortedSetTest1', 'sortedSetTest2', 'doesnotexist'], function (err, counts) { assert.ifError(err); assert.equal(arguments.length, 2); @@ -555,7 +555,7 @@ describe('Sorted Set methods', function () { }); }); - it('should return empty array if keys is falsy', function (done) { + it('should return empty array if keys is falsy', (done) => { db.sortedSetsCard(undefined, function (err, counts) { assert.ifError(err); assert.equal(arguments.length, 2); @@ -564,7 +564,7 @@ describe('Sorted Set methods', function () { }); }); - it('should return empty array if keys is empty array', function (done) { + it('should return empty array if keys is empty array', (done) => { db.sortedSetsCard([], function (err, counts) { assert.ifError(err); assert.equal(arguments.length, 2); @@ -574,8 +574,8 @@ describe('Sorted Set methods', function () { }); }); - describe('sortedSetsCardSum()', function () { - it('should return the total number of elements in sorted sets', function (done) { + describe('sortedSetsCardSum()', () => { + it('should return the total number of elements in sorted sets', (done) => { db.sortedSetsCardSum(['sortedSetTest1', 'sortedSetTest2', 'doesnotexist'], function (err, sum) { assert.ifError(err); assert.equal(arguments.length, 2); @@ -584,7 +584,7 @@ describe('Sorted Set methods', function () { }); }); - it('should return 0 if keys is falsy', function (done) { + it('should return 0 if keys is falsy', (done) => { db.sortedSetsCardSum(undefined, function (err, counts) { assert.ifError(err); assert.equal(arguments.length, 2); @@ -593,7 +593,7 @@ describe('Sorted Set methods', function () { }); }); - it('should return 0 if keys is empty array', function (done) { + it('should return 0 if keys is empty array', (done) => { db.sortedSetsCardSum([], function (err, counts) { assert.ifError(err); assert.equal(arguments.length, 2); @@ -602,7 +602,7 @@ describe('Sorted Set methods', function () { }); }); - it('should return the total number of elements in sorted set', function (done) { + it('should return the total number of elements in sorted set', (done) => { db.sortedSetsCardSum('sortedSetTest1', function (err, sum) { assert.ifError(err); assert.equal(arguments.length, 2); @@ -612,8 +612,8 @@ describe('Sorted Set methods', function () { }); }); - describe('sortedSetRank()', function () { - it('should return falsy if sorted set does not exist', function (done) { + describe('sortedSetRank()', () => { + it('should return falsy if sorted set does not exist', (done) => { db.sortedSetRank('doesnotexist', 'value1', function (err, rank) { assert.equal(err, null); assert.equal(arguments.length, 2); @@ -622,7 +622,7 @@ describe('Sorted Set methods', function () { }); }); - it('should return falsy if element isnt in sorted set', function (done) { + it('should return falsy if element isnt in sorted set', (done) => { db.sortedSetRank('sortedSetTest1', 'value5', function (err, rank) { assert.equal(err, null); assert.equal(arguments.length, 2); @@ -631,7 +631,7 @@ describe('Sorted Set methods', function () { }); }); - it('should return the rank of the element in the sorted set sorted by lowest to highest score', function (done) { + it('should return the rank of the element in the sorted set sorted by lowest to highest score', (done) => { db.sortedSetRank('sortedSetTest1', 'value1', function (err, rank) { assert.equal(err, null); assert.equal(arguments.length, 2); @@ -640,7 +640,7 @@ describe('Sorted Set methods', function () { }); }); - it('should return the rank sorted by the score and then the value (a)', function (done) { + it('should return the rank sorted by the score and then the value (a)', (done) => { db.sortedSetRank('sortedSetTest4', 'a', function (err, rank) { assert.equal(err, null); assert.equal(arguments.length, 2); @@ -649,7 +649,7 @@ describe('Sorted Set methods', function () { }); }); - it('should return the rank sorted by the score and then the value (b)', function (done) { + it('should return the rank sorted by the score and then the value (b)', (done) => { db.sortedSetRank('sortedSetTest4', 'b', function (err, rank) { assert.equal(err, null); assert.equal(arguments.length, 2); @@ -658,7 +658,7 @@ describe('Sorted Set methods', function () { }); }); - it('should return the rank sorted by the score and then the value (c)', function (done) { + it('should return the rank sorted by the score and then the value (c)', (done) => { db.sortedSetRank('sortedSetTest4', 'c', function (err, rank) { assert.equal(err, null); assert.equal(arguments.length, 2); @@ -668,8 +668,8 @@ describe('Sorted Set methods', function () { }); }); - describe('sortedSetRevRank()', function () { - it('should return falsy if sorted set doesnot exist', function (done) { + describe('sortedSetRevRank()', () => { + it('should return falsy if sorted set doesnot exist', (done) => { db.sortedSetRevRank('doesnotexist', 'value1', function (err, rank) { assert.equal(err, null); assert.equal(arguments.length, 2); @@ -678,7 +678,7 @@ describe('Sorted Set methods', function () { }); }); - it('should return falsy if element isnt in sorted set', function (done) { + it('should return falsy if element isnt in sorted set', (done) => { db.sortedSetRevRank('sortedSetTest1', 'value5', function (err, rank) { assert.equal(err, null); assert.equal(arguments.length, 2); @@ -687,7 +687,7 @@ describe('Sorted Set methods', function () { }); }); - it('should return the rank of the element in the sorted set sorted by highest to lowest score', function (done) { + it('should return the rank of the element in the sorted set sorted by highest to lowest score', (done) => { db.sortedSetRevRank('sortedSetTest1', 'value1', function (err, rank) { assert.equal(err, null); assert.equal(arguments.length, 2); @@ -697,8 +697,8 @@ describe('Sorted Set methods', function () { }); }); - describe('sortedSetsRanks()', function () { - it('should return the ranks of values in sorted sets', function (done) { + describe('sortedSetsRanks()', () => { + it('should return the ranks of values in sorted sets', (done) => { db.sortedSetsRanks(['sortedSetTest1', 'sortedSetTest2'], ['value1', 'value4'], function (err, ranks) { assert.equal(err, null); assert.equal(arguments.length, 2); @@ -708,8 +708,8 @@ describe('Sorted Set methods', function () { }); }); - describe('sortedSetRanks()', function () { - it('should return the ranks of values in a sorted set', function (done) { + describe('sortedSetRanks()', () => { + it('should return the ranks of values in a sorted set', (done) => { db.sortedSetRanks('sortedSetTest1', ['value2', 'value1', 'value3', 'value4'], function (err, ranks) { assert.equal(err, null); assert.equal(arguments.length, 2); @@ -718,7 +718,7 @@ describe('Sorted Set methods', function () { }); }); - it('should return the ranks of values in a sorted set in reverse', function (done) { + it('should return the ranks of values in a sorted set in reverse', (done) => { db.sortedSetRevRanks('sortedSetTest1', ['value2', 'value1', 'value3', 'value4'], function (err, ranks) { assert.equal(err, null); assert.equal(arguments.length, 2); @@ -728,8 +728,8 @@ describe('Sorted Set methods', function () { }); }); - describe('sortedSetScore()', function () { - it('should return falsy if sorted set does not exist', function (done) { + describe('sortedSetScore()', () => { + it('should return falsy if sorted set does not exist', (done) => { db.sortedSetScore('doesnotexist', 'value1', function (err, score) { assert.equal(err, null); assert.equal(arguments.length, 2); @@ -739,7 +739,7 @@ describe('Sorted Set methods', function () { }); }); - it('should return falsy if element is not in sorted set', function (done) { + it('should return falsy if element is not in sorted set', (done) => { db.sortedSetScore('sortedSetTest1', 'value5', function (err, score) { assert.equal(err, null); assert.equal(arguments.length, 2); @@ -749,7 +749,7 @@ describe('Sorted Set methods', function () { }); }); - it('should return the score of an element', function (done) { + it('should return the score of an element', (done) => { db.sortedSetScore('sortedSetTest1', 'value2', function (err, score) { assert.equal(err, null); assert.equal(arguments.length, 2); @@ -758,16 +758,16 @@ describe('Sorted Set methods', function () { }); }); - it('should not error if key is undefined', function (done) { - db.sortedSetScore(undefined, 1, function (err, score) { + it('should not error if key is undefined', (done) => { + db.sortedSetScore(undefined, 1, (err, score) => { assert.ifError(err); assert.strictEqual(score, null); done(); }); }); - it('should not error if value is undefined', function (done) { - db.sortedSetScore('sortedSetTest1', undefined, function (err, score) { + it('should not error if value is undefined', (done) => { + db.sortedSetScore('sortedSetTest1', undefined, (err, score) => { assert.ifError(err); assert.strictEqual(score, null); done(); @@ -775,8 +775,8 @@ describe('Sorted Set methods', function () { }); }); - describe('sortedSetsScore()', function () { - it('should return the scores of value in sorted sets', function (done) { + describe('sortedSetsScore()', () => { + it('should return the scores of value in sorted sets', (done) => { db.sortedSetsScore(['sortedSetTest1', 'sortedSetTest2', 'doesnotexist'], 'value1', function (err, scores) { assert.equal(err, null); assert.equal(arguments.length, 2); @@ -785,7 +785,7 @@ describe('Sorted Set methods', function () { }); }); - it('should return scores even if some keys are undefined', function (done) { + it('should return scores even if some keys are undefined', (done) => { db.sortedSetsScore(['sortedSetTest1', undefined, 'doesnotexist'], 'value1', function (err, scores) { assert.equal(err, null); assert.equal(arguments.length, 2); @@ -794,7 +794,7 @@ describe('Sorted Set methods', function () { }); }); - it('should return empty array if keys is empty array', function (done) { + it('should return empty array if keys is empty array', (done) => { db.sortedSetsScore([], 'value1', function (err, scores) { assert.equal(err, null); assert.equal(arguments.length, 2); @@ -804,20 +804,20 @@ describe('Sorted Set methods', function () { }); }); - describe('sortedSetScores()', function () { - before(function (done) { + describe('sortedSetScores()', () => { + before((done) => { db.sortedSetAdd('zeroScore', 0, 'value1', done); }); - it('should return 0 if score is 0', function (done) { - db.sortedSetScores('zeroScore', ['value1'], function (err, scores) { + it('should return 0 if score is 0', (done) => { + db.sortedSetScores('zeroScore', ['value1'], (err, scores) => { assert.ifError(err); assert.strictEqual(scores[0], 0); done(); }); }); - it('should return the scores of value in sorted sets', function (done) { + it('should return the scores of value in sorted sets', (done) => { db.sortedSetScores('sortedSetTest1', ['value2', 'value1', 'doesnotexist'], function (err, scores) { assert.ifError(err); assert.equal(arguments.length, 2); @@ -826,7 +826,7 @@ describe('Sorted Set methods', function () { }); }); - it('should return scores even if some values are undefined', function (done) { + it('should return scores even if some values are undefined', (done) => { db.sortedSetScores('sortedSetTest1', ['value2', undefined, 'doesnotexist'], function (err, scores) { assert.ifError(err); assert.equal(arguments.length, 2); @@ -835,7 +835,7 @@ describe('Sorted Set methods', function () { }); }); - it('should return empty array if values is an empty array', function (done) { + it('should return empty array if values is an empty array', (done) => { db.sortedSetScores('sortedSetTest1', [], function (err, scores) { assert.ifError(err); assert.equal(arguments.length, 2); @@ -844,7 +844,7 @@ describe('Sorted Set methods', function () { }); }); - it('should return scores properly', function (done) { + it('should return scores properly', (done) => { db.sortedSetsScore(['zeroScore', 'sortedSetTest1', 'doesnotexist'], 'value1', function (err, scores) { assert.ifError(err); assert.equal(arguments.length, 2); @@ -854,12 +854,12 @@ describe('Sorted Set methods', function () { }); }); - describe('isSortedSetMember()', function () { - before(function (done) { + describe('isSortedSetMember()', () => { + before((done) => { db.sortedSetAdd('zeroscore', 0, 'itemwithzeroscore', done); }); - it('should return false if sorted set does not exist', function (done) { + it('should return false if sorted set does not exist', (done) => { db.isSortedSetMember('doesnotexist', 'value1', function (err, isMember) { assert.ifError(err); assert.equal(arguments.length, 2); @@ -868,7 +868,7 @@ describe('Sorted Set methods', function () { }); }); - it('should return false if element is not in sorted set', function (done) { + it('should return false if element is not in sorted set', (done) => { db.isSortedSetMember('sorted2', 'value5', function (err, isMember) { assert.ifError(err); assert.equal(arguments.length, 2); @@ -877,7 +877,7 @@ describe('Sorted Set methods', function () { }); }); - it('should return true if element is in sorted set', function (done) { + it('should return true if element is in sorted set', (done) => { db.isSortedSetMember('sortedSetTest1', 'value2', function (err, isMember) { assert.ifError(err); assert.equal(arguments.length, 2); @@ -886,8 +886,8 @@ describe('Sorted Set methods', function () { }); }); - it('should return true if element is in sorted set with score 0', function (done) { - db.isSortedSetMember('zeroscore', 'itemwithzeroscore', function (err, isMember) { + it('should return true if element is in sorted set with score 0', (done) => { + db.isSortedSetMember('zeroscore', 'itemwithzeroscore', (err, isMember) => { assert.ifError(err); assert.strictEqual(isMember, true); done(); @@ -895,8 +895,8 @@ describe('Sorted Set methods', function () { }); }); - describe('isSortedSetMembers()', function () { - it('should return an array of booleans indicating membership', function (done) { + describe('isSortedSetMembers()', () => { + it('should return an array of booleans indicating membership', (done) => { db.isSortedSetMembers('sortedSetTest1', ['value1', 'value2', 'value5'], function (err, isMembers) { assert.equal(err, null); assert.equal(arguments.length, 2); @@ -905,7 +905,7 @@ describe('Sorted Set methods', function () { }); }); - it('should return true if element is in sorted set with score 0', function (done) { + it('should return true if element is in sorted set with score 0', (done) => { db.isSortedSetMembers('zeroscore', ['itemwithzeroscore'], function (err, isMembers) { assert.ifError(err); assert.equal(arguments.length, 2); @@ -915,8 +915,8 @@ describe('Sorted Set methods', function () { }); }); - describe('isMemberOfSortedSets', function () { - it('should return true for members false for non members', function (done) { + describe('isMemberOfSortedSets', () => { + it('should return true for members false for non members', (done) => { db.isMemberOfSortedSets(['doesnotexist', 'sortedSetTest1', 'sortedSetTest2'], 'value2', function (err, isMembers) { assert.equal(err, null); assert.equal(arguments.length, 2); @@ -925,7 +925,7 @@ describe('Sorted Set methods', function () { }); }); - it('should return empty array if keys is empty array', function (done) { + it('should return empty array if keys is empty array', (done) => { db.isMemberOfSortedSets([], 'value2', function (err, isMembers) { assert.ifError(err); assert.equal(arguments.length, 2); @@ -935,20 +935,20 @@ describe('Sorted Set methods', function () { }); }); - describe('getSortedSetsMembers', function () { - it('should return members of a sorted set', async function () { + describe('getSortedSetsMembers', () => { + it('should return members of a sorted set', async () => { const result = await db.getSortedSetMembers('sortedSetTest1'); - result.forEach(function (element) { + result.forEach((element) => { assert(['value1', 'value2', 'value3'].includes(element)); }); }); - it('should return members of multiple sorted sets', function (done) { + it('should return members of multiple sorted sets', (done) => { db.getSortedSetsMembers(['doesnotexist', 'sortedSetTest1'], function (err, sortedSets) { assert.equal(err, null); assert.equal(arguments.length, 2); assert.deepEqual(sortedSets[0], []); - sortedSets[0].forEach(function (element) { + sortedSets[0].forEach((element) => { assert.notEqual(['value1', 'value2', 'value3'].indexOf(element), -1); }); @@ -957,9 +957,9 @@ describe('Sorted Set methods', function () { }); }); - describe('sortedSetUnionCard', function () { - it('should return the number of elements in the union', function (done) { - db.sortedSetUnionCard(['sortedSetTest2', 'sortedSetTest3'], function (err, count) { + describe('sortedSetUnionCard', () => { + it('should return the number of elements in the union', (done) => { + db.sortedSetUnionCard(['sortedSetTest2', 'sortedSetTest3'], (err, count) => { assert.ifError(err); assert.equal(count, 3); done(); @@ -967,8 +967,8 @@ describe('Sorted Set methods', function () { }); }); - describe('getSortedSetUnion()', function () { - it('should return an array of values from both sorted sets sorted by scores lowest to highest', function (done) { + describe('getSortedSetUnion()', () => { + it('should return an array of values from both sorted sets sorted by scores lowest to highest', (done) => { db.getSortedSetUnion({ sets: ['sortedSetTest2', 'sortedSetTest3'], start: 0, stop: -1 }, function (err, values) { assert.equal(err, null); assert.equal(arguments.length, 2); @@ -977,7 +977,7 @@ describe('Sorted Set methods', function () { }); }); - it('should return an array of values and scores from both sorted sets sorted by scores lowest to highest', function (done) { + it('should return an array of values and scores from both sorted sets sorted by scores lowest to highest', (done) => { db.getSortedSetUnion({ sets: ['sortedSetTest2', 'sortedSetTest3'], start: 0, stop: -1, withScores: true }, function (err, data) { assert.equal(err, null); assert.equal(arguments.length, 2); @@ -987,8 +987,8 @@ describe('Sorted Set methods', function () { }); }); - describe('getSortedSetRevUnion()', function () { - it('should return an array of values from both sorted sets sorted by scores highest to lowest', function (done) { + describe('getSortedSetRevUnion()', () => { + it('should return an array of values from both sorted sets sorted by scores highest to lowest', (done) => { db.getSortedSetRevUnion({ sets: ['sortedSetTest2', 'sortedSetTest3'], start: 0, stop: -1 }, function (err, values) { assert.equal(err, null); assert.equal(arguments.length, 2); @@ -998,13 +998,13 @@ describe('Sorted Set methods', function () { }); }); - describe('sortedSetIncrBy()', function () { - it('should create a sorted set with a field set to 1', function (done) { + describe('sortedSetIncrBy()', () => { + it('should create a sorted set with a field set to 1', (done) => { db.sortedSetIncrBy('sortedIncr', 1, 'field1', function (err, newValue) { assert.equal(err, null); assert.equal(arguments.length, 2); assert.strictEqual(newValue, 1); - db.sortedSetScore('sortedIncr', 'field1', function (err, score) { + db.sortedSetScore('sortedIncr', 'field1', (err, score) => { assert.equal(err, null); assert.strictEqual(score, 1); done(); @@ -1012,12 +1012,12 @@ describe('Sorted Set methods', function () { }); }); - it('should increment a field of a sorted set by 5', function (done) { + it('should increment a field of a sorted set by 5', (done) => { db.sortedSetIncrBy('sortedIncr', 5, 'field1', function (err, newValue) { assert.equal(err, null); assert.equal(arguments.length, 2); assert.strictEqual(newValue, 6); - db.sortedSetScore('sortedIncr', 'field1', function (err, score) { + db.sortedSetScore('sortedIncr', 'field1', (err, score) => { assert.equal(err, null); assert.strictEqual(score, 6); done(); @@ -1027,16 +1027,16 @@ describe('Sorted Set methods', function () { }); - describe('sortedSetRemove()', function () { - before(function (done) { + describe('sortedSetRemove()', () => { + before((done) => { db.sortedSetAdd('sorted3', [1, 2], ['value1', 'value2'], done); }); - it('should remove an element from a sorted set', function (done) { + it('should remove an element from a sorted set', (done) => { db.sortedSetRemove('sorted3', 'value2', function (err) { assert.equal(err, null); assert.equal(arguments.length, 1); - db.isSortedSetMember('sorted3', 'value2', function (err, isMember) { + db.isSortedSetMember('sorted3', 'value2', (err, isMember) => { assert.equal(err, null); assert.equal(isMember, false); done(); @@ -1044,14 +1044,14 @@ describe('Sorted Set methods', function () { }); }); - it('should remove multiple values from multiple keys', function (done) { - db.sortedSetAdd('multiTest1', [1, 2, 3, 4], ['one', 'two', 'three', 'four'], function (err) { + it('should remove multiple values from multiple keys', (done) => { + db.sortedSetAdd('multiTest1', [1, 2, 3, 4], ['one', 'two', 'three', 'four'], (err) => { assert.ifError(err); - db.sortedSetAdd('multiTest2', [3, 4, 5, 6], ['three', 'four', 'five', 'six'], function (err) { + db.sortedSetAdd('multiTest2', [3, 4, 5, 6], ['three', 'four', 'five', 'six'], (err) => { assert.ifError(err); - db.sortedSetRemove(['multiTest1', 'multiTest2'], ['two', 'three', 'four', 'five', 'doesnt exist'], function (err) { + db.sortedSetRemove(['multiTest1', 'multiTest2'], ['two', 'three', 'four', 'five', 'doesnt exist'], (err) => { assert.ifError(err); - db.getSortedSetsMembers(['multiTest1', 'multiTest2'], function (err, members) { + db.getSortedSetsMembers(['multiTest1', 'multiTest2'], (err, members) => { assert.ifError(err); assert.equal(members[0].length, 1); assert.equal(members[1].length, 1); @@ -1063,7 +1063,7 @@ describe('Sorted Set methods', function () { }); }); - it('should remove value from multiple keys', async function () { + it('should remove value from multiple keys', async () => { await db.sortedSetAdd('multiTest3', [1, 2, 3, 4], ['one', 'two', 'three', 'four']); await db.sortedSetAdd('multiTest4', [3, 4, 5, 6], ['three', 'four', 'five', 'six']); await db.sortedSetRemove(['multiTest3', 'multiTest4'], 'three'); @@ -1071,16 +1071,16 @@ describe('Sorted Set methods', function () { assert.deepStrictEqual(await db.getSortedSetRange('multiTest4', 0, -1), ['four', 'five', 'six']); }); - it('should remove multiple values from multiple keys', function (done) { - db.sortedSetAdd('multiTest5', [1], ['one'], function (err) { + it('should remove multiple values from multiple keys', (done) => { + db.sortedSetAdd('multiTest5', [1], ['one'], (err) => { assert.ifError(err); - db.sortedSetAdd('multiTest6', [2], ['two'], function (err) { + db.sortedSetAdd('multiTest6', [2], ['two'], (err) => { assert.ifError(err); - db.sortedSetAdd('multiTest7', [3], [333], function (err) { + db.sortedSetAdd('multiTest7', [3], [333], (err) => { assert.ifError(err); - db.sortedSetRemove(['multiTest5', 'multiTest6', 'multiTest7'], ['one', 'two', 333], function (err) { + db.sortedSetRemove(['multiTest5', 'multiTest6', 'multiTest7'], ['one', 'two', 333], (err) => { assert.ifError(err); - db.getSortedSetsMembers(['multiTest5', 'multiTest6', 'multiTest7'], function (err, members) { + db.getSortedSetsMembers(['multiTest5', 'multiTest6', 'multiTest7'], (err, members) => { assert.ifError(err); assert.deepEqual(members, [[], [], []]); done(); @@ -1091,12 +1091,12 @@ describe('Sorted Set methods', function () { }); }); - it('should not remove anything if values is empty array', function (done) { - db.sortedSetAdd('removeNothing', [1, 2, 3], ['val1', 'val2', 'val3'], function (err) { + it('should not remove anything if values is empty array', (done) => { + db.sortedSetAdd('removeNothing', [1, 2, 3], ['val1', 'val2', 'val3'], (err) => { assert.ifError(err); - db.sortedSetRemove('removeNothing', [], function (err) { + db.sortedSetRemove('removeNothing', [], (err) => { assert.ifError(err); - db.getSortedSetRange('removeNothing', 0, -1, function (err, data) { + db.getSortedSetRange('removeNothing', 0, -1, (err, data) => { assert.ifError(err); assert.deepStrictEqual(data, ['val1', 'val2', 'val3']); done(); @@ -1105,7 +1105,7 @@ describe('Sorted Set methods', function () { }); }); - it('should do a bulk remove', async function () { + it('should do a bulk remove', async () => { await db.sortedSetAddBulk([ ['bulkRemove1', 1, 'value1'], ['bulkRemove1', 2, 'value2'], @@ -1121,19 +1121,19 @@ describe('Sorted Set methods', function () { }); }); - describe('sortedSetsRemove()', function () { - before(function (done) { + describe('sortedSetsRemove()', () => { + before((done) => { async.parallel([ async.apply(db.sortedSetAdd, 'sorted4', [1, 2], ['value1', 'value2']), async.apply(db.sortedSetAdd, 'sorted5', [1, 2], ['value1', 'value3']), ], done); }); - it('should remove element from multiple sorted sets', function (done) { + it('should remove element from multiple sorted sets', (done) => { db.sortedSetsRemove(['sorted4', 'sorted5'], 'value1', function (err) { assert.equal(err, null); assert.equal(arguments.length, 1); - db.sortedSetsScore(['sorted4', 'sorted5'], 'value1', function (err, scores) { + db.sortedSetsScore(['sorted4', 'sorted5'], 'value1', (err, scores) => { assert.equal(err, null); assert.deepStrictEqual(scores, [null, null]); done(); @@ -1142,16 +1142,16 @@ describe('Sorted Set methods', function () { }); }); - describe('sortedSetsRemoveRangeByScore()', function () { - before(function (done) { + describe('sortedSetsRemoveRangeByScore()', () => { + before((done) => { db.sortedSetAdd('sorted6', [1, 2, 3, 4, 5], ['value1', 'value2', 'value3', 'value4', 'value5'], done); }); - it('should remove elements with scores between min max inclusive', function (done) { + it('should remove elements with scores between min max inclusive', (done) => { db.sortedSetsRemoveRangeByScore(['sorted6'], 4, 5, function (err) { assert.ifError(err); assert.equal(arguments.length, 1); - db.getSortedSetRange('sorted6', 0, -1, function (err, values) { + db.getSortedSetRange('sorted6', 0, -1, (err, values) => { assert.ifError(err); assert.deepEqual(values, ['value1', 'value2', 'value3']); done(); @@ -1159,12 +1159,12 @@ describe('Sorted Set methods', function () { }); }); - it('should remove elements with if strin score is passed in', function (done) { - db.sortedSetAdd('sortedForRemove', [11, 22, 33], ['value1', 'value2', 'value3'], function (err) { + it('should remove elements with if strin score is passed in', (done) => { + db.sortedSetAdd('sortedForRemove', [11, 22, 33], ['value1', 'value2', 'value3'], (err) => { assert.ifError(err); - db.sortedSetsRemoveRangeByScore(['sortedForRemove'], '22', '22', function (err) { + db.sortedSetsRemoveRangeByScore(['sortedForRemove'], '22', '22', (err) => { assert.ifError(err); - db.getSortedSetRange('sortedForRemove', 0, -1, function (err, values) { + db.getSortedSetRange('sortedForRemove', 0, -1, (err, values) => { assert.ifError(err); assert.deepEqual(values, ['value1', 'value3']); done(); @@ -1174,8 +1174,8 @@ describe('Sorted Set methods', function () { }); }); - describe('getSortedSetIntersect', function () { - before(function (done) { + describe('getSortedSetIntersect', () => { + before((done) => { async.parallel([ function (next) { db.sortedSetAdd('interSet1', [1, 2, 3], ['value1', 'value2', 'value3'], next); @@ -1186,110 +1186,110 @@ describe('Sorted Set methods', function () { ], done); }); - it('should return the intersection of two sets', function (done) { + it('should return the intersection of two sets', (done) => { db.getSortedSetIntersect({ sets: ['interSet1', 'interSet2'], start: 0, stop: -1, - }, function (err, data) { + }, (err, data) => { assert.ifError(err); assert.deepEqual(['value2', 'value3'], data); done(); }); }); - it('should return the intersection of two sets with scores', function (done) { + it('should return the intersection of two sets with scores', (done) => { db.getSortedSetIntersect({ sets: ['interSet1', 'interSet2'], start: 0, stop: -1, withScores: true, - }, function (err, data) { + }, (err, data) => { assert.ifError(err); assert.deepEqual([{ value: 'value2', score: 6 }, { value: 'value3', score: 8 }], data); done(); }); }); - it('should return the reverse intersection of two sets', function (done) { + it('should return the reverse intersection of two sets', (done) => { db.getSortedSetRevIntersect({ sets: ['interSet1', 'interSet2'], start: 0, stop: 2, - }, function (err, data) { + }, (err, data) => { assert.ifError(err); assert.deepEqual(['value3', 'value2'], data); done(); }); }); - it('should return the intersection of two sets with scores aggregate MIN', function (done) { + it('should return the intersection of two sets with scores aggregate MIN', (done) => { db.getSortedSetIntersect({ sets: ['interSet1', 'interSet2'], start: 0, stop: -1, withScores: true, aggregate: 'MIN', - }, function (err, data) { + }, (err, data) => { assert.ifError(err); assert.deepEqual([{ value: 'value2', score: 2 }, { value: 'value3', score: 3 }], data); done(); }); }); - it('should return the intersection of two sets with scores aggregate MAX', function (done) { + it('should return the intersection of two sets with scores aggregate MAX', (done) => { db.getSortedSetIntersect({ sets: ['interSet1', 'interSet2'], start: 0, stop: -1, withScores: true, aggregate: 'MAX', - }, function (err, data) { + }, (err, data) => { assert.ifError(err); assert.deepEqual([{ value: 'value2', score: 4 }, { value: 'value3', score: 5 }], data); done(); }); }); - it('should return the intersection with scores modified by weights', function (done) { + it('should return the intersection with scores modified by weights', (done) => { db.getSortedSetIntersect({ sets: ['interSet1', 'interSet2'], start: 0, stop: -1, withScores: true, weights: [1, 0.5], - }, function (err, data) { + }, (err, data) => { assert.ifError(err); assert.deepEqual([{ value: 'value2', score: 4 }, { value: 'value3', score: 5.5 }], data); done(); }); }); - it('should return empty array if sets do not exist', function (done) { + it('should return empty array if sets do not exist', (done) => { db.getSortedSetIntersect({ sets: ['interSet10', 'interSet12'], start: 0, stop: -1, - }, function (err, data) { + }, (err, data) => { assert.ifError(err); assert.equal(data.length, 0); done(); }); }); - it('should return empty array if one set does not exist', function (done) { + it('should return empty array if one set does not exist', (done) => { db.getSortedSetIntersect({ sets: ['interSet1', 'interSet12'], start: 0, stop: -1, - }, function (err, data) { + }, (err, data) => { assert.ifError(err); assert.equal(data.length, 0); done(); }); }); - it('should return correct results if sorting by different zset', async function () { + it('should return correct results if sorting by different zset', async () => { await db.sortedSetAdd('bigzset', [1, 2, 3, 4, 5, 6], ['a', 'b', 'c', 'd', 'e', 'f']); await db.sortedSetAdd('smallzset', [3, 2, 1], ['b', 'e', 'g']); const data = await db.getSortedSetRevIntersect({ @@ -1310,7 +1310,7 @@ describe('Sorted Set methods', function () { assert.deepStrictEqual(data2, [{ value: 'b', score: 3 }, { value: 'e', score: 2 }]); }); - it('should return correct results when intersecting big zsets', async function () { + it('should return correct results when intersecting big zsets', async () => { const scores = []; const values = []; for (let i = 0; i < 30000; i++) { @@ -1342,8 +1342,8 @@ describe('Sorted Set methods', function () { }); }); - describe('sortedSetIntersectCard', function () { - before(function (done) { + describe('sortedSetIntersectCard', () => { + before((done) => { async.parallel([ function (next) { db.sortedSetAdd('interCard1', [0, 0, 0], ['value1', 'value2', 'value3'], next); @@ -1360,16 +1360,16 @@ describe('Sorted Set methods', function () { ], done); }); - it('should return # of elements in intersection', function (done) { - db.sortedSetIntersectCard(['interCard1', 'interCard2', 'interCard3'], function (err, count) { + it('should return # of elements in intersection', (done) => { + db.sortedSetIntersectCard(['interCard1', 'interCard2', 'interCard3'], (err, count) => { assert.ifError(err); assert.strictEqual(count, 1); done(); }); }); - it('should return 0 if intersection is empty', function (done) { - db.sortedSetIntersectCard(['interCard1', 'interCard4'], function (err, count) { + it('should return 0 if intersection is empty', (done) => { + db.sortedSetIntersectCard(['interCard1', 'interCard4'], (err, count) => { assert.ifError(err); assert.strictEqual(count, 0); done(); @@ -1377,48 +1377,48 @@ describe('Sorted Set methods', function () { }); }); - describe('getSortedSetRangeByLex', function () { - it('should return an array of all values', function (done) { - db.getSortedSetRangeByLex('sortedSetLex', '-', '+', function (err, data) { + describe('getSortedSetRangeByLex', () => { + it('should return an array of all values', (done) => { + db.getSortedSetRangeByLex('sortedSetLex', '-', '+', (err, data) => { assert.ifError(err); assert.deepEqual(data, ['a', 'b', 'c', 'd']); done(); }); }); - it('should return an array with an inclusive range by default', function (done) { - db.getSortedSetRangeByLex('sortedSetLex', 'a', 'd', function (err, data) { + it('should return an array with an inclusive range by default', (done) => { + db.getSortedSetRangeByLex('sortedSetLex', 'a', 'd', (err, data) => { assert.ifError(err); assert.deepEqual(data, ['a', 'b', 'c', 'd']); done(); }); }); - it('should return an array with an inclusive range', function (done) { - db.getSortedSetRangeByLex('sortedSetLex', '[a', '[d', function (err, data) { + it('should return an array with an inclusive range', (done) => { + db.getSortedSetRangeByLex('sortedSetLex', '[a', '[d', (err, data) => { assert.ifError(err); assert.deepEqual(data, ['a', 'b', 'c', 'd']); done(); }); }); - it('should return an array with an exclusive range', function (done) { - db.getSortedSetRangeByLex('sortedSetLex', '(a', '(d', function (err, data) { + it('should return an array with an exclusive range', (done) => { + db.getSortedSetRangeByLex('sortedSetLex', '(a', '(d', (err, data) => { assert.ifError(err); assert.deepEqual(data, ['b', 'c']); done(); }); }); - it('should return an array limited to the first two values', function (done) { - db.getSortedSetRangeByLex('sortedSetLex', '-', '+', 0, 2, function (err, data) { + it('should return an array limited to the first two values', (done) => { + db.getSortedSetRangeByLex('sortedSetLex', '-', '+', 0, 2, (err, data) => { assert.ifError(err); assert.deepEqual(data, ['a', 'b']); done(); }); }); - it('should return correct result', async function () { + it('should return correct result', async () => { await db.sortedSetAdd('sortedSetLexSearch', [0, 0, 0], ['baris:usakli:1', 'baris usakli:2', 'baris soner:3']); const query = 'baris:'; const min = query; @@ -1428,41 +1428,41 @@ describe('Sorted Set methods', function () { }); }); - describe('getSortedSetRevRangeByLex', function () { - it('should return an array of all values reversed', function (done) { - db.getSortedSetRevRangeByLex('sortedSetLex', '+', '-', function (err, data) { + describe('getSortedSetRevRangeByLex', () => { + it('should return an array of all values reversed', (done) => { + db.getSortedSetRevRangeByLex('sortedSetLex', '+', '-', (err, data) => { assert.ifError(err); assert.deepEqual(data, ['d', 'c', 'b', 'a']); done(); }); }); - it('should return an array with an inclusive range by default reversed', function (done) { - db.getSortedSetRevRangeByLex('sortedSetLex', 'd', 'a', function (err, data) { + it('should return an array with an inclusive range by default reversed', (done) => { + db.getSortedSetRevRangeByLex('sortedSetLex', 'd', 'a', (err, data) => { assert.ifError(err); assert.deepEqual(data, ['d', 'c', 'b', 'a']); done(); }); }); - it('should return an array with an inclusive range reversed', function (done) { - db.getSortedSetRevRangeByLex('sortedSetLex', '[d', '[a', function (err, data) { + it('should return an array with an inclusive range reversed', (done) => { + db.getSortedSetRevRangeByLex('sortedSetLex', '[d', '[a', (err, data) => { assert.ifError(err); assert.deepEqual(data, ['d', 'c', 'b', 'a']); done(); }); }); - it('should return an array with an exclusive range reversed', function (done) { - db.getSortedSetRevRangeByLex('sortedSetLex', '(d', '(a', function (err, data) { + it('should return an array with an exclusive range reversed', (done) => { + db.getSortedSetRevRangeByLex('sortedSetLex', '(d', '(a', (err, data) => { assert.ifError(err); assert.deepEqual(data, ['c', 'b']); done(); }); }); - it('should return an array limited to the first two values reversed', function (done) { - db.getSortedSetRevRangeByLex('sortedSetLex', '+', '-', 0, 2, function (err, data) { + it('should return an array limited to the first two values reversed', (done) => { + db.getSortedSetRevRangeByLex('sortedSetLex', '+', '-', 0, 2, (err, data) => { assert.ifError(err); assert.deepEqual(data, ['d', 'c']); done(); @@ -1470,33 +1470,33 @@ describe('Sorted Set methods', function () { }); }); - describe('sortedSetLexCount', function () { - it('should return the count of all values', function (done) { - db.sortedSetLexCount('sortedSetLex', '-', '+', function (err, data) { + describe('sortedSetLexCount', () => { + it('should return the count of all values', (done) => { + db.sortedSetLexCount('sortedSetLex', '-', '+', (err, data) => { assert.ifError(err); assert.strictEqual(data, 4); done(); }); }); - it('should return the count with an inclusive range by default', function (done) { - db.sortedSetLexCount('sortedSetLex', 'a', 'd', function (err, data) { + it('should return the count with an inclusive range by default', (done) => { + db.sortedSetLexCount('sortedSetLex', 'a', 'd', (err, data) => { assert.ifError(err); assert.strictEqual(data, 4); done(); }); }); - it('should return the count with an inclusive range', function (done) { - db.sortedSetLexCount('sortedSetLex', '[a', '[d', function (err, data) { + it('should return the count with an inclusive range', (done) => { + db.sortedSetLexCount('sortedSetLex', '[a', '[d', (err, data) => { assert.ifError(err); assert.strictEqual(data, 4); done(); }); }); - it('should return the count with an exclusive range', function (done) { - db.sortedSetLexCount('sortedSetLex', '(a', '(d', function (err, data) { + it('should return the count with an exclusive range', (done) => { + db.sortedSetLexCount('sortedSetLex', '(a', '(d', (err, data) => { assert.ifError(err); assert.strictEqual(data, 2); done(); @@ -1504,16 +1504,16 @@ describe('Sorted Set methods', function () { }); }); - describe('sortedSetRemoveRangeByLex', function () { - before(function (done) { + describe('sortedSetRemoveRangeByLex', () => { + before((done) => { db.sortedSetAdd('sortedSetLex2', [0, 0, 0, 0, 0, 0, 0], ['a', 'b', 'c', 'd', 'e', 'f', 'g'], done); }); - it('should remove an inclusive range by default', function (done) { + it('should remove an inclusive range by default', (done) => { db.sortedSetRemoveRangeByLex('sortedSetLex2', 'a', 'b', function (err) { assert.ifError(err); assert.equal(arguments.length, 1); - db.getSortedSetRangeByLex('sortedSetLex2', '-', '+', function (err, data) { + db.getSortedSetRangeByLex('sortedSetLex2', '-', '+', (err, data) => { assert.ifError(err); assert.deepEqual(data, ['c', 'd', 'e', 'f', 'g']); done(); @@ -1521,11 +1521,11 @@ describe('Sorted Set methods', function () { }); }); - it('should remove an inclusive range', function (done) { + it('should remove an inclusive range', (done) => { db.sortedSetRemoveRangeByLex('sortedSetLex2', '[c', '[d', function (err) { assert.ifError(err); assert.equal(arguments.length, 1); - db.getSortedSetRangeByLex('sortedSetLex2', '-', '+', function (err, data) { + db.getSortedSetRangeByLex('sortedSetLex2', '-', '+', (err, data) => { assert.ifError(err); assert.deepEqual(data, ['e', 'f', 'g']); done(); @@ -1533,11 +1533,11 @@ describe('Sorted Set methods', function () { }); }); - it('should remove an exclusive range', function (done) { + it('should remove an exclusive range', (done) => { db.sortedSetRemoveRangeByLex('sortedSetLex2', '(e', '(g', function (err) { assert.ifError(err); assert.equal(arguments.length, 1); - db.getSortedSetRangeByLex('sortedSetLex2', '-', '+', function (err, data) { + db.getSortedSetRangeByLex('sortedSetLex2', '-', '+', (err, data) => { assert.ifError(err); assert.deepEqual(data, ['e', 'g']); done(); @@ -1545,11 +1545,11 @@ describe('Sorted Set methods', function () { }); }); - it('should remove all values', function (done) { + it('should remove all values', (done) => { db.sortedSetRemoveRangeByLex('sortedSetLex2', '-', '+', function (err) { assert.ifError(err); assert.equal(arguments.length, 1); - db.getSortedSetRangeByLex('sortedSetLex2', '-', '+', function (err, data) { + db.getSortedSetRangeByLex('sortedSetLex2', '-', '+', (err, data) => { assert.ifError(err); assert.deepEqual(data, []); done(); diff --git a/test/defer-logger.js b/test/defer-logger.js index e6cdf1b721..7a07fd1c4a 100644 --- a/test/defer-logger.js +++ b/test/defer-logger.js @@ -21,17 +21,17 @@ class DeferLogger extends Transport { } } -before(function () { +before(() => { // defer winston logs until the end winston.clear(); winston.add(new DeferLogger({ logged: winstonLogged })); }); -after(function () { +after(() => { console.log('\n\n'); - winstonLogged.forEach(function (args) { + winstonLogged.forEach((args) => { console.log(`${args[0]} ${args[1]}`); }); }); diff --git a/test/emailer.js b/test/emailer.js index 689156102a..f9412d0769 100644 --- a/test/emailer.js +++ b/test/emailer.js @@ -10,7 +10,7 @@ var Plugins = require('../src/plugins'); var Emailer = require('../src/emailer'); var Meta = require('../src/meta'); -describe('emailer', function () { +describe('emailer', () => { var onMail = function (address, session, callback) { callback(); }; var onTo = function (address, session, callback) { callback(); }; @@ -21,7 +21,7 @@ describe('emailer', function () { subject: 'Welcome to NodeBB', }; - before(function (done) { + before((done) => { var server = new SMTPServer({ allowInsecureAuth: true, onAuth: function (auth, session, callback) { @@ -37,7 +37,7 @@ describe('emailer', function () { }, }); - server.on('error', function (err) { + server.on('error', (err) => { throw err; }); server.listen(4000, done); @@ -45,7 +45,7 @@ describe('emailer', function () { // TODO: test sendmail here at some point - it('plugin hook should work', function (done) { + it('plugin hook should work', (done) => { var error = new Error(); Plugins.hooks.register('emailer-test', { @@ -59,7 +59,7 @@ describe('emailer', function () { }, }); - Emailer.sendToEmail(template, email, language, params, function (err) { + Emailer.sendToEmail(template, email, language, params, (err) => { assert.equal(err, error); Plugins.hooks.unregister('emailer-test', 'filter:email.send'); @@ -67,21 +67,21 @@ describe('emailer', function () { }); }); - it('should build custom template on config change', function (done) { + it('should build custom template on config change', (done) => { var text = 'a random string of text'; // make sure it's not already set - Emailer.renderAndTranslate('test', {}, 'en-GB', function (err, output) { + Emailer.renderAndTranslate('test', {}, 'en-GB', (err, output) => { assert.ifError(err); assert.notEqual(output, text); - Meta.configs.set('email:custom:test', text, function (err) { + Meta.configs.set('email:custom:test', text, (err) => { assert.ifError(err); // wait for pubsub stuff - setTimeout(function () { - Emailer.renderAndTranslate('test', {}, 'en-GB', function (err, output) { + setTimeout(() => { + Emailer.renderAndTranslate('test', {}, 'en-GB', (err, output) => { assert.ifError(err); assert.equal(output, text); @@ -92,7 +92,7 @@ describe('emailer', function () { }); }); - it('should send via SMTP', function (done) { + it('should send via SMTP', (done) => { var from = 'admin@example.org'; var username = 'another@example.com'; @@ -119,21 +119,21 @@ describe('emailer', function () { 'email:smtpTransport:host': 'localhost', 'email:smtpTransport:security': 'NONE', 'email:from': from, - }, function (err) { + }, (err) => { assert.ifError(err); // delay so emailer has a chance to update after config changes - setTimeout(function () { + setTimeout(() => { assert.equal(Emailer.fallbackTransport, Emailer.transports.smtp); - Emailer.sendToEmail(template, email, language, params, function (err) { + Emailer.sendToEmail(template, email, language, params, (err) => { assert.ifError(err); }); }, 200); }); }); - after(function (done) { + after((done) => { fs.unlinkSync(path.join(__dirname, '../build/public/templates/emails/test.js')); Meta.configs.setMultiple({ 'email:smtpTransport:enabled': '0', diff --git a/test/feeds.js b/test/feeds.js index bbfdc6da79..06aa208f6a 100644 --- a/test/feeds.js +++ b/test/feeds.js @@ -14,12 +14,12 @@ var meta = require('../src/meta'); var privileges = require('../src/privileges'); var helpers = require('./helpers'); -describe('feeds', function () { +describe('feeds', () => { var tid; var pid; var fooUid; var cid; - before(function (done) { + before((done) => { meta.config['feeds:disableRSS'] = 1; async.series({ category: function (next) { @@ -31,14 +31,14 @@ describe('feeds', function () { user: function (next) { user.create({ username: 'foo', password: 'barbar', email: 'foo@test.com' }, next); }, - }, function (err, results) { + }, (err, results) => { if (err) { return done(err); } cid = results.category.cid; fooUid = results.user; - topics.post({ uid: results.user, title: 'test topic title', content: 'test topic content', cid: results.category.cid }, function (err, result) { + topics.post({ uid: results.user, title: 'test topic title', content: 'test topic content', cid: results.category.cid }, (err, result) => { tid = result.topicData.tid; pid = result.postData.pid; done(err); @@ -47,7 +47,7 @@ describe('feeds', function () { }); - it('should 404', function (done) { + it('should 404', (done) => { var feedUrls = [ `${nconf.get('url')}/topic/${tid}.rss`, `${nconf.get('url')}/category/${cid}.rss`, @@ -61,39 +61,39 @@ describe('feeds', function () { `${nconf.get('url')}/user/foo/topics.rss`, `${nconf.get('url')}/tags/nodebb.rss`, ]; - async.eachSeries(feedUrls, function (url, next) { - request(url, function (err, res) { + async.eachSeries(feedUrls, (url, next) => { + request(url, (err, res) => { assert.ifError(err); assert.equal(res.statusCode, 404); next(); }); - }, function (err) { + }, (err) => { assert.ifError(err); meta.config['feeds:disableRSS'] = 0; done(); }); }); - it('should 404 if topic does not exist', function (done) { - request(`${nconf.get('url')}/topic/${1000}.rss`, function (err, res) { + it('should 404 if topic does not exist', (done) => { + request(`${nconf.get('url')}/topic/${1000}.rss`, (err, res) => { assert.ifError(err); assert.equal(res.statusCode, 404); done(); }); }); - it('should 404 if category id is not a number', function (done) { - request(`${nconf.get('url')}/category/invalid.rss`, function (err, res) { + it('should 404 if category id is not a number', (done) => { + request(`${nconf.get('url')}/category/invalid.rss`, (err, res) => { assert.ifError(err); assert.equal(res.statusCode, 404); done(); }); }); - it('should redirect if we do not have read privilege', function (done) { - privileges.categories.rescind(['groups:topics:read'], cid, 'guests', function (err) { + it('should redirect if we do not have read privilege', (done) => { + privileges.categories.rescind(['groups:topics:read'], cid, 'guests', (err) => { assert.ifError(err); - request(`${nconf.get('url')}/topic/${tid}.rss`, function (err, res, body) { + request(`${nconf.get('url')}/topic/${tid}.rss`, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -103,18 +103,18 @@ describe('feeds', function () { }); }); - it('should 404 if user is not found', function (done) { - request(`${nconf.get('url')}/user/doesnotexist/topics.rss`, function (err, res) { + it('should 404 if user is not found', (done) => { + request(`${nconf.get('url')}/user/doesnotexist/topics.rss`, (err, res) => { assert.ifError(err); assert.equal(res.statusCode, 404); done(); }); }); - it('should redirect if we do not have read privilege', function (done) { - privileges.categories.rescind(['groups:read'], cid, 'guests', function (err) { + it('should redirect if we do not have read privilege', (done) => { + privileges.categories.rescind(['groups:read'], cid, 'guests', (err) => { assert.ifError(err); - request(`${nconf.get('url')}/category/${cid}.rss`, function (err, res, body) { + request(`${nconf.get('url')}/category/${cid}.rss`, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -124,19 +124,19 @@ describe('feeds', function () { }); }); - describe('private feeds and tokens', function () { + describe('private feeds and tokens', () => { var jar; var rssToken; - before(function (done) { - helpers.loginUser('foo', 'barbar', function (err, _jar) { + before((done) => { + helpers.loginUser('foo', 'barbar', (err, _jar) => { assert.ifError(err); jar = _jar; done(); }); }); - it('should load feed if its not private', function (done) { - request(`${nconf.get('url')}/category/${cid}.rss`, { }, function (err, res, body) { + it('should load feed if its not private', (done) => { + request(`${nconf.get('url')}/category/${cid}.rss`, { }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -145,8 +145,8 @@ describe('feeds', function () { }); - it('should not allow access if uid or token is missing', function (done) { - privileges.categories.rescind(['groups:read'], cid, 'guests', function (err) { + it('should not allow access if uid or token is missing', (done) => { + privileges.categories.rescind(['groups:read'], cid, 'guests', (err) => { assert.ifError(err); async.parallel({ test1: function (next) { @@ -155,7 +155,7 @@ describe('feeds', function () { test2: function (next) { request(`${nconf.get('url')}/category/${cid}.rss?token=sometoken`, { }, next); }, - }, function (err, results) { + }, (err, results) => { assert.ifError(err); assert.equal(results.test1[0].statusCode, 200); assert.equal(results.test2[0].statusCode, 200); @@ -166,8 +166,8 @@ describe('feeds', function () { }); }); - it('should not allow access if token is wrong', function (done) { - request(`${nconf.get('url')}/category/${cid}.rss?uid=${fooUid}&token=sometoken`, { }, function (err, res, body) { + it('should not allow access if token is wrong', (done) => { + request(`${nconf.get('url')}/category/${cid}.rss?uid=${fooUid}&token=sometoken`, { }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body.includes('Login to your account')); @@ -175,11 +175,11 @@ describe('feeds', function () { }); }); - it('should allow access if token is correct', function (done) { - request(`${nconf.get('url')}/api/category/${cid}`, { jar: jar, json: true }, function (err, res, body) { + it('should allow access if token is correct', (done) => { + request(`${nconf.get('url')}/api/category/${cid}`, { jar: jar, json: true }, (err, res, body) => { assert.ifError(err); rssToken = body.rssFeedUrl.split('token')[1].slice(1); - request(`${nconf.get('url')}/category/${cid}.rss?uid=${fooUid}&token=${rssToken}`, { }, function (err, res, body) { + request(`${nconf.get('url')}/category/${cid}.rss?uid=${fooUid}&token=${rssToken}`, { }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body.startsWith(' { + privileges.categories.rescind(['groups:read'], cid, 'registered-users', (err) => { assert.ifError(err); - request(`${nconf.get('url')}/category/${cid}.rss?uid=${fooUid}&token=${rssToken}`, { }, function (err, res, body) { + request(`${nconf.get('url')}/category/${cid}.rss?uid=${fooUid}&token=${rssToken}`, { }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body.includes('Login to your account')); diff --git a/test/file.js b/test/file.js index daf7686d0f..479202d7e8 100644 --- a/test/file.js +++ b/test/file.js @@ -8,21 +8,21 @@ var nconf = require('nconf'); var utils = require('../src/utils'); var file = require('../src/file'); -describe('file', function () { +describe('file', () => { var filename = `${utils.generateUUID()}.png`; var folder = 'files'; var uploadPath = path.join(nconf.get('upload_path'), folder, filename); var tempPath = path.join(__dirname, './files/test.png'); - afterEach(function (done) { - fs.unlink(uploadPath, function () { + afterEach((done) => { + fs.unlink(uploadPath, () => { done(); }); }); - describe('copyFile', function () { - it('should copy a file', function (done) { - fs.copyFile(tempPath, uploadPath, function (err) { + describe('copyFile', () => { + it('should copy a file', (done) => { + fs.copyFile(tempPath, uploadPath, (err) => { assert.ifError(err); assert(file.existsSync(uploadPath)); @@ -35,10 +35,10 @@ describe('file', function () { }); }); - it('should override an existing file', function (done) { + it('should override an existing file', (done) => { fs.writeFileSync(uploadPath, 'hsdkjhgkjsfhkgj'); - fs.copyFile(tempPath, uploadPath, function (err) { + fs.copyFile(tempPath, uploadPath, (err) => { assert.ifError(err); assert(file.existsSync(uploadPath)); @@ -51,8 +51,8 @@ describe('file', function () { }); }); - it('should error if source file does not exist', function (done) { - fs.copyFile(`${tempPath}0000000000`, uploadPath, function (err) { + it('should error if source file does not exist', (done) => { + fs.copyFile(`${tempPath}0000000000`, uploadPath, (err) => { assert(err); assert.strictEqual(err.code, 'ENOENT'); @@ -60,11 +60,11 @@ describe('file', function () { }); }); - it('should error if existing file is read only', function (done) { + it('should error if existing file is read only', (done) => { fs.writeFileSync(uploadPath, 'hsdkjhgkjsfhkgj'); fs.chmodSync(uploadPath, '444'); - fs.copyFile(tempPath, uploadPath, function (err) { + fs.copyFile(tempPath, uploadPath, (err) => { assert(err); assert(err.code === 'EPERM' || err.code === 'EACCES'); @@ -73,9 +73,9 @@ describe('file', function () { }); }); - describe('saveFileToLocal', function () { - it('should work', function (done) { - file.saveFileToLocal(filename, folder, tempPath, function (err) { + describe('saveFileToLocal', () => { + it('should work', (done) => { + file.saveFileToLocal(filename, folder, tempPath, (err) => { assert.ifError(err); assert(file.existsSync(uploadPath)); @@ -88,8 +88,8 @@ describe('file', function () { }); }); - it('should error if source does not exist', function (done) { - file.saveFileToLocal(filename, folder, `${tempPath}000000000`, function (err) { + it('should error if source does not exist', (done) => { + file.saveFileToLocal(filename, folder, `${tempPath}000000000`, (err) => { assert(err); assert.strictEqual(err.code, 'ENOENT'); @@ -97,8 +97,8 @@ describe('file', function () { }); }); - it('should error if folder is relative', function (done) { - file.saveFileToLocal(filename, '../../text', `${tempPath}000000000`, function (err) { + it('should error if folder is relative', (done) => { + file.saveFileToLocal(filename, '../../text', `${tempPath}000000000`, (err) => { assert(err); assert.strictEqual(err.message, '[[error:invalid-path]]'); done(); @@ -106,15 +106,15 @@ describe('file', function () { }); }); - it('should walk directory', function (done) { - file.walk(__dirname, function (err, data) { + it('should walk directory', (done) => { + file.walk(__dirname, (err, data) => { assert.ifError(err); assert(Array.isArray(data)); done(); }); }); - it('should convert mime type to extension', function (done) { + it('should convert mime type to extension', (done) => { assert.equal(file.typeToExtension('image/png'), '.png'); assert.equal(file.typeToExtension(''), ''); done(); diff --git a/test/flags.js b/test/flags.js index 402706d074..7d197b41ea 100644 --- a/test/flags.js +++ b/test/flags.js @@ -16,7 +16,7 @@ const Groups = require('../src/groups'); const Meta = require('../src/meta'); const Privileges = require('../src/privileges'); -describe('Flags', function () { +describe('Flags', () => { let uid1; let adminUid; let uid3; @@ -43,9 +43,9 @@ describe('Flags', function () { }); }); - describe('.create()', function () { - it('should create a flag and return its data', function (done) { - Flags.create('post', 1, 1, 'Test flag', function (err, flagData) { + describe('.create()', () => { + it('should create a flag and return its data', (done) => { + Flags.create('post', 1, 1, 'Test flag', (err, flagData) => { assert.ifError(err); var compare = { flagId: 1, @@ -66,16 +66,16 @@ describe('Flags', function () { }); }); - it('should add the flag to the byCid zset for category 1 if it is of type post', function (done) { - db.isSortedSetMember(`flags:byCid:${1}`, 1, function (err, isMember) { + it('should add the flag to the byCid zset for category 1 if it is of type post', (done) => { + db.isSortedSetMember(`flags:byCid:${1}`, 1, (err, isMember) => { assert.ifError(err); assert.ok(isMember); done(); }); }); - it('should add the flag to the byPid zset for pid 1 if it is of type post', function (done) { - db.isSortedSetMember(`flags:byPid:${1}`, 1, function (err, isMember) { + it('should add the flag to the byPid zset for pid 1 if it is of type post', (done) => { + db.isSortedSetMember(`flags:byPid:${1}`, 1, (err, isMember) => { assert.ifError(err); assert.ok(isMember); done(); @@ -83,17 +83,17 @@ describe('Flags', function () { }); }); - describe('.exists()', function () { - it('should return Boolean True if a flag matching the flag hash already exists', function (done) { - Flags.exists('post', 1, 1, function (err, exists) { + describe('.exists()', () => { + it('should return Boolean True if a flag matching the flag hash already exists', (done) => { + Flags.exists('post', 1, 1, (err, exists) => { assert.ifError(err); assert.strictEqual(true, exists); done(); }); }); - it('should return Boolean False if a flag matching the flag hash does not already exists', function (done) { - Flags.exists('post', 1, 2, function (err, exists) { + it('should return Boolean False if a flag matching the flag hash does not already exists', (done) => { + Flags.exists('post', 1, 2, (err, exists) => { assert.ifError(err); assert.strictEqual(false, exists); done(); @@ -101,17 +101,17 @@ describe('Flags', function () { }); }); - describe('.targetExists()', function () { - it('should return Boolean True if the targeted element exists', function (done) { - Flags.targetExists('post', 1, function (err, exists) { + describe('.targetExists()', () => { + it('should return Boolean True if the targeted element exists', (done) => { + Flags.targetExists('post', 1, (err, exists) => { assert.ifError(err); assert.strictEqual(true, exists); done(); }); }); - it('should return Boolean False if the targeted element does not exist', function (done) { - Flags.targetExists('post', 15, function (err, exists) { + it('should return Boolean False if the targeted element does not exist', (done) => { + Flags.targetExists('post', 15, (err, exists) => { assert.ifError(err); assert.strictEqual(false, exists); done(); @@ -119,9 +119,9 @@ describe('Flags', function () { }); }); - describe('.get()', function () { - it('should retrieve and display a flag\'s data', function (done) { - Flags.get(1, function (err, flagData) { + describe('.get()', () => { + it('should retrieve and display a flag\'s data', (done) => { + Flags.get(1, (err, flagData) => { assert.ifError(err); var compare = { flagId: 1, @@ -143,12 +143,12 @@ describe('Flags', function () { }); }); - describe('.list()', function () { - it('should show a list of flags (with one item)', function (done) { + describe('.list()', () => { + it('should show a list of flags (with one item)', (done) => { Flags.list({ filters: {}, uid: 1, - }, function (err, payload) { + }, (err, payload) => { assert.ifError(err); assert.ok(payload.hasOwnProperty('flags')); assert.ok(payload.hasOwnProperty('page')); @@ -156,7 +156,7 @@ describe('Flags', function () { assert.ok(Array.isArray(payload.flags)); assert.equal(payload.flags.length, 1); - Flags.get(payload.flags[0].flagId, function (err, flagData) { + Flags.get(payload.flags[0].flagId, (err, flagData) => { assert.ifError(err); assert.equal(payload.flags[0].flagId, flagData.flagId); assert.equal(payload.flags[0].description, flagData.description); @@ -165,14 +165,14 @@ describe('Flags', function () { }); }); - describe('(with filters)', function () { - it('should return a filtered list of flags if said filters are passed in', function (done) { + describe('(with filters)', () => { + it('should return a filtered list of flags if said filters are passed in', (done) => { Flags.list({ filters: { state: 'open', }, uid: 1, - }, function (err, payload) { + }, (err, payload) => { assert.ifError(err); assert.ok(payload.hasOwnProperty('flags')); assert.ok(payload.hasOwnProperty('page')); @@ -183,13 +183,13 @@ describe('Flags', function () { }); }); - it('should return no flags if a filter with no matching flags is used', function (done) { + it('should return no flags if a filter with no matching flags is used', (done) => { Flags.list({ filters: { state: 'rejected', }, uid: 1, - }, function (err, payload) { + }, (err, payload) => { assert.ifError(err); assert.ok(payload.hasOwnProperty('flags')); assert.ok(payload.hasOwnProperty('page')); @@ -200,13 +200,13 @@ describe('Flags', function () { }); }); - it('should return a flag when filtered by cid 1', function (done) { + it('should return a flag when filtered by cid 1', (done) => { Flags.list({ filters: { cid: 1, }, uid: 1, - }, function (err, payload) { + }, (err, payload) => { assert.ifError(err); assert.ok(payload.hasOwnProperty('flags')); assert.ok(payload.hasOwnProperty('page')); @@ -217,13 +217,13 @@ describe('Flags', function () { }); }); - it('shouldn\'t return a flag when filtered by cid 2', function (done) { + it('shouldn\'t return a flag when filtered by cid 2', (done) => { Flags.list({ filters: { cid: 2, }, uid: 1, - }, function (err, payload) { + }, (err, payload) => { assert.ifError(err); assert.ok(payload.hasOwnProperty('flags')); assert.ok(payload.hasOwnProperty('page')); @@ -234,13 +234,13 @@ describe('Flags', function () { }); }); - it('should return a flag when filtered by both cid 1 and 2', function (done) { + it('should return a flag when filtered by both cid 1 and 2', (done) => { Flags.list({ filters: { cid: [1, 2], }, uid: 1, - }, function (err, payload) { + }, (err, payload) => { assert.ifError(err); assert.ok(payload.hasOwnProperty('flags')); assert.ok(payload.hasOwnProperty('page')); @@ -251,14 +251,14 @@ describe('Flags', function () { }); }); - it('should return one flag if filtered by both cid 1 and 2 and open state', function (done) { + it('should return one flag if filtered by both cid 1 and 2 and open state', (done) => { Flags.list({ filters: { cid: [1, 2], state: 'open', }, uid: 1, - }, function (err, payload) { + }, (err, payload) => { assert.ifError(err); assert.ok(payload.hasOwnProperty('flags')); assert.ok(payload.hasOwnProperty('page')); @@ -269,14 +269,14 @@ describe('Flags', function () { }); }); - it('should return no flag if filtered by both cid 1 and 2 and non-open state', function (done) { + it('should return no flag if filtered by both cid 1 and 2 and non-open state', (done) => { Flags.list({ filters: { cid: [1, 2], state: 'resolved', }, uid: 1, - }, function (err, payload) { + }, (err, payload) => { assert.ifError(err); assert.ok(payload.hasOwnProperty('flags')); assert.ok(payload.hasOwnProperty('page')); @@ -349,14 +349,14 @@ describe('Flags', function () { }); }); - describe('.update()', function () { - it('should alter a flag\'s various attributes and persist them to the database', function (done) { + describe('.update()', () => { + it('should alter a flag\'s various attributes and persist them to the database', (done) => { Flags.update(1, adminUid, { state: 'wip', assignee: adminUid, - }, function (err) { + }, (err) => { assert.ifError(err); - db.getObjectFields('flag:1', ['state', 'assignee'], function (err, data) { + db.getObjectFields('flag:1', ['state', 'assignee'], (err, data) => { if (err) { throw err; } @@ -369,13 +369,13 @@ describe('Flags', function () { }); }); - it('should persist to the flag\'s history', function (done) { - Flags.getHistory(1, function (err, history) { + it('should persist to the flag\'s history', (done) => { + Flags.getHistory(1, (err, history) => { if (err) { throw err; } - history.forEach(function (change) { + history.forEach((change) => { switch (change.attribute) { case 'state': assert.strictEqual('[[flags:state-wip]]', change.value); @@ -473,9 +473,9 @@ describe('Flags', function () { }); }); - describe('.getTarget()', function () { - it('should return a post\'s data if queried with type "post"', function (done) { - Flags.getTarget('post', 1, 1, function (err, data) { + describe('.getTarget()', () => { + it('should return a post\'s data if queried with type "post"', (done) => { + Flags.getTarget('post', 1, 1, (err, data) => { assert.ifError(err); var compare = { uid: 1, @@ -494,8 +494,8 @@ describe('Flags', function () { }); }); - it('should return a user\'s data if queried with type "user"', function (done) { - Flags.getTarget('user', 1, 1, function (err, data) { + it('should return a user\'s data if queried with type "user"', (done) => { + Flags.getTarget('user', 1, 1, (err, data) => { assert.ifError(err); var compare = { uid: 1, @@ -514,8 +514,8 @@ describe('Flags', function () { }); }); - it('should return a plain object with no properties if the target no longer exists', function (done) { - Flags.getTarget('user', 15, 1, function (err, data) { + it('should return a plain object with no properties if the target no longer exists', (done) => { + Flags.getTarget('user', 15, 1, (err, data) => { assert.ifError(err); assert.strictEqual(0, Object.keys(data).length); done(); @@ -523,9 +523,9 @@ describe('Flags', function () { }); }); - describe('.validate()', function () { - it('should error out if type is post and post is deleted', function (done) { - Posts.delete(1, 1, function (err) { + describe('.validate()', () => { + it('should error out if type is post and post is deleted', (done) => { + Posts.delete(1, 1, (err) => { if (err) { throw err; } @@ -534,7 +534,7 @@ describe('Flags', function () { type: 'post', id: 1, uid: 1, - }, function (err) { + }, (err) => { assert.ok(err); assert.strictEqual('[[error:post-deleted]]', err.message); Posts.restore(1, 1, done); @@ -542,15 +542,15 @@ describe('Flags', function () { }); }); - it('should not pass validation if flag threshold is set and user rep does not meet it', function (done) { - Meta.configs.set('min:rep:flag', '50', function (err) { + it('should not pass validation if flag threshold is set and user rep does not meet it', (done) => { + Meta.configs.set('min:rep:flag', '50', (err) => { assert.ifError(err); Flags.validate({ type: 'post', id: 1, uid: 3, - }, function (err) { + }, (err) => { assert.ok(err); assert.strictEqual('[[error:not-enough-reputation-to-flag]]', err.message); Meta.configs.set('min:rep:flag', 0, done); @@ -558,7 +558,7 @@ describe('Flags', function () { }); }); - it('should not error if user blocked target', function (done) { + it('should not error if user blocked target', (done) => { var SocketFlags = require('../src/socket.io/flags.js'); var reporterUid; var reporteeUid; @@ -588,20 +588,20 @@ describe('Flags', function () { ], done); }); - it('should send back error if reporter does not exist', function (done) { - Flags.validate({ uid: 123123123, id: 1, type: 'post' }, function (err) { + it('should send back error if reporter does not exist', (done) => { + Flags.validate({ uid: 123123123, id: 1, type: 'post' }, (err) => { assert.equal(err.message, '[[error:no-user]]'); done(); }); }); }); - describe('.appendNote()', function () { - it('should add a note to a flag', function (done) { - Flags.appendNote(1, 1, 'this is my note', function (err) { + describe('.appendNote()', () => { + it('should add a note to a flag', (done) => { + Flags.appendNote(1, 1, 'this is my note', (err) => { assert.ifError(err); - db.getSortedSetRange('flag:1:notes', 0, -1, function (err, notes) { + db.getSortedSetRange('flag:1:notes', 0, -1, (err, notes) => { if (err) { throw err; } @@ -612,8 +612,8 @@ describe('Flags', function () { }); }); - it('should be a JSON string', function (done) { - db.getSortedSetRange('flag:1:notes', 0, -1, function (err, notes) { + it('should be a JSON string', (done) => { + db.getSortedSetRange('flag:1:notes', 0, -1, (err, notes) => { if (err) { throw err; } @@ -629,14 +629,14 @@ describe('Flags', function () { }); }); - describe('.getNotes()', function () { - before(function (done) { + describe('.getNotes()', () => { + before((done) => { // Add a second note Flags.appendNote(1, 1, 'this is the second note', done); }); - it('return should match a predefined spec', function (done) { - Flags.getNotes(1, function (err, notes) { + it('return should match a predefined spec', (done) => { + Flags.getNotes(1, (err, notes) => { assert.ifError(err); var compare = { uid: 1, @@ -655,8 +655,8 @@ describe('Flags', function () { }); }); - it('should retrieve a list of notes, from newest to oldest', function (done) { - Flags.getNotes(1, function (err, notes) { + it('should retrieve a list of notes, from newest to oldest', (done) => { + Flags.getNotes(1, (err, notes) => { assert.ifError(err); assert(notes[0].datetime > notes[1].datetime, `${notes[0].datetime}-${notes[1].datetime}`); assert.strictEqual('this is the second note', notes[0].content); @@ -665,22 +665,22 @@ describe('Flags', function () { }); }); - describe('.appendHistory()', function () { + describe('.appendHistory()', () => { var entries; - before(function (done) { - db.sortedSetCard('flag:1:history', function (err, count) { + before((done) => { + db.sortedSetCard('flag:1:history', (err, count) => { entries = count; done(err); }); }); - it('should add a new entry into a flag\'s history', function (done) { + it('should add a new entry into a flag\'s history', (done) => { Flags.appendHistory(1, 1, { state: 'rejected', - }, function (err) { + }, (err) => { assert.ifError(err); - Flags.getHistory(1, function (err, history) { + Flags.getHistory(1, (err, history) => { if (err) { throw err; } @@ -693,9 +693,9 @@ describe('Flags', function () { }); }); - describe('.getHistory()', function () { - it('should retrieve a flag\'s history', function (done) { - Flags.getHistory(1, function (err, history) { + describe('.getHistory()', () => { + it('should retrieve a flag\'s history', (done) => { + Flags.getHistory(1, (err, history) => { assert.ifError(err); assert.strictEqual(history[0].fields.state, '[[flags:state-rejected]]'); done(); @@ -703,33 +703,33 @@ describe('Flags', function () { }); }); - describe('(websockets)', function () { + describe('(websockets)', () => { var SocketFlags = require('../src/socket.io/flags.js'); var pid; - before(function (done) { + before((done) => { Topics.post({ cid: 1, uid: 1, title: 'Another topic', content: 'This is flaggable content', - }, function (err, topic) { + }, (err, topic) => { pid = topic.postData.pid; done(err); }); }); - describe('.create()', function () { - it('should create a flag with no errors', function (done) { + describe('.create()', () => { + it('should create a flag with no errors', (done) => { SocketFlags.create({ uid: 2 }, { type: 'post', id: pid, reason: 'foobar', - }, function (err) { + }, (err) => { assert.ifError(err); - Flags.exists('post', pid, 1, function (err, exists) { + Flags.exists('post', pid, 1, (err, exists) => { assert.ifError(err); assert(true); done(); @@ -737,7 +737,7 @@ describe('Flags', function () { }); }); - it('should not allow flagging post in private category', async function () { + it('should not allow flagging post in private category', async () => { const category = await Categories.create({ name: 'private category' }); await Privileges.categories.rescind(['groups:topics:read'], category.cid, 'registered-users'); @@ -756,15 +756,15 @@ describe('Flags', function () { }); }); - describe('.update()', function () { - it('should update a flag\'s properties', function (done) { + describe('.update()', () => { + it('should update a flag\'s properties', (done) => { SocketFlags.update({ uid: 2 }, { flagId: 2, data: [{ name: 'state', value: 'wip', }], - }, function (err, history) { + }, (err, history) => { assert.ifError(err); assert(Array.isArray(history)); assert(history[0].fields.hasOwnProperty('state')); @@ -774,12 +774,12 @@ describe('Flags', function () { }); }); - describe('.appendNote()', function () { - it('should append a note to the flag', function (done) { + describe('.appendNote()', () => { + it('should append a note to the flag', (done) => { SocketFlags.appendNote({ uid: 2 }, { flagId: 2, note: 'lorem ipsum dolor sit amet', - }, function (err, data) { + }, (err, data) => { assert.ifError(err); assert(data.hasOwnProperty('notes')); assert(Array.isArray(data.notes)); diff --git a/test/groups.js b/test/groups.js index b24521c34f..bc591be310 100644 --- a/test/groups.js +++ b/test/groups.js @@ -14,10 +14,10 @@ var meta = require('../src/meta'); var navigation = require('../src/navigation/admin'); -describe('Groups', function () { +describe('Groups', () => { var adminUid; var testUid; - before(async function () { + before(async () => { const navData = require('../install/data/navigation.json'); await navigation.save(navData); @@ -74,9 +74,9 @@ describe('Groups', function () { await Groups.join('administrators', adminUid); }); - describe('.list()', function () { - it('should list the groups present', function (done) { - Groups.getGroupsFromSet('groups:visible:createtime', 0, -1, function (err, groups) { + describe('.list()', () => { + it('should list the groups present', (done) => { + Groups.getGroupsFromSet('groups:visible:createtime', 0, -1, (err, groups) => { assert.ifError(err); assert.equal(groups.length, 5); done(); @@ -84,13 +84,13 @@ describe('Groups', function () { }); }); - describe('.get()', function () { - before(function (done) { + describe('.get()', () => { + before((done) => { Groups.join('Test', testUid, done); }); - it('with no options, should show group information', function (done) { - Groups.get('Test', {}, function (err, groupObj) { + it('with no options, should show group information', (done) => { + Groups.get('Test', {}, (err, groupObj) => { assert.ifError(err); assert.equal(typeof groupObj, 'object'); assert(Array.isArray(groupObj.members)); @@ -103,8 +103,8 @@ describe('Groups', function () { }); }); - it('should return null if group does not exist', function (done) { - Groups.get('doesnotexist', {}, function (err, groupObj) { + it('should return null if group does not exist', (done) => { + Groups.get('doesnotexist', {}, (err, groupObj) => { assert.ifError(err); assert.strictEqual(groupObj, null); done(); @@ -112,27 +112,27 @@ describe('Groups', function () { }); }); - describe('.search()', function () { + describe('.search()', () => { var socketGroups = require('../src/socket.io/groups'); - it('should return empty array if query is falsy', function (done) { - Groups.search(null, {}, function (err, groups) { + it('should return empty array if query is falsy', (done) => { + Groups.search(null, {}, (err, groups) => { assert.ifError(err); assert.equal(0, groups.length); done(); }); }); - it('should return the groups when search query is empty', function (done) { - socketGroups.search({ uid: adminUid }, { query: '' }, function (err, groups) { + it('should return the groups when search query is empty', (done) => { + socketGroups.search({ uid: adminUid }, { query: '' }, (err, groups) => { assert.ifError(err); assert.equal(5, groups.length); done(); }); }); - it('should return the "Test" group when searched for', function (done) { - socketGroups.search({ uid: adminUid }, { query: 'test' }, function (err, groups) { + it('should return the "Test" group when searched for', (done) => { + socketGroups.search({ uid: adminUid }, { query: 'test' }, (err, groups) => { assert.ifError(err); assert.equal(2, groups.length); assert.strictEqual('Test', groups[0].name); @@ -140,8 +140,8 @@ describe('Groups', function () { }); }); - it('should return the "Test" group when searched for and sort by member count', function (done) { - Groups.search('test', { filterHidden: true, sort: 'count' }, function (err, groups) { + it('should return the "Test" group when searched for and sort by member count', (done) => { + Groups.search('test', { filterHidden: true, sort: 'count' }, (err, groups) => { assert.ifError(err); assert.equal(2, groups.length); assert.strictEqual('Test', groups[0].name); @@ -149,8 +149,8 @@ describe('Groups', function () { }); }); - it('should return the "Test" group when searched for and sort by creation time', function (done) { - Groups.search('test', { filterHidden: true, sort: 'date' }, function (err, groups) { + it('should return the "Test" group when searched for and sort by creation time', (done) => { + Groups.search('test', { filterHidden: true, sort: 'date' }, (err, groups) => { assert.ifError(err); assert.equal(2, groups.length); assert.strictEqual('Test', groups[1].name); @@ -158,7 +158,7 @@ describe('Groups', function () { }); }); - it('should return all users if no query', function (done) { + it('should return all users if no query', (done) => { function createAndJoinGroup(username, email, callback) { async.waterfall([ function (next) { @@ -176,10 +176,10 @@ describe('Groups', function () { function (next) { createAndJoinGroup('bob', 'bob@b.com', next); }, - ], function (err) { + ], (err) => { assert.ifError(err); - socketGroups.searchMembers({ uid: adminUid }, { groupName: 'Test', query: '' }, function (err, data) { + socketGroups.searchMembers({ uid: adminUid }, { groupName: 'Test', query: '' }, (err, data) => { assert.ifError(err); assert.equal(data.users.length, 3); done(); @@ -187,15 +187,15 @@ describe('Groups', function () { }); }); - it('should search group members', function (done) { - socketGroups.searchMembers({ uid: adminUid }, { groupName: 'Test', query: 'test' }, function (err, data) { + it('should search group members', (done) => { + socketGroups.searchMembers({ uid: adminUid }, { groupName: 'Test', query: 'test' }, (err, data) => { assert.ifError(err); assert.strictEqual('testuser', data.users[0].username); done(); }); }); - it('should not return hidden groups', async function () { + it('should not return hidden groups', async () => { await Groups.create({ name: 'hiddenGroup', hidden: '1', @@ -205,33 +205,33 @@ describe('Groups', function () { }); }); - describe('.isMember()', function () { - it('should return boolean true when a user is in a group', function (done) { - Groups.isMember(1, 'Test', function (err, isMember) { + describe('.isMember()', () => { + it('should return boolean true when a user is in a group', (done) => { + Groups.isMember(1, 'Test', (err, isMember) => { assert.ifError(err); assert.strictEqual(isMember, true); done(); }); }); - it('should return boolean false when a user is not in a group', function (done) { - Groups.isMember(2, 'Test', function (err, isMember) { + it('should return boolean false when a user is not in a group', (done) => { + Groups.isMember(2, 'Test', (err, isMember) => { assert.ifError(err); assert.strictEqual(isMember, false); done(); }); }); - it('should return true for uid 0 and guests group', function (done) { - Groups.isMembers([1, 0], 'guests', function (err, isMembers) { + it('should return true for uid 0 and guests group', (done) => { + Groups.isMembers([1, 0], 'guests', (err, isMembers) => { assert.ifError(err); assert.deepStrictEqual(isMembers, [false, true]); done(); }); }); - it('should return true for uid 0 and guests group', function (done) { - Groups.isMemberOfGroups(0, ['guests', 'registered-users'], function (err, isMembers) { + it('should return true for uid 0 and guests group', (done) => { + Groups.isMemberOfGroups(0, ['guests', 'registered-users'], (err, isMembers) => { assert.ifError(err); assert.deepStrictEqual(isMembers, [true, false]); done(); @@ -239,17 +239,17 @@ describe('Groups', function () { }); }); - describe('.isMemberOfGroupList', function () { - it('should report that a user is part of a groupList, if they are', function (done) { - Groups.isMemberOfGroupList(1, 'Hidden', function (err, isMember) { + describe('.isMemberOfGroupList', () => { + it('should report that a user is part of a groupList, if they are', (done) => { + Groups.isMemberOfGroupList(1, 'Hidden', (err, isMember) => { assert.ifError(err); assert.strictEqual(isMember, true); done(); }); }); - it('should report that a user is not part of a groupList, if they are not', function (done) { - Groups.isMemberOfGroupList(2, 'Hidden', function (err, isMember) { + it('should report that a user is not part of a groupList, if they are not', (done) => { + Groups.isMemberOfGroupList(2, 'Hidden', (err, isMember) => { assert.ifError(err); assert.strictEqual(isMember, false); done(); @@ -257,25 +257,25 @@ describe('Groups', function () { }); }); - describe('.exists()', function () { - it('should verify that the test group exists', function (done) { - Groups.exists('Test', function (err, exists) { + describe('.exists()', () => { + it('should verify that the test group exists', (done) => { + Groups.exists('Test', (err, exists) => { assert.ifError(err); assert.strictEqual(exists, true); done(); }); }); - it('should verify that a fake group does not exist', function (done) { - Groups.exists('Derp', function (err, exists) { + it('should verify that a fake group does not exist', (done) => { + Groups.exists('Derp', (err, exists) => { assert.ifError(err); assert.strictEqual(exists, false); done(); }); }); - it('should check if group exists using an array', function (done) { - Groups.exists(['Test', 'Derp'], function (err, groupsExists) { + it('should check if group exists using an array', (done) => { + Groups.exists(['Test', 'Derp'], (err, groupsExists) => { assert.ifError(err); assert.strictEqual(groupsExists[0], true); assert.strictEqual(groupsExists[1], false); @@ -284,24 +284,24 @@ describe('Groups', function () { }); }); - describe('.create()', function () { - it('should create another group', function (done) { + describe('.create()', () => { + it('should create another group', (done) => { Groups.create({ name: 'foo', description: 'bar', - }, function (err) { + }, (err) => { assert.ifError(err); Groups.get('foo', {}, done); }); }); - it('should create a hidden group if hidden is 1', function (done) { + it('should create a hidden group if hidden is 1', (done) => { Groups.create({ name: 'hidden group', hidden: '1', - }, function (err) { + }, (err) => { assert.ifError(err); - db.isSortedSetMember('groups:visible:memberCount', 'visible group', function (err, isMember) { + db.isSortedSetMember('groups:visible:memberCount', 'visible group', (err, isMember) => { assert.ifError(err); assert(!isMember); done(); @@ -309,13 +309,13 @@ describe('Groups', function () { }); }); - it('should create a visible group if hidden is 0', function (done) { + it('should create a visible group if hidden is 0', (done) => { Groups.create({ name: 'visible group', hidden: '0', - }, function (err) { + }, (err) => { assert.ifError(err); - db.isSortedSetMember('groups:visible:memberCount', 'visible group', function (err, isMember) { + db.isSortedSetMember('groups:visible:memberCount', 'visible group', (err, isMember) => { assert.ifError(err); assert(isMember); done(); @@ -323,12 +323,12 @@ describe('Groups', function () { }); }); - it('should create a visible group if hidden is not passed in', function (done) { + it('should create a visible group if hidden is not passed in', (done) => { Groups.create({ name: 'visible group 2', - }, function (err) { + }, (err) => { assert.ifError(err); - db.isSortedSetMember('groups:visible:memberCount', 'visible group 2', function (err, isMember) { + db.isSortedSetMember('groups:visible:memberCount', 'visible group 2', (err, isMember) => { assert.ifError(err); assert(isMember); done(); @@ -336,46 +336,46 @@ describe('Groups', function () { }); }); - it('should fail to create group with duplicate group name', function (done) { - Groups.create({ name: 'foo' }, function (err) { + it('should fail to create group with duplicate group name', (done) => { + Groups.create({ name: 'foo' }, (err) => { assert(err); assert.equal(err.message, '[[error:group-already-exists]]'); done(); }); }); - it('should fail to create group if slug is empty', function (done) { - Groups.create({ name: '>>>>' }, function (err) { + it('should fail to create group if slug is empty', (done) => { + Groups.create({ name: '>>>>' }, (err) => { assert.equal(err.message, '[[error:invalid-group-name]]'); done(); }); }); - it('should fail if group name is invalid', function (done) { - Groups.create({ name: 'not/valid' }, function (err) { + it('should fail if group name is invalid', (done) => { + Groups.create({ name: 'not/valid' }, (err) => { assert.equal(err.message, '[[error:invalid-group-name]]'); done(); }); }); - it('should fail if group name is invalid', function (done) { - Groups.create({ name: ['array/'] }, function (err) { + it('should fail if group name is invalid', (done) => { + Groups.create({ name: ['array/'] }, (err) => { assert.equal(err.message, '[[error:invalid-group-name]]'); done(); }); }); - it('should fail if group name is invalid', function (done) { - socketGroups.create({ uid: adminUid }, { name: ['test', 'administrators'] }, function (err) { + it('should fail if group name is invalid', (done) => { + socketGroups.create({ uid: adminUid }, { name: ['test', 'administrators'] }, (err) => { assert.equal(err.message, '[[error:invalid-group-name]]'); done(); }); }); - it('should not create a system group', function (done) { - socketGroups.create({ uid: adminUid }, { name: 'mysystemgroup', system: true }, function (err) { + it('should not create a system group', (done) => { + socketGroups.create({ uid: adminUid }, { name: 'mysystemgroup', system: true }, (err) => { assert.ifError(err); - Groups.getGroupData('mysystemgroup', function (err, data) { + Groups.getGroupData('mysystemgroup', (err, data) => { assert.ifError(err); assert.strictEqual(data.system, 0); done(); @@ -383,19 +383,19 @@ describe('Groups', function () { }); }); - it('should fail if group name is invalid', function (done) { - Groups.create({ name: 'not:valid' }, function (err) { + it('should fail if group name is invalid', (done) => { + Groups.create({ name: 'not:valid' }, (err) => { assert.equal(err.message, '[[error:invalid-group-name]]'); done(); }); }); - it('should return falsy for userTitleEnabled', function (done) { - Groups.create({ name: 'userTitleEnabledGroup' }, function (err) { + it('should return falsy for userTitleEnabled', (done) => { + Groups.create({ name: 'userTitleEnabledGroup' }, (err) => { assert.ifError(err); - Groups.setGroupField('userTitleEnabledGroup', 'userTitleEnabled', 0, function (err) { + Groups.setGroupField('userTitleEnabledGroup', 'userTitleEnabled', 0, (err) => { assert.ifError(err); - Groups.getGroupData('userTitleEnabledGroup', function (err, data) { + Groups.getGroupData('userTitleEnabledGroup', (err, data) => { assert.ifError(err); assert.strictEqual(data.userTitleEnabled, 0); done(); @@ -405,12 +405,12 @@ describe('Groups', function () { }); }); - describe('.hide()', function () { - it('should mark the group as hidden', function (done) { - Groups.hide('foo', function (err) { + describe('.hide()', () => { + it('should mark the group as hidden', (done) => { + Groups.hide('foo', (err) => { assert.ifError(err); - Groups.get('foo', {}, function (err, groupObj) { + Groups.get('foo', {}, (err, groupObj) => { assert.ifError(err); assert.strictEqual(1, groupObj.hidden); done(); @@ -419,8 +419,8 @@ describe('Groups', function () { }); }); - describe('.update()', function () { - before(function (done) { + describe('.update()', () => { + before((done) => { Groups.create({ name: 'updateTestGroup', description: 'bar', @@ -429,13 +429,13 @@ describe('Groups', function () { }, done); }); - it('should change an aspect of a group', function (done) { + it('should change an aspect of a group', (done) => { Groups.update('updateTestGroup', { description: 'baz', - }, function (err) { + }, (err) => { assert.ifError(err); - Groups.get('updateTestGroup', {}, function (err, groupObj) { + Groups.get('updateTestGroup', {}, (err, groupObj) => { assert.ifError(err); assert.strictEqual('baz', groupObj.description); done(); @@ -443,7 +443,7 @@ describe('Groups', function () { }); }); - it('should rename a group and not break navigation routes', async function () { + it('should rename a group and not break navigation routes', async () => { await Groups.update('updateTestGroup', { name: 'updateTestGroup?', }); @@ -456,81 +456,81 @@ describe('Groups', function () { assert.strictEqual(navItems[0].route, '/categories'); }); - it('should fail if system groups is being renamed', function (done) { + it('should fail if system groups is being renamed', (done) => { Groups.update('administrators', { name: 'administrators_fail', - }, function (err) { + }, (err) => { assert.equal(err.message, '[[error:not-allowed-to-rename-system-group]]'); done(); }); }); - it('should fail to rename if group name is invalid', function (done) { - socketGroups.update({ uid: adminUid }, { groupName: ['updateTestGroup?'], values: {} }, function (err) { + it('should fail to rename if group name is invalid', (done) => { + socketGroups.update({ uid: adminUid }, { groupName: ['updateTestGroup?'], values: {} }, (err) => { assert.strictEqual(err.message, '[[error:invalid-group-name]]'); done(); }); }); - it('should fail to rename if group name is too short', function (done) { - socketGroups.update({ uid: adminUid }, { groupName: 'updateTestGroup?', values: { name: '' } }, function (err) { + it('should fail to rename if group name is too short', (done) => { + socketGroups.update({ uid: adminUid }, { groupName: 'updateTestGroup?', values: { name: '' } }, (err) => { assert.strictEqual(err.message, '[[error:group-name-too-short]]'); done(); }); }); - it('should fail to rename if group name is invalid', function (done) { - socketGroups.update({ uid: adminUid }, { groupName: 'updateTestGroup?', values: { name: ['invalid'] } }, function (err) { + it('should fail to rename if group name is invalid', (done) => { + socketGroups.update({ uid: adminUid }, { groupName: 'updateTestGroup?', values: { name: ['invalid'] } }, (err) => { assert.strictEqual(err.message, '[[error:invalid-group-name]]'); done(); }); }); - it('should fail to rename if group name is invalid', function (done) { - socketGroups.update({ uid: adminUid }, { groupName: 'updateTestGroup?', values: { name: 'cid:0:privileges:ban' } }, function (err) { + it('should fail to rename if group name is invalid', (done) => { + socketGroups.update({ uid: adminUid }, { groupName: 'updateTestGroup?', values: { name: 'cid:0:privileges:ban' } }, (err) => { assert.strictEqual(err.message, '[[error:invalid-group-name]]'); done(); }); }); - it('should fail to rename if group name is too long', function (done) { - socketGroups.update({ uid: adminUid }, { groupName: 'updateTestGroup?', values: { name: 'verylongstringverylongstringverylongstringverylongstringverylongstringverylongstringverylongstringverylongstringverylongstringverylongstringverylongstringverylongstringverylongstringverylongstringverylongstringverylongstringverylongstringverylongstringverylongstringverylongstring' } }, function (err) { + it('should fail to rename if group name is too long', (done) => { + socketGroups.update({ uid: adminUid }, { groupName: 'updateTestGroup?', values: { name: 'verylongstringverylongstringverylongstringverylongstringverylongstringverylongstringverylongstringverylongstringverylongstringverylongstringverylongstringverylongstringverylongstringverylongstringverylongstringverylongstringverylongstringverylongstringverylongstringverylongstring' } }, (err) => { assert.strictEqual(err.message, '[[error:group-name-too-long]]'); done(); }); }); - it('should fail to rename if group name is invalid', function (done) { - socketGroups.update({ uid: adminUid }, { groupName: 'updateTestGroup?', values: { name: 'test:test' } }, function (err) { + it('should fail to rename if group name is invalid', (done) => { + socketGroups.update({ uid: adminUid }, { groupName: 'updateTestGroup?', values: { name: 'test:test' } }, (err) => { assert.strictEqual(err.message, '[[error:invalid-group-name]]'); done(); }); }); - it('should fail to rename if group name is invalid', function (done) { - socketGroups.update({ uid: adminUid }, { groupName: 'updateTestGroup?', values: { name: 'another/test' } }, function (err) { + it('should fail to rename if group name is invalid', (done) => { + socketGroups.update({ uid: adminUid }, { groupName: 'updateTestGroup?', values: { name: 'another/test' } }, (err) => { assert.strictEqual(err.message, '[[error:invalid-group-name]]'); done(); }); }); - it('should fail to rename if group name is invalid', function (done) { - socketGroups.update({ uid: adminUid }, { groupName: 'updateTestGroup?', values: { name: '---' } }, function (err) { + it('should fail to rename if group name is invalid', (done) => { + socketGroups.update({ uid: adminUid }, { groupName: 'updateTestGroup?', values: { name: '---' } }, (err) => { assert.strictEqual(err.message, '[[error:invalid-group-name]]'); done(); }); }); - it('should fail to rename group to an existing group', function (done) { + it('should fail to rename group to an existing group', (done) => { Groups.create({ name: 'group2', system: 0, hidden: 0, - }, function (err) { + }, (err) => { assert.ifError(err); Groups.update('group2', { name: 'updateTestGroup?', - }, function (err) { + }, (err) => { assert.equal(err.message, '[[error:group-already-exists]]'); done(); }); @@ -538,16 +538,16 @@ describe('Groups', function () { }); }); - describe('.destroy()', function () { - before(function (done) { + describe('.destroy()', () => { + before((done) => { Groups.join('foobar?', 1, done); }); - it('should destroy a group', function (done) { - Groups.destroy('foobar?', function (err) { + it('should destroy a group', (done) => { + Groups.destroy('foobar?', (err) => { assert.ifError(err); - Groups.get('foobar?', {}, function (err, groupObj) { + Groups.get('foobar?', {}, (err, groupObj) => { assert.ifError(err); assert.strictEqual(groupObj, null); done(); @@ -555,15 +555,15 @@ describe('Groups', function () { }); }); - it('should also remove the members set', function (done) { - db.exists('group:foo:members', function (err, exists) { + it('should also remove the members set', (done) => { + db.exists('group:foo:members', (err, exists) => { assert.ifError(err); assert.strictEqual(false, exists); done(); }); }); - it('should remove group from privilege groups', function (done) { + it('should remove group from privilege groups', (done) => { const privileges = require('../src/privileges'); const cid = 1; const groupName = '1'; @@ -597,16 +597,16 @@ describe('Groups', function () { }); }); - describe('.join()', function () { - before(function (done) { + describe('.join()', () => { + before((done) => { Groups.leave('Test', testUid, done); }); - it('should add a user to a group', function (done) { - Groups.join('Test', testUid, function (err) { + it('should add a user to a group', (done) => { + Groups.join('Test', testUid, (err) => { assert.ifError(err); - Groups.isMember(testUid, 'Test', function (err, isMember) { + Groups.isMember(testUid, 'Test', (err, isMember) => { assert.ifError(err); assert.strictEqual(true, isMember); @@ -615,7 +615,7 @@ describe('Groups', function () { }); }); - it('should fail to add user to admin group', async function () { + it('should fail to add user to admin group', async () => { const oldValue = meta.config.allowPrivateGroups; try { meta.config.allowPrivateGroups = false; @@ -629,12 +629,12 @@ describe('Groups', function () { meta.config.allowPrivateGroups = oldValue; }); - it('should fail to add user to group if group name is invalid', function (done) { - Groups.join(0, 1, function (err) { + it('should fail to add user to group if group name is invalid', (done) => { + Groups.join(0, 1, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); - Groups.join(null, 1, function (err) { + Groups.join(null, 1, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); - Groups.join(undefined, 1, function (err) { + Groups.join(undefined, 1, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); @@ -642,12 +642,12 @@ describe('Groups', function () { }); }); - it('should fail to add user to group if uid is invalid', function (done) { - Groups.join('Test', 0, function (err) { + it('should fail to add user to group if uid is invalid', (done) => { + Groups.join('Test', 0, (err) => { assert.equal(err.message, '[[error:invalid-uid]]'); - Groups.join('Test', null, function (err) { + Groups.join('Test', null, (err) => { assert.equal(err.message, '[[error:invalid-uid]]'); - Groups.join('Test', undefined, function (err) { + Groups.join('Test', undefined, (err) => { assert.equal(err.message, '[[error:invalid-uid]]'); done(); }); @@ -655,23 +655,23 @@ describe('Groups', function () { }); }); - it('should add user to Global Moderators group', async function () { + it('should add user to Global Moderators group', async () => { const uid = await User.create({ username: 'glomod' }); await socketGroups.join({ uid: adminUid }, { groupName: 'Global Moderators', uid: uid }); const isGlobalMod = await User.isGlobalModerator(uid); assert.strictEqual(isGlobalMod, true); }); - it('should add user to multiple groups', function (done) { + it('should add user to multiple groups', (done) => { var groupNames = ['test-hidden1', 'Test', 'test-hidden2', 'empty group']; - Groups.create({ name: 'empty group' }, function (err) { + Groups.create({ name: 'empty group' }, (err) => { assert.ifError(err); - Groups.join(groupNames, testUid, function (err) { + Groups.join(groupNames, testUid, (err) => { assert.ifError(err); - Groups.isMemberOfGroups(testUid, groupNames, function (err, isMembers) { + Groups.isMemberOfGroups(testUid, groupNames, (err, isMembers) => { assert.ifError(err); assert(isMembers.every(Boolean)); - db.sortedSetScores('groups:visible:memberCount', groupNames, function (err, memberCounts) { + db.sortedSetScores('groups:visible:memberCount', groupNames, (err, memberCounts) => { assert.ifError(err); // hidden groups are not in "groups:visible:memberCount" so they are null assert.deepEqual(memberCounts, [null, 3, null, 1]); @@ -682,15 +682,15 @@ describe('Groups', function () { }); }); - it('should set group title when user joins the group', function (done) { + it('should set group title when user joins the group', (done) => { var groupName = 'this will be title'; - User.create({ username: 'needstitle' }, function (err, uid) { + User.create({ username: 'needstitle' }, (err, uid) => { assert.ifError(err); - Groups.create({ name: groupName }, function (err) { + Groups.create({ name: groupName }, (err) => { assert.ifError(err); - Groups.join([groupName], uid, function (err) { + Groups.join([groupName], uid, (err) => { assert.ifError(err); - User.getUserData(uid, function (err, data) { + User.getUserData(uid, (err, data) => { assert.ifError(err); assert.equal(data.groupTitle, `["${groupName}"]`); assert.deepEqual(data.groupTitleArray, [groupName]); @@ -701,7 +701,7 @@ describe('Groups', function () { }); }); - it('should fail to add user to system group', async function () { + it('should fail to add user to system group', async () => { const uid = await User.create({ username: 'eviluser' }); const oldValue = meta.config.allowPrivateGroups; meta.config.allowPrivateGroups = 0; @@ -725,12 +725,12 @@ describe('Groups', function () { }); }); - describe('.leave()', function () { - it('should remove a user from a group', function (done) { - Groups.leave('Test', testUid, function (err) { + describe('.leave()', () => { + it('should remove a user from a group', (done) => { + Groups.leave('Test', testUid, (err) => { assert.ifError(err); - Groups.isMember(testUid, 'Test', function (err, isMember) { + Groups.isMember(testUid, 'Test', (err, isMember) => { assert.ifError(err); assert.strictEqual(false, isMember); @@ -740,17 +740,17 @@ describe('Groups', function () { }); }); - describe('.leaveAllGroups()', function () { - it('should remove a user from all groups', function (done) { - Groups.leaveAllGroups(testUid, function (err) { + describe('.leaveAllGroups()', () => { + it('should remove a user from all groups', (done) => { + Groups.leaveAllGroups(testUid, (err) => { assert.ifError(err); var groups = ['Test', 'Hidden']; - async.every(groups, function (group, next) { - Groups.isMember(testUid, group, function (err, isMember) { + async.every(groups, (group, next) => { + Groups.isMember(testUid, group, (err, isMember) => { next(err, !isMember); }); - }, function (err, result) { + }, (err, result) => { assert.ifError(err); assert(result); @@ -760,12 +760,12 @@ describe('Groups', function () { }); }); - describe('.show()', function () { - it('should make a group visible', function (done) { + describe('.show()', () => { + it('should make a group visible', (done) => { Groups.show('Test', function (err) { assert.ifError(err); assert.equal(arguments.length, 1); - db.isSortedSetMember('groups:visible:createtime', 'Test', function (err, isMember) { + db.isSortedSetMember('groups:visible:createtime', 'Test', (err, isMember) => { assert.ifError(err); assert.strictEqual(isMember, true); done(); @@ -774,12 +774,12 @@ describe('Groups', function () { }); }); - describe('.hide()', function () { - it('should make a group hidden', function (done) { + describe('.hide()', () => { + it('should make a group hidden', (done) => { Groups.hide('Test', function (err) { assert.ifError(err); assert.equal(arguments.length, 1); - db.isSortedSetMember('groups:visible:createtime', 'Test', function (err, isMember) { + db.isSortedSetMember('groups:visible:createtime', 'Test', (err, isMember) => { assert.ifError(err); assert.strictEqual(isMember, false); done(); @@ -788,47 +788,47 @@ describe('Groups', function () { }); }); - describe('socket methods', function () { - it('should error if data is null', function (done) { - socketGroups.before({ uid: 0 }, 'groups.join', null, function (err) { + describe('socket methods', () => { + it('should error if data is null', (done) => { + socketGroups.before({ uid: 0 }, 'groups.join', null, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); }); - it('should not error if data is valid', function (done) { - socketGroups.before({ uid: 0 }, 'groups.join', {}, function (err) { + it('should not error if data is valid', (done) => { + socketGroups.before({ uid: 0 }, 'groups.join', {}, (err) => { assert.ifError(err); done(); }); }); - it('should return error if not logged in', function (done) { - socketGroups.join({ uid: 0 }, {}, function (err) { + it('should return error if not logged in', (done) => { + socketGroups.join({ uid: 0 }, {}, (err) => { assert.equal(err.message, '[[error:invalid-uid]]'); done(); }); }); - it('should return error if group name is special', function (done) { - socketGroups.join({ uid: testUid }, { groupName: 'administrators' }, function (err) { + it('should return error if group name is special', (done) => { + socketGroups.join({ uid: testUid }, { groupName: 'administrators' }, (err) => { assert.equal(err.message, '[[error:not-allowed]]'); done(); }); }); - it('should error if group does not exist', function (done) { - socketGroups.join({ uid: adminUid }, { groupName: 'doesnotexist' }, function (err) { + it('should error if group does not exist', (done) => { + socketGroups.join({ uid: adminUid }, { groupName: 'doesnotexist' }, (err) => { assert.equal(err.message, '[[error:no-group]]'); done(); }); }); - it('should join test group', function (done) { + it('should join test group', (done) => { meta.config.allowPrivateGroups = 0; - socketGroups.join({ uid: adminUid }, { groupName: 'Test' }, function (err) { + socketGroups.join({ uid: adminUid }, { groupName: 'Test' }, (err) => { assert.ifError(err); - Groups.isMember(adminUid, 'Test', function (err, isMember) { + Groups.isMember(adminUid, 'Test', (err, isMember) => { assert.ifError(err); assert(isMember); done(); @@ -836,24 +836,24 @@ describe('Groups', function () { }); }); - it('should error if not logged in', function (done) { - socketGroups.leave({ uid: 0 }, {}, function (err) { + it('should error if not logged in', (done) => { + socketGroups.leave({ uid: 0 }, {}, (err) => { assert.equal(err.message, '[[error:invalid-uid]]'); done(); }); }); - it('should return error if group name is special', function (done) { - socketGroups.leave({ uid: adminUid }, { groupName: 'administrators' }, function (err) { + it('should return error if group name is special', (done) => { + socketGroups.leave({ uid: adminUid }, { groupName: 'administrators' }, (err) => { assert.equal(err.message, '[[error:cant-remove-self-as-admin]]'); done(); }); }); - it('should leave test group', function (done) { - socketGroups.leave({ uid: adminUid }, { groupName: 'Test' }, function (err) { + it('should leave test group', (done) => { + socketGroups.leave({ uid: adminUid }, { groupName: 'Test' }, (err) => { assert.ifError(err); - Groups.isMember('Test', adminUid, function (err, isMember) { + Groups.isMember('Test', adminUid, (err, isMember) => { assert.ifError(err); assert(!isMember); done(); @@ -861,9 +861,9 @@ describe('Groups', function () { }); }); - it('should fail to join if group is private and join requests are disabled', function (done) { + it('should fail to join if group is private and join requests are disabled', (done) => { meta.config.allowPrivateGroups = 1; - socketGroups.join({ uid: testUid }, { groupName: 'PrivateNoJoin' }, function (err) { + socketGroups.join({ uid: testUid }, { groupName: 'PrivateNoJoin' }, (err) => { assert.equal(err.message, '[[error:group-join-disabled]]'); done(); }); @@ -879,10 +879,10 @@ describe('Groups', function () { } }); - it('should join if user is admin', function (done) { - socketGroups.join({ uid: adminUid }, { groupName: 'PrivateCanJoin' }, function (err) { + it('should join if user is admin', (done) => { + socketGroups.join({ uid: adminUid }, { groupName: 'PrivateCanJoin' }, (err) => { assert.ifError(err); - Groups.isMember(adminUid, 'PrivateCanJoin', function (err, isMember) { + Groups.isMember(adminUid, 'PrivateCanJoin', (err, isMember) => { assert.ifError(err); assert(isMember); done(); @@ -890,10 +890,10 @@ describe('Groups', function () { }); }); - it('should request membership for regular user', function (done) { - socketGroups.join({ uid: testUid }, { groupName: 'PrivateCanJoin' }, function (err) { + it('should request membership for regular user', (done) => { + socketGroups.join({ uid: testUid }, { groupName: 'PrivateCanJoin' }, (err) => { assert.ifError(err); - Groups.isPending(testUid, 'PrivateCanJoin', function (err, isPending) { + Groups.isPending(testUid, 'PrivateCanJoin', (err, isPending) => { assert.ifError(err); assert(isPending); done(); @@ -901,10 +901,10 @@ describe('Groups', function () { }); }); - it('should reject membership of user', function (done) { - socketGroups.reject({ uid: adminUid }, { groupName: 'PrivateCanJoin', toUid: testUid }, function (err) { + it('should reject membership of user', (done) => { + socketGroups.reject({ uid: adminUid }, { groupName: 'PrivateCanJoin', toUid: testUid }, (err) => { assert.ifError(err); - Groups.isInvited(testUid, 'PrivateCanJoin', function (err, invited) { + Groups.isInvited(testUid, 'PrivateCanJoin', (err, invited) => { assert.ifError(err); assert.equal(invited, false); done(); @@ -912,19 +912,19 @@ describe('Groups', function () { }); }); - it('should error if not owner or admin', function (done) { - socketGroups.accept({ uid: 0 }, { groupName: 'PrivateCanJoin', toUid: testUid }, function (err) { + it('should error if not owner or admin', (done) => { + socketGroups.accept({ uid: 0 }, { groupName: 'PrivateCanJoin', toUid: testUid }, (err) => { assert.equal(err.message, '[[error:no-privileges]]'); done(); }); }); - it('should accept membership of user', function (done) { - socketGroups.join({ uid: testUid }, { groupName: 'PrivateCanJoin' }, function (err) { + it('should accept membership of user', (done) => { + socketGroups.join({ uid: testUid }, { groupName: 'PrivateCanJoin' }, (err) => { assert.ifError(err); - socketGroups.accept({ uid: adminUid }, { groupName: 'PrivateCanJoin', toUid: testUid }, function (err) { + socketGroups.accept({ uid: adminUid }, { groupName: 'PrivateCanJoin', toUid: testUid }, (err) => { assert.ifError(err); - Groups.isMember(testUid, 'PrivateCanJoin', function (err, isMember) { + Groups.isMember(testUid, 'PrivateCanJoin', (err, isMember) => { assert.ifError(err); assert(isMember); done(); @@ -933,7 +933,7 @@ describe('Groups', function () { }); }); - it('should reject/accept all memberships requests', function (done) { + it('should reject/accept all memberships requests', (done) => { function requestMembership(uids, callback) { async.series([ function (next) { @@ -942,7 +942,7 @@ describe('Groups', function () { function (next) { socketGroups.join({ uid: uids.uid2 }, { groupName: 'PrivateCanJoin' }, next); }, - ], function (err) { + ], (err) => { callback(err); }); } @@ -983,17 +983,17 @@ describe('Groups', function () { assert(isMembers[1]); next(); }, - ], function (err) { + ], (err) => { done(err); }); }); - it('should issue invite to user', function (done) { - User.create({ username: 'invite1' }, function (err, uid) { + it('should issue invite to user', (done) => { + User.create({ username: 'invite1' }, (err, uid) => { assert.ifError(err); - socketGroups.issueInvite({ uid: adminUid }, { groupName: 'PrivateCanJoin', toUid: uid }, function (err) { + socketGroups.issueInvite({ uid: adminUid }, { groupName: 'PrivateCanJoin', toUid: uid }, (err) => { assert.ifError(err); - Groups.isInvited(uid, 'PrivateCanJoin', function (err, isInvited) { + Groups.isInvited(uid, 'PrivateCanJoin', (err, isInvited) => { assert.ifError(err); assert(isInvited); done(); @@ -1002,19 +1002,19 @@ describe('Groups', function () { }); }); - it('should fail with invalid data', function (done) { - socketGroups.issueMassInvite({ uid: adminUid }, { groupName: 'PrivateCanJoin', usernames: null }, function (err) { + it('should fail with invalid data', (done) => { + socketGroups.issueMassInvite({ uid: adminUid }, { groupName: 'PrivateCanJoin', usernames: null }, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); }); - it('should issue mass invite to users', function (done) { - User.create({ username: 'invite2' }, function (err, uid) { + it('should issue mass invite to users', (done) => { + User.create({ username: 'invite2' }, (err, uid) => { assert.ifError(err); - socketGroups.issueMassInvite({ uid: adminUid }, { groupName: 'PrivateCanJoin', usernames: 'invite1, invite2' }, function (err) { + socketGroups.issueMassInvite({ uid: adminUid }, { groupName: 'PrivateCanJoin', usernames: 'invite1, invite2' }, (err) => { assert.ifError(err); - Groups.isInvited([adminUid, uid], 'PrivateCanJoin', function (err, isInvited) { + Groups.isInvited([adminUid, uid], 'PrivateCanJoin', (err, isInvited) => { assert.ifError(err); assert.deepStrictEqual(isInvited, [false, true]); done(); @@ -1023,14 +1023,14 @@ describe('Groups', function () { }); }); - it('should rescind invite', function (done) { - User.create({ username: 'invite3' }, function (err, uid) { + it('should rescind invite', (done) => { + User.create({ username: 'invite3' }, (err, uid) => { assert.ifError(err); - socketGroups.issueInvite({ uid: adminUid }, { groupName: 'PrivateCanJoin', toUid: uid }, function (err) { + socketGroups.issueInvite({ uid: adminUid }, { groupName: 'PrivateCanJoin', toUid: uid }, (err) => { assert.ifError(err); - socketGroups.rescindInvite({ uid: adminUid }, { groupName: 'PrivateCanJoin', toUid: uid }, function (err) { + socketGroups.rescindInvite({ uid: adminUid }, { groupName: 'PrivateCanJoin', toUid: uid }, (err) => { assert.ifError(err); - Groups.isInvited(uid, 'PrivateCanJoin', function (err, isInvited) { + Groups.isInvited(uid, 'PrivateCanJoin', (err, isInvited) => { assert.ifError(err); assert(!isInvited); done(); @@ -1040,21 +1040,21 @@ describe('Groups', function () { }); }); - it('should error if user is not invited', function (done) { - socketGroups.acceptInvite({ uid: adminUid }, { groupName: 'PrivateCanJoin' }, function (err) { + it('should error if user is not invited', (done) => { + socketGroups.acceptInvite({ uid: adminUid }, { groupName: 'PrivateCanJoin' }, (err) => { assert.equal(err.message, '[[error:not-invited]]'); done(); }); }); - it('should accept invite', function (done) { - User.create({ username: 'invite4' }, function (err, uid) { + it('should accept invite', (done) => { + User.create({ username: 'invite4' }, (err, uid) => { assert.ifError(err); - socketGroups.issueInvite({ uid: adminUid }, { groupName: 'PrivateCanJoin', toUid: uid }, function (err) { + socketGroups.issueInvite({ uid: adminUid }, { groupName: 'PrivateCanJoin', toUid: uid }, (err) => { assert.ifError(err); - socketGroups.acceptInvite({ uid: uid }, { groupName: 'PrivateCanJoin' }, function (err) { + socketGroups.acceptInvite({ uid: uid }, { groupName: 'PrivateCanJoin' }, (err) => { assert.ifError(err); - Groups.isMember(uid, 'PrivateCanJoin', function (err, isMember) { + Groups.isMember(uid, 'PrivateCanJoin', (err, isMember) => { assert.ifError(err); assert(isMember); done(); @@ -1064,14 +1064,14 @@ describe('Groups', function () { }); }); - it('should reject invite', function (done) { - User.create({ username: 'invite5' }, function (err, uid) { + it('should reject invite', (done) => { + User.create({ username: 'invite5' }, (err, uid) => { assert.ifError(err); - socketGroups.issueInvite({ uid: adminUid }, { groupName: 'PrivateCanJoin', toUid: uid }, function (err) { + socketGroups.issueInvite({ uid: adminUid }, { groupName: 'PrivateCanJoin', toUid: uid }, (err) => { assert.ifError(err); - socketGroups.rejectInvite({ uid: uid }, { groupName: 'PrivateCanJoin' }, function (err) { + socketGroups.rejectInvite({ uid: uid }, { groupName: 'PrivateCanJoin' }, (err) => { assert.ifError(err); - Groups.isInvited(uid, 'PrivateCanJoin', function (err, isInvited) { + Groups.isInvited(uid, 'PrivateCanJoin', (err, isInvited) => { assert.ifError(err); assert(!isInvited); done(); @@ -1081,10 +1081,10 @@ describe('Groups', function () { }); }); - it('should grant ownership to user', function (done) { - socketGroups.grant({ uid: adminUid }, { groupName: 'PrivateCanJoin', toUid: testUid }, function (err) { + it('should grant ownership to user', (done) => { + socketGroups.grant({ uid: adminUid }, { groupName: 'PrivateCanJoin', toUid: testUid }, (err) => { assert.ifError(err); - Groups.ownership.isOwner(testUid, 'PrivateCanJoin', function (err, isOwner) { + Groups.ownership.isOwner(testUid, 'PrivateCanJoin', (err, isOwner) => { assert.ifError(err); assert(isOwner); done(); @@ -1092,10 +1092,10 @@ describe('Groups', function () { }); }); - it('should rescind ownership from user', function (done) { - socketGroups.rescind({ uid: adminUid }, { groupName: 'PrivateCanJoin', toUid: testUid }, function (err) { + it('should rescind ownership from user', (done) => { + socketGroups.rescind({ uid: adminUid }, { groupName: 'PrivateCanJoin', toUid: testUid }, (err) => { assert.ifError(err); - Groups.ownership.isOwner(testUid, 'PrivateCanJoin', function (err, isOwner) { + Groups.ownership.isOwner(testUid, 'PrivateCanJoin', (err, isOwner) => { assert.ifError(err); assert(!isOwner); done(); @@ -1103,17 +1103,17 @@ describe('Groups', function () { }); }); - it('should fail to kick user with invalid data', function (done) { - socketGroups.kick({ uid: adminUid }, { groupName: 'PrivateCanJoin', uid: adminUid }, function (err) { + it('should fail to kick user with invalid data', (done) => { + socketGroups.kick({ uid: adminUid }, { groupName: 'PrivateCanJoin', uid: adminUid }, (err) => { assert.equal(err.message, '[[error:cant-kick-self]]'); done(); }); }); - it('should kick user from group', function (done) { - socketGroups.kick({ uid: adminUid }, { groupName: 'PrivateCanJoin', uid: testUid }, function (err) { + it('should kick user from group', (done) => { + socketGroups.kick({ uid: adminUid }, { groupName: 'PrivateCanJoin', uid: testUid }, (err) => { assert.ifError(err); - Groups.isMember(testUid, 'PrivateCanJoin', function (err, isMember) { + Groups.isMember(testUid, 'PrivateCanJoin', (err, isMember) => { assert.ifError(err); assert(!isMember); done(); @@ -1121,29 +1121,29 @@ describe('Groups', function () { }); }); - it('should fail to create group with invalid data', function (done) { - socketGroups.create({ uid: 0 }, {}, function (err) { + it('should fail to create group with invalid data', (done) => { + socketGroups.create({ uid: 0 }, {}, (err) => { assert.equal(err.message, '[[error:no-privileges]]'); done(); }); }); - it('should fail to create group if group creation is disabled', function (done) { - socketGroups.create({ uid: testUid }, { name: 'avalidname' }, function (err) { + it('should fail to create group if group creation is disabled', (done) => { + socketGroups.create({ uid: testUid }, { name: 'avalidname' }, (err) => { assert.equal(err.message, '[[error:no-privileges]]'); done(); }); }); - it('should fail to create group if name is privilege group', function (done) { - socketGroups.create({ uid: 1 }, { name: 'cid:1:privileges:groups:find' }, function (err) { + it('should fail to create group if name is privilege group', (done) => { + socketGroups.create({ uid: 1 }, { name: 'cid:1:privileges:groups:find' }, (err) => { assert.equal(err.message, '[[error:invalid-group-name]]'); done(); }); }); - it('should create/update group', function (done) { - socketGroups.create({ uid: adminUid }, { name: 'createupdategroup' }, function (err, groupData) { + it('should create/update group', (done) => { + socketGroups.create({ uid: adminUid }, { name: 'createupdategroup' }, (err, groupData) => { assert.ifError(err); assert(groupData); var data = { @@ -1158,9 +1158,9 @@ describe('Groups', function () { private: 0, }, }; - socketGroups.update({ uid: adminUid }, data, function (err) { + socketGroups.update({ uid: adminUid }, data, (err) => { assert.ifError(err); - Groups.get('renamedupdategroup', {}, function (err, groupData) { + Groups.get('renamedupdategroup', {}, (err, groupData) => { assert.ifError(err); assert.equal(groupData.name, 'renamedupdategroup'); assert.equal(groupData.userTitle, 'cats'); @@ -1174,30 +1174,30 @@ describe('Groups', function () { }); }); - it('should fail to create a group with name guests', function (done) { - socketGroups.create({ uid: adminUid }, { name: 'guests' }, function (err) { + it('should fail to create a group with name guests', (done) => { + socketGroups.create({ uid: adminUid }, { name: 'guests' }, (err) => { assert.equal(err.message, '[[error:invalid-group-name]]'); done(); }); }); - it('should fail to rename guests group', function (done) { + it('should fail to rename guests group', (done) => { var data = { groupName: 'guests', values: { name: 'guests2', }, }; - socketGroups.update({ uid: adminUid }, data, function (err) { + socketGroups.update({ uid: adminUid }, data, (err) => { assert.equal(err.message, '[[error:invalid-group-name]]'); done(); }); }); - it('should delete group', function (done) { - socketGroups.delete({ uid: adminUid }, { groupName: 'renamedupdategroup' }, function (err) { + it('should delete group', (done) => { + socketGroups.delete({ uid: adminUid }, { groupName: 'renamedupdategroup' }, (err) => { assert.ifError(err); - Groups.exists('renamedupdategroup', function (err, exists) { + Groups.exists('renamedupdategroup', (err, exists) => { assert.ifError(err); assert(!exists); done(); @@ -1205,58 +1205,58 @@ describe('Groups', function () { }); }); - it('should fail to delete group if name is special', function (done) { - socketGroups.delete({ uid: adminUid }, { groupName: 'administrators' }, function (err) { + it('should fail to delete group if name is special', (done) => { + socketGroups.delete({ uid: adminUid }, { groupName: 'administrators' }, (err) => { assert.equal(err.message, '[[error:not-allowed]]'); done(); }); }); - it('should fail to delete group if name is special', function (done) { - socketGroups.delete({ uid: adminUid }, { groupName: 'registered-users' }, function (err) { + it('should fail to delete group if name is special', (done) => { + socketGroups.delete({ uid: adminUid }, { groupName: 'registered-users' }, (err) => { assert.equal(err.message, '[[error:not-allowed]]'); done(); }); }); - it('should fail to delete group if name is special', function (done) { - socketGroups.delete({ uid: adminUid }, { groupName: 'Global Moderators' }, function (err) { + it('should fail to delete group if name is special', (done) => { + socketGroups.delete({ uid: adminUid }, { groupName: 'Global Moderators' }, (err) => { assert.equal(err.message, '[[error:not-allowed]]'); done(); }); }); - it('should fail to delete group if name is special', function (done) { - socketGroups.delete({ uid: adminUid }, { groupName: 'guests' }, function (err) { + it('should fail to delete group if name is special', (done) => { + socketGroups.delete({ uid: adminUid }, { groupName: 'guests' }, (err) => { assert.equal(err.message, '[[error:invalid-group-name]]'); done(); }); }); - it('should fail to load more groups with invalid data', function (done) { - socketGroups.loadMore({ uid: adminUid }, {}, function (err) { + it('should fail to load more groups with invalid data', (done) => { + socketGroups.loadMore({ uid: adminUid }, {}, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); }); - it('should load more groups', function (done) { - socketGroups.loadMore({ uid: adminUid }, { after: 0, sort: 'count' }, function (err, data) { + it('should load more groups', (done) => { + socketGroups.loadMore({ uid: adminUid }, { after: 0, sort: 'count' }, (err, data) => { assert.ifError(err); assert(Array.isArray(data.groups)); done(); }); }); - it('should fail to load more members with invalid data', function (done) { - socketGroups.loadMoreMembers({ uid: adminUid }, {}, function (err) { + it('should fail to load more members with invalid data', (done) => { + socketGroups.loadMoreMembers({ uid: adminUid }, {}, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); }); - it('should load more members', function (done) { - socketGroups.loadMoreMembers({ uid: adminUid }, { after: 0, groupName: 'PrivateCanJoin' }, function (err, data) { + it('should load more members', (done) => { + socketGroups.loadMoreMembers({ uid: adminUid }, { after: 0, groupName: 'PrivateCanJoin' }, (err, data) => { assert.ifError(err); assert(Array.isArray(data.users)); done(); @@ -1264,25 +1264,25 @@ describe('Groups', function () { }); }); - describe('admin socket methods', function () { + describe('admin socket methods', () => { var socketGroups = require('../src/socket.io/admin/groups'); - it('should fail to create group with invalid data', function (done) { - socketGroups.create({ uid: adminUid }, null, function (err) { + it('should fail to create group with invalid data', (done) => { + socketGroups.create({ uid: adminUid }, null, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); }); - it('should fail to create group if group name is privilege group', function (done) { - socketGroups.create({ uid: adminUid }, { name: 'cid:1:privileges:read' }, function (err) { + it('should fail to create group if group name is privilege group', (done) => { + socketGroups.create({ uid: adminUid }, { name: 'cid:1:privileges:read' }, (err) => { assert.equal(err.message, '[[error:invalid-group-name]]'); done(); }); }); - it('should create a group', function (done) { - socketGroups.create({ uid: adminUid }, { name: 'newgroup', description: 'group created by admin' }, function (err, groupData) { + it('should create a group', (done) => { + socketGroups.create({ uid: adminUid }, { name: 'newgroup', description: 'group created by admin' }, (err, groupData) => { assert.ifError(err); assert.equal(groupData.name, 'newgroup'); assert.equal(groupData.description, 'group created by admin'); @@ -1293,17 +1293,17 @@ describe('Groups', function () { }); }); - it('should fail to join with invalid data', function (done) { - socketGroups.join({ uid: adminUid }, null, function (err) { + it('should fail to join with invalid data', (done) => { + socketGroups.join({ uid: adminUid }, null, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); }); - it('should add user to group', function (done) { - socketGroups.join({ uid: adminUid }, { uid: testUid, groupName: 'newgroup' }, function (err) { + it('should add user to group', (done) => { + socketGroups.join({ uid: adminUid }, { uid: testUid, groupName: 'newgroup' }, (err) => { assert.ifError(err); - Groups.isMember(testUid, 'newgroup', function (err, isMember) { + Groups.isMember(testUid, 'newgroup', (err, isMember) => { assert.ifError(err); assert(isMember); done(); @@ -1311,45 +1311,45 @@ describe('Groups', function () { }); }); - it('should not error if user is already member', function (done) { - socketGroups.join({ uid: adminUid }, { uid: testUid, groupName: 'newgroup' }, function (err) { + it('should not error if user is already member', (done) => { + socketGroups.join({ uid: adminUid }, { uid: testUid, groupName: 'newgroup' }, (err) => { assert.ifError(err); done(); }); }); - it('it should fail with invalid data', function (done) { - socketGroups.leave({ uid: adminUid }, null, function (err) { + it('it should fail with invalid data', (done) => { + socketGroups.leave({ uid: adminUid }, null, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); }); - it('it should fail if admin tries to remove self', function (done) { - socketGroups.leave({ uid: adminUid }, { uid: adminUid, groupName: 'administrators' }, function (err) { + it('it should fail if admin tries to remove self', (done) => { + socketGroups.leave({ uid: adminUid }, { uid: adminUid, groupName: 'administrators' }, (err) => { assert.equal(err.message, '[[error:cant-remove-self-as-admin]]'); done(); }); }); - it('should not error if user is not member', function (done) { - socketGroups.leave({ uid: adminUid }, { uid: 3, groupName: 'newgroup' }, function (err) { + it('should not error if user is not member', (done) => { + socketGroups.leave({ uid: adminUid }, { uid: 3, groupName: 'newgroup' }, (err) => { assert.ifError(err); done(); }); }); - it('should fail if trying to remove someone else from group', function (done) { - socketGroups.leave({ uid: testUid }, { uid: adminUid, groupName: 'newgroup' }, function (err) { + it('should fail if trying to remove someone else from group', (done) => { + socketGroups.leave({ uid: testUid }, { uid: adminUid, groupName: 'newgroup' }, (err) => { assert.strictEqual(err.message, '[[error:no-privileges]]'); done(); }); }); - it('should remove user from group', function (done) { - socketGroups.leave({ uid: adminUid }, { uid: testUid, groupName: 'newgroup' }, function (err) { + it('should remove user from group', (done) => { + socketGroups.leave({ uid: adminUid }, { uid: testUid, groupName: 'newgroup' }, (err) => { assert.ifError(err); - Groups.isMember(testUid, 'newgroup', function (err, isMember) { + Groups.isMember(testUid, 'newgroup', (err, isMember) => { assert.ifError(err); assert(!isMember); done(); @@ -1357,14 +1357,14 @@ describe('Groups', function () { }); }); - it('should fail with invalid data', function (done) { - socketGroups.update({ uid: adminUid }, null, function (err) { + it('should fail with invalid data', (done) => { + socketGroups.update({ uid: adminUid }, null, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); }); - it('should update group', function (done) { + it('should update group', (done) => { var data = { groupName: 'newgroup', values: { @@ -1377,9 +1377,9 @@ describe('Groups', function () { private: 0, }, }; - socketGroups.update({ uid: adminUid }, data, function (err) { + socketGroups.update({ uid: adminUid }, data, (err) => { assert.ifError(err); - Groups.get('renamedgroup', {}, function (err, groupData) { + Groups.get('renamedgroup', {}, (err, groupData) => { assert.ifError(err); assert.equal(groupData.name, 'renamedgroup'); assert.equal(groupData.userTitle, 'cats'); @@ -1393,13 +1393,13 @@ describe('Groups', function () { }); }); - describe('groups cover', function () { + describe('groups cover', () => { var socketGroups = require('../src/socket.io/groups'); var regularUid; var logoPath = path.join(__dirname, '../test/files/test.png'); var imagePath = path.join(__dirname, '../test/files/groupcover.png'); - before(function (done) { - User.create({ username: 'regularuser', password: '123456' }, function (err, uid) { + before((done) => { + User.create({ username: 'regularuser', password: '123456' }, (err, uid) => { assert.ifError(err); regularUid = uid; async.series([ @@ -1416,17 +1416,17 @@ describe('Groups', function () { }); }); - it('should fail if user is not logged in or not owner', function (done) { - socketGroups.cover.update({ uid: 0 }, { imageData: 'asd' }, function (err) { + it('should fail if user is not logged in or not owner', (done) => { + socketGroups.cover.update({ uid: 0 }, { imageData: 'asd' }, (err) => { assert.equal(err.message, '[[error:no-privileges]]'); - socketGroups.cover.update({ uid: regularUid }, { groupName: 'Test', imageData: 'asd' }, function (err) { + socketGroups.cover.update({ uid: regularUid }, { groupName: 'Test', imageData: 'asd' }, (err) => { assert.equal(err.message, '[[error:no-privileges]]'); done(); }); }); }); - it('should upload group cover image from file', function (done) { + it('should upload group cover image from file', (done) => { var data = { groupName: 'Test', file: { @@ -1434,9 +1434,9 @@ describe('Groups', function () { type: 'image/png', }, }; - Groups.updateCover({ uid: adminUid }, data, function (err, data) { + Groups.updateCover({ uid: adminUid }, data, (err, data) => { assert.ifError(err); - Groups.getGroupFields('Test', ['cover:url'], function (err, groupData) { + Groups.getGroupFields('Test', ['cover:url'], (err, groupData) => { assert.ifError(err); assert.equal(nconf.get('relative_path') + data.url, groupData['cover:url']); if (nconf.get('relative_path')) { @@ -1449,14 +1449,14 @@ describe('Groups', function () { }); - it('should upload group cover image from data', function (done) { + it('should upload group cover image from data', (done) => { var data = { groupName: 'Test', imageData: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABwAAAAgCAYAAAABtRhCAAAACXBIWXMAAC4jAAAuIwF4pT92AAAKT2lDQ1BQaG90b3Nob3AgSUNDIHByb2ZpbGUAAHjanVNnVFPpFj333vRCS4iAlEtvUhUIIFJCi4AUkSYqIQkQSoghodkVUcERRUUEG8igiAOOjoCMFVEsDIoK2AfkIaKOg6OIisr74Xuja9a89+bN/rXXPues852zzwfACAyWSDNRNYAMqUIeEeCDx8TG4eQuQIEKJHAAEAizZCFz/SMBAPh+PDwrIsAHvgABeNMLCADATZvAMByH/w/qQplcAYCEAcB0kThLCIAUAEB6jkKmAEBGAYCdmCZTAKAEAGDLY2LjAFAtAGAnf+bTAICd+Jl7AQBblCEVAaCRACATZYhEAGg7AKzPVopFAFgwABRmS8Q5ANgtADBJV2ZIALC3AMDOEAuyAAgMADBRiIUpAAR7AGDIIyN4AISZABRG8lc88SuuEOcqAAB4mbI8uSQ5RYFbCC1xB1dXLh4ozkkXKxQ2YQJhmkAuwnmZGTKBNA/g88wAAKCRFRHgg/P9eM4Ors7ONo62Dl8t6r8G/yJiYuP+5c+rcEAAAOF0ftH+LC+zGoA7BoBt/qIl7gRoXgugdfeLZrIPQLUAoOnaV/Nw+H48PEWhkLnZ2eXk5NhKxEJbYcpXff5nwl/AV/1s+X48/Pf14L7iJIEyXYFHBPjgwsz0TKUcz5IJhGLc5o9H/LcL//wd0yLESWK5WCoU41EScY5EmozzMqUiiUKSKcUl0v9k4t8s+wM+3zUAsGo+AXuRLahdYwP2SycQWHTA4vcAAPK7b8HUKAgDgGiD4c93/+8//UegJQCAZkmScQAAXkQkLlTKsz/HCAAARKCBKrBBG/TBGCzABhzBBdzBC/xgNoRCJMTCQhBCCmSAHHJgKayCQiiGzbAdKmAv1EAdNMBRaIaTcA4uwlW4Dj1wD/phCJ7BKLyBCQRByAgTYSHaiAFiilgjjggXmYX4IcFIBBKLJCDJiBRRIkuRNUgxUopUIFVIHfI9cgI5h1xGupE7yAAygvyGvEcxlIGyUT3UDLVDuag3GoRGogvQZHQxmo8WoJvQcrQaPYw2oefQq2gP2o8+Q8cwwOgYBzPEbDAuxsNCsTgsCZNjy7EirAyrxhqwVqwDu4n1Y8+xdwQSgUXACTYEd0IgYR5BSFhMWE7YSKggHCQ0EdoJNwkDhFHCJyKTqEu0JroR+cQYYjIxh1hILCPWEo8TLxB7iEPENyQSiUMyJ7mQAkmxpFTSEtJG0m5SI+ksqZs0SBojk8naZGuyBzmULCAryIXkneTD5DPkG+Qh8lsKnWJAcaT4U+IoUspqShnlEOU05QZlmDJBVaOaUt2ooVQRNY9aQq2htlKvUYeoEzR1mjnNgxZJS6WtopXTGmgXaPdpr+h0uhHdlR5Ol9BX0svpR+iX6AP0dwwNhhWDx4hnKBmbGAcYZxl3GK+YTKYZ04sZx1QwNzHrmOeZD5lvVVgqtip8FZHKCpVKlSaVGyovVKmqpqreqgtV81XLVI+pXlN9rkZVM1PjqQnUlqtVqp1Q61MbU2epO6iHqmeob1Q/pH5Z/YkGWcNMw09DpFGgsV/jvMYgC2MZs3gsIWsNq4Z1gTXEJrHN2Xx2KruY/R27iz2qqaE5QzNKM1ezUvOUZj8H45hx+Jx0TgnnKKeX836K3hTvKeIpG6Y0TLkxZVxrqpaXllirSKtRq0frvTau7aedpr1Fu1n7gQ5Bx0onXCdHZ4/OBZ3nU9lT3acKpxZNPTr1ri6qa6UbobtEd79up+6Ynr5egJ5Mb6feeb3n+hx9L/1U/W36p/VHDFgGswwkBtsMzhg8xTVxbzwdL8fb8VFDXcNAQ6VhlWGX4YSRudE8o9VGjUYPjGnGXOMk423GbcajJgYmISZLTepN7ppSTbmmKaY7TDtMx83MzaLN1pk1mz0x1zLnm+eb15vft2BaeFostqi2uGVJsuRaplnutrxuhVo5WaVYVVpds0atna0l1rutu6cRp7lOk06rntZnw7Dxtsm2qbcZsOXYBtuutm22fWFnYhdnt8Wuw+6TvZN9un2N/T0HDYfZDqsdWh1+c7RyFDpWOt6azpzuP33F9JbpL2dYzxDP2DPjthPLKcRpnVOb00dnF2e5c4PziIuJS4LLLpc+Lpsbxt3IveRKdPVxXeF60vWdm7Obwu2o26/uNu5p7ofcn8w0nymeWTNz0MPIQ+BR5dE/C5+VMGvfrH5PQ0+BZ7XnIy9jL5FXrdewt6V3qvdh7xc+9j5yn+M+4zw33jLeWV/MN8C3yLfLT8Nvnl+F30N/I/9k/3r/0QCngCUBZwOJgUGBWwL7+Hp8Ib+OPzrbZfay2e1BjKC5QRVBj4KtguXBrSFoyOyQrSH355jOkc5pDoVQfujW0Adh5mGLw34MJ4WHhVeGP45wiFga0TGXNXfR3ENz30T6RJZE3ptnMU85ry1KNSo+qi5qPNo3ujS6P8YuZlnM1VidWElsSxw5LiquNm5svt/87fOH4p3iC+N7F5gvyF1weaHOwvSFpxapLhIsOpZATIhOOJTwQRAqqBaMJfITdyWOCnnCHcJnIi/RNtGI2ENcKh5O8kgqTXqS7JG8NXkkxTOlLOW5hCepkLxMDUzdmzqeFpp2IG0yPTq9MYOSkZBxQqohTZO2Z+pn5mZ2y6xlhbL+xW6Lty8elQfJa7OQrAVZLQq2QqboVFoo1yoHsmdlV2a/zYnKOZarnivN7cyzytuQN5zvn//tEsIS4ZK2pYZLVy0dWOa9rGo5sjxxedsK4xUFK4ZWBqw8uIq2Km3VT6vtV5eufr0mek1rgV7ByoLBtQFr6wtVCuWFfevc1+1dT1gvWd+1YfqGnRs+FYmKrhTbF5cVf9go3HjlG4dvyr+Z3JS0qavEuWTPZtJm6ebeLZ5bDpaql+aXDm4N2dq0Dd9WtO319kXbL5fNKNu7g7ZDuaO/PLi8ZafJzs07P1SkVPRU+lQ27tLdtWHX+G7R7ht7vPY07NXbW7z3/T7JvttVAVVN1WbVZftJ+7P3P66Jqun4lvttXa1ObXHtxwPSA/0HIw6217nU1R3SPVRSj9Yr60cOxx++/p3vdy0NNg1VjZzG4iNwRHnk6fcJ3/ceDTradox7rOEH0x92HWcdL2pCmvKaRptTmvtbYlu6T8w+0dbq3nr8R9sfD5w0PFl5SvNUyWna6YLTk2fyz4ydlZ19fi753GDborZ752PO32oPb++6EHTh0kX/i+c7vDvOXPK4dPKy2+UTV7hXmq86X23qdOo8/pPTT8e7nLuarrlca7nuer21e2b36RueN87d9L158Rb/1tWeOT3dvfN6b/fF9/XfFt1+cif9zsu72Xcn7q28T7xf9EDtQdlD3YfVP1v+3Njv3H9qwHeg89HcR/cGhYPP/pH1jw9DBY+Zj8uGDYbrnjg+OTniP3L96fynQ89kzyaeF/6i/suuFxYvfvjV69fO0ZjRoZfyl5O/bXyl/erA6xmv28bCxh6+yXgzMV70VvvtwXfcdx3vo98PT+R8IH8o/2j5sfVT0Kf7kxmTk/8EA5jz/GMzLdsAAAAgY0hSTQAAeiUAAICDAAD5/wAAgOkAAHUwAADqYAAAOpgAABdvkl/FRgAACcJJREFUeNqMl9tvnNV6xn/f+s5z8DCeg88Zj+NYdhJH4KShFoJAIkzVphLVJnsDaiV6gUKaC2qQUFVATbnoValAakuQYKMqBKUUJCgI9XBBSmOROMqGoCStHbA9sWM7nrFn/I3n9B17kcwoabfarj9gvet53+d9nmdJAwMDAAgh8DyPtbU1XNfFMAwkScK2bTzPw/M8dF1/SAhxKAiCxxVF2aeqqqTr+q+Af+7o6Ch0d3f/69TU1KwkSRiGwbFjx3jmmWd47rnn+OGHH1BVFYX/5QRBkPQ87xeSJP22YRi/oapqStM0PM/D931kWSYIgnHf98cXFxepVqtomjZt2/Zf2bb990EQ4Pv+PXfeU1CSpGYhfN9/TgjxQTQaJQgCwuEwQRBQKpUwDAPTNPF9n0ajAYDv+8zPzzM+Pr6/Wq2eqdVqfxOJRA6Zpnn57hrivyEC0IQQZ4Mg+MAwDCKRCJIkUa/XEUIQi8XQNI1QKIQkSQghUBQFIQSmaTI7OwtAuVxOTE9Pfzc9Pf27lUqlBUgulUoUi0VKpRKqqg4EQfAfiqLsDIfDAC0E4XCYaDSKEALXdalUKvfM1/d9hBBYlkUul2N4eJi3335bcl33mW+++aaUz+cvSJKE8uKLL6JpGo7j8Omnn/7d+vp6sr+/HyEEjuMgyzKu6yJJEsViEVVV8TyPjY2NVisV5fZkTNMkkUhw8+ZN6vU6Kysr7Nmzh9OnT7/12GOPDS8sLByT7rQR4A9XV1d/+cILLzA9PU0kEmF4eBhFUTh//jyWZaHrOkII0uk0jUaDWq1GJpOhWCyysrLC1tYWnuehqir79+9H13W6urp48803+f7773n++ef/4G7S/H4ikUCSJNbX11trcuvWLcrlMrIs4zgODzzwABMTE/i+T7lcpq2tjUqlwubmJrZts7y8jBCCkZERGo0G2WyWkydPkkql6Onp+eMmwihwc3JyMvrWW2+RTCYBcF0XWZbRdZ3l5WX27NnD008/TSwWQ1VVyuVy63GhUIhEIkEqlcJxHCzLIhaLMTQ0xJkzZ7Btm3379lmS53kIIczZ2dnFsbGxRK1Wo729HQDP8zAMg5WVFXp7e5mcnKSzs5N8Po/rutTrdVzXbQmHrutEo1FM00RVVXp7e0kkEgRBwMWLF9F1vaxUq1UikUjtlVdeuV6pVBJ9fX3Ytn2bwrLMysoKXV1dTE5OkslksCwLTdMwDANVVdnY2CAIApLJJJFIBMdxiMfj7Nq1C1VViUajLQCvvvrqkhKJRJiZmfmdb7/99jeTySSyLLfWodFoEAqFOH78OLt37yaXy2GaJoqisLy8zNTUFFevXiUIAtrb29m5cyePPPJIa+cymQz1eh2A0dFRCoXCsgIwNTW1J5/P093dTbFYRJZlJEmiWq1y4MABxsbGqNVqhEIh6vU6QRBQLpcxDIPh4WE8z2NxcZFTp05x7tw5Xn755ZY6dXZ2tliZzWa/EwD1ev3RsbExxsfHSafTVCoVGo0Gqqqya9cuIpEIQgh832dtbY3FxUUA+vr62LZtG2NjYxw5coTDhw+ztLTEyZMnuXr1KoVC4R4d3bt375R84sQJEY/H/2Jubq7N9326urqwbZt6vY5pmhw5coS+vr4W9YvFIrdu3WJqagohBFeuXOHcuXOtue7evRtN01rtfO+991haWmJkZGQrkUi8JIC9iqL0BkFAIpFACMETTzxBV1cXiUSC7u5uHMfB8zyCIMA0TeLxONlsFlmW8X2fwcFBHMdhfn6eer1Oe3s7Dz30EBMTE1y6dImjR49y6tSppR07dqwrjuM8+OWXXzI0NMTly5e5du0aQ0NDTExMkMvlCIKAIAhaIh2LxQiHw0QiEfL5POl0mlqtRq1Wo6OjA8uykGWZdDrN0tISvb29vPPOOzz++OPk83lELpf7rXfffRfDMOjo6MBxHEqlEocOHWLHjh00Gg0kSULTNIS4bS6qqhKPxxkaGmJ4eJjR0VH279/PwMAA27dvJ5vN4vs+X331FR9//DGzs7OEQiE++eQTlPb29keuX7/OtWvXOH78ONVqlZs3b9LW1kYmk8F13dZeCiGQJAnXdRFCYBgGsiwjhMC2bQqFAkEQoOs6P/74Iw8++CCDg4Pous6xY8f47LPPkIIguDo2Nrbzxo0bfPjhh9i2zczMTHNvcF2XpsZalkWj0cB1Xe4o1O3YoCisra3x008/EY/H6erqAuDAgQNEIhGCIODQoUP/ubCwMCKAjx599FHW19f56KOP6OjooFgsks/niUajKIqCbds4joMQAiFESxxs226xd2Zmhng8Tl9fH67r0mg0sG2bbDZLpVIhl8vd5gHwtysrKy8Dcdd1mZubo6enh1gsRrVabZlrk6VND/R9n3q9TqVSQdd1QqEQi4uLnD9/nlKpxODgIHv37gXAcRyCICiFQiHEzp07i1988cUfKYpCIpHANE22b9/eUhNFUVotDIKghc7zPCzLolKpsLW1RVtbG0EQ4DgOmqbR09NDM1qUSiWAPwdQ7ujjmf7+/kQymfxrSZJQVZWtra2WG+i63iKH53m4rku1WqVcLmNZFu3t7S2x7+/vJ51O89prr7VYfenSpcPAP1UqFeSHH36YeDxOKpW6eP/9988Bv9d09nw+T7VapVKptJjZnE2tVmNtbY1cLke5XGZra4vNzU16enp49tlnGRgYaD7iTxqNxgexWIzDhw+jNEPQHV87NT8/f+PChQtnR0ZGqFarrUVuOsDds2u2b2FhgVQqRSQSYWFhgStXrtDf308ymcwBf3nw4EEOHjx4O5c2lURVVRzHYXp6+t8uX7785IULFz7LZDLous59991HOBy+h31N9xgdHSWTyVCtVhkaGmLfvn1MT08zPz/PzMzM6c8//9xr+uE9QViWZer1OhsbGxiG8fns7OzPc7ncx729vXR3d1OpVNi2bRuhUAhZljEMA9/3sW0bVVVZWlri4sWLjI+P8/rrr/P111/z5JNPXrIs69cn76ZeGoaBpmm0tbX9Q6FQeHhubu7fC4UCkUiE1dVVstks8Xgc0zSRZZlGo9ESAdM02djYoNFo8MYbb2BZ1mYoFOKuZPjr/xZBEHCHred83x/b3Nz8l/X19aRlWWxsbNDZ2cnw8DDhcBjf96lWq/T09HD06FGeeuopXnrpJc6ePUs6nb4hhPi/C959ZFn+TtO0lG3bJ0ql0p85jsPW1haFQoG2tjYkSWpF/Uwmw9raGu+//z7A977vX2+GrP93wSZiTdNOGIbxy3K5/DPHcfYXCoVe27Yzpmm2m6bppVKp/Orqqnv69OmoZVn/mEwm/9TzvP9x138NAMpJ4VFTBr6SAAAAAElFTkSuQmCC', }; - socketGroups.cover.update({ uid: adminUid }, data, function (err, data) { + socketGroups.cover.update({ uid: adminUid }, data, (err, data) => { assert.ifError(err); - Groups.getGroupFields('Test', ['cover:url'], function (err, groupData) { + Groups.getGroupFields('Test', ['cover:url'], (err, groupData) => { assert.ifError(err); assert.equal(nconf.get('relative_path') + data.url, groupData['cover:url']); done(); @@ -1464,7 +1464,7 @@ describe('Groups', function () { }); }); - it('should fail to upload group cover with invalid image', function (done) { + it('should fail to upload group cover with invalid image', (done) => { var data = { groupName: 'Test', file: { @@ -1472,31 +1472,31 @@ describe('Groups', function () { type: 'image/png', }, }; - socketGroups.cover.update({ uid: adminUid }, data, function (err) { + socketGroups.cover.update({ uid: adminUid }, data, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); }); - it('should fail to upload group cover with invalid image', function (done) { + it('should fail to upload group cover with invalid image', (done) => { var data = { groupName: 'Test', imageData: 'data:image/svg;base64,iVBORw0KGgoAAAANSUhEUgAAABwA', }; - socketGroups.cover.update({ uid: adminUid }, data, function (err, data) { + socketGroups.cover.update({ uid: adminUid }, data, (err, data) => { assert.equal(err.message, '[[error:invalid-image]]'); done(); }); }); - it('should update group cover position', function (done) { + it('should update group cover position', (done) => { var data = { groupName: 'Test', position: '50% 50%', }; - socketGroups.cover.update({ uid: adminUid }, data, function (err) { + socketGroups.cover.update({ uid: adminUid }, data, (err) => { assert.ifError(err); - Groups.getGroupFields('Test', ['cover:position'], function (err, groupData) { + Groups.getGroupFields('Test', ['cover:position'], (err, groupData) => { assert.ifError(err); assert.equal('50% 50%', groupData['cover:position']); done(); @@ -1504,31 +1504,31 @@ describe('Groups', function () { }); }); - it('should fail to update cover position if group name is missing', function (done) { - Groups.updateCoverPosition('', '50% 50%', function (err) { + it('should fail to update cover position if group name is missing', (done) => { + Groups.updateCoverPosition('', '50% 50%', (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); }); - it('should fail to remove cover if not logged in', function (done) { - socketGroups.cover.remove({ uid: 0 }, { groupName: 'Test' }, function (err) { + it('should fail to remove cover if not logged in', (done) => { + socketGroups.cover.remove({ uid: 0 }, { groupName: 'Test' }, (err) => { assert.equal(err.message, '[[error:no-privileges]]'); done(); }); }); - it('should fail to remove cover if not owner', function (done) { - socketGroups.cover.remove({ uid: regularUid }, { groupName: 'Test' }, function (err) { + it('should fail to remove cover if not owner', (done) => { + socketGroups.cover.remove({ uid: regularUid }, { groupName: 'Test' }, (err) => { assert.equal(err.message, '[[error:no-privileges]]'); done(); }); }); - it('should remove cover', function (done) { - socketGroups.cover.remove({ uid: adminUid }, { groupName: 'Test' }, function (err) { + it('should remove cover', (done) => { + socketGroups.cover.remove({ uid: adminUid }, { groupName: 'Test' }, (err) => { assert.ifError(err); - db.getObjectFields('group:Test', ['cover:url'], function (err, groupData) { + db.getObjectFields('group:Test', ['cover:url'], (err, groupData) => { assert.ifError(err); assert(!groupData['cover:url']); done(); diff --git a/test/helpers/index.js b/test/helpers/index.js index a85d2e9992..4d83e7c0cd 100644 --- a/test/helpers/index.js +++ b/test/helpers/index.js @@ -17,7 +17,7 @@ helpers.loginUser = function (username, password, callback) { url: `${nconf.get('url')}/api/config`, json: true, jar: jar, - }, function (err, res, body) { + }, (err, res, body) => { if (err || res.statusCode !== 200) { return callback(err || new Error('[[error:invalid-response]]')); } @@ -32,7 +32,7 @@ helpers.loginUser = function (username, password, callback) { headers: { 'x-csrf-token': body.csrf_token, }, - }, function (err, res) { + }, (err, res) => { if (err || res.statusCode !== 200) { return callback(err || new Error('[[error:invalid-response]]')); } @@ -47,7 +47,7 @@ helpers.logoutUser = function (jar, callback) { url: `${nconf.get('url')}/api/config`, json: true, jar: jar, - }, function (err, response, body) { + }, (err, response, body) => { if (err) { return callback(err, response, body); } @@ -59,7 +59,7 @@ helpers.logoutUser = function (jar, callback) { headers: { 'x-csrf-token': body.csrf_token, }, - }, function (err, response, body) { + }, (err, response, body) => { callback(err, response, body); }); }); @@ -78,11 +78,11 @@ helpers.connectSocketIO = function (res, callback) { }, }); - socket.on('connect', function () { + socket.on('connect', () => { callback(null, socket); }); - socket.on('error', function (err) { + socket.on('error', (err) => { callback(err); }); }; @@ -103,7 +103,7 @@ helpers.uploadFile = function (uploadEndPoint, filePath, body, jar, csrf_token, headers: { 'x-csrf-token': csrf_token, }, - }, function (err, res, body) { + }, (err, res, body) => { if (err) { return callback(err); } @@ -120,7 +120,7 @@ helpers.registerUser = function (data, callback) { url: `${nconf.get('url')}/api/config`, json: true, jar: jar, - }, function (err, response, body) { + }, (err, response, body) => { if (err) { return callback(err); } @@ -132,7 +132,7 @@ helpers.registerUser = function (data, callback) { headers: { 'x-csrf-token': body.csrf_token, }, - }, function (err, response, body) { + }, (err, response, body) => { callback(err, jar, response, body); }); }); @@ -143,14 +143,14 @@ helpers.copyFile = function (source, target, callback) { var cbCalled = false; var rd = fs.createReadStream(source); - rd.on('error', function (err) { + rd.on('error', (err) => { done(err); }); var wr = fs.createWriteStream(target); - wr.on('error', function (err) { + wr.on('error', (err) => { done(err); }); - wr.on('close', function () { + wr.on('close', () => { done(); }); rd.pipe(wr); diff --git a/test/image.js b/test/image.js index 7ace3aa6ca..f2c2c06941 100644 --- a/test/image.js +++ b/test/image.js @@ -7,11 +7,11 @@ var db = require('./mocks/databasemock'); var image = require('../src/image'); var file = require('../src/file'); -describe('image', function () { - it('should normalise image', function (done) { - image.normalise(path.join(__dirname, 'files/normalise.jpg'), '.jpg', function (err) { +describe('image', () => { + it('should normalise image', (done) => { + image.normalise(path.join(__dirname, 'files/normalise.jpg'), '.jpg', (err) => { assert.ifError(err); - file.exists(path.join(__dirname, 'files/normalise.jpg.png'), function (err, exists) { + file.exists(path.join(__dirname, 'files/normalise.jpg.png'), (err, exists) => { assert.ifError(err); assert(exists); done(); @@ -19,15 +19,15 @@ describe('image', function () { }); }); - it('should resize an image', function (done) { + it('should resize an image', (done) => { image.resizeImage({ path: path.join(__dirname, 'files/normalise.jpg'), target: path.join(__dirname, 'files/normalise-resized.jpg'), width: 50, height: 40, - }, function (err) { + }, (err) => { assert.ifError(err); - image.size(path.join(__dirname, 'files/normalise-resized.jpg'), function (err, bitmap) { + image.size(path.join(__dirname, 'files/normalise-resized.jpg'), (err, bitmap) => { assert.ifError(err); assert.equal(bitmap.width, 50); assert.equal(bitmap.height, 40); diff --git a/test/locale-detect.js b/test/locale-detect.js index 29b55ca1f5..5b76d70fdb 100644 --- a/test/locale-detect.js +++ b/test/locale-detect.js @@ -7,16 +7,16 @@ var request = require('request'); var db = require('./mocks/databasemock'); var meta = require('../src/meta'); -describe('Language detection', function () { - it('should detect the language for a guest', function (done) { - meta.configs.set('autoDetectLang', 1, function (err) { +describe('Language detection', () => { + it('should detect the language for a guest', (done) => { + meta.configs.set('autoDetectLang', 1, (err) => { assert.ifError(err); request(`${nconf.get('url')}/api/config`, { headers: { 'Accept-Language': 'de-DE,de;q=0.5', }, json: true, - }, function (err, res, body) { + }, (err, res, body) => { assert.ifError(err); assert.ok(body); @@ -26,15 +26,15 @@ describe('Language detection', function () { }); }); - it('should do nothing when disabled', function (done) { - meta.configs.set('autoDetectLang', 0, function (err) { + it('should do nothing when disabled', (done) => { + meta.configs.set('autoDetectLang', 0, (err) => { assert.ifError(err); request(`${nconf.get('url')}/api/config`, { headers: { 'Accept-Language': 'de-DE,de;q=0.5', }, json: true, - }, function (err, res, body) { + }, (err, res, body) => { assert.ifError(err); assert.ok(body); diff --git a/test/messaging.js b/test/messaging.js index 78b85e0598..f5a069ba97 100644 --- a/test/messaging.js +++ b/test/messaging.js @@ -13,19 +13,19 @@ var Messaging = require('../src/messaging'); var helpers = require('./helpers'); var socketModules = require('../src/socket.io/modules'); -describe('Messaging Library', function () { +describe('Messaging Library', () => { var fooUid; // the admin var bazUid; // the user with chat restriction enabled var herpUid; var roomId; - before(function (done) { + before((done) => { // Create 3 users: 1 admin, 2 regular async.series([ async.apply(User.create, { username: 'foo', password: 'barbar' }), // admin async.apply(User.create, { username: 'baz', password: 'quuxquux' }), // restricted user async.apply(User.create, { username: 'herp', password: 'derpderp' }), // regular user - ], function (err, uids) { + ], (err, uids) => { if (err) { return done(err); } @@ -41,20 +41,20 @@ describe('Messaging Library', function () { }); }); - describe('.canMessage()', function () { - it('should allow messages to be sent to an unrestricted user', function (done) { - Messaging.canMessageUser(bazUid, herpUid, function (err) { + describe('.canMessage()', () => { + it('should allow messages to be sent to an unrestricted user', (done) => { + Messaging.canMessageUser(bazUid, herpUid, (err) => { assert.ifError(err); done(); }); }); - it('should NOT allow messages to be sent to a restricted user', function (done) { - User.setSetting(bazUid, 'restrictChat', '1', function (err) { + it('should NOT allow messages to be sent to a restricted user', (done) => { + User.setSetting(bazUid, 'restrictChat', '1', (err) => { assert.ifError(err); - Messaging.canMessageUser(herpUid, bazUid, function (err) { + Messaging.canMessageUser(herpUid, bazUid, (err) => { assert.strictEqual(err.message, '[[error:chat-restricted]]'); - socketModules.chats.addUserToRoom({ uid: herpUid }, { roomId: 1, username: 'baz' }, function (err) { + socketModules.chats.addUserToRoom({ uid: herpUid }, { roomId: 1, username: 'baz' }, (err) => { assert.equal(err.message, '[[error:chat-restricted]]'); done(); }); @@ -62,16 +62,16 @@ describe('Messaging Library', function () { }); }); - it('should always allow admins through', function (done) { - Messaging.canMessageUser(fooUid, bazUid, function (err) { + it('should always allow admins through', (done) => { + Messaging.canMessageUser(fooUid, bazUid, (err) => { assert.ifError(err); done(); }); }); - it('should allow messages to be sent to a restricted user if restricted user follows sender', function (done) { - User.follow(bazUid, herpUid, function () { - Messaging.canMessageUser(herpUid, bazUid, function (err) { + it('should allow messages to be sent to a restricted user if restricted user follows sender', (done) => { + User.follow(bazUid, herpUid, () => { + Messaging.canMessageUser(herpUid, bazUid, (err) => { assert.ifError(err); done(); }); @@ -79,21 +79,21 @@ describe('Messaging Library', function () { }); }); - describe('rooms', function () { - it('should fail to create a new chat room with invalid data', function (done) { - socketModules.chats.newRoom({ uid: fooUid }, null, function (err) { + describe('rooms', () => { + it('should fail to create a new chat room with invalid data', (done) => { + socketModules.chats.newRoom({ uid: fooUid }, null, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); }); - it('should return rate limit error on second try', function (done) { + it('should return rate limit error on second try', (done) => { var socketMock = { uid: fooUid }; var oldValue = meta.config.chatMessageDelay; meta.config.chatMessageDelay = 1000; - socketModules.chats.newRoom(socketMock, { touid: bazUid }, function (err) { + socketModules.chats.newRoom(socketMock, { touid: bazUid }, (err) => { assert.ifError(err); - socketModules.chats.newRoom(socketMock, { touid: bazUid }, function (err) { + socketModules.chats.newRoom(socketMock, { touid: bazUid }, (err) => { assert.equal(err.message, '[[error:too-many-messages]]'); meta.configs.chatMessageDelay = oldValue; done(); @@ -101,12 +101,12 @@ describe('Messaging Library', function () { }); }); - it('should create a new chat room', function (done) { - socketModules.chats.newRoom({ uid: fooUid }, { touid: bazUid }, function (err, _roomId) { + it('should create a new chat room', (done) => { + socketModules.chats.newRoom({ uid: fooUid }, { touid: bazUid }, (err, _roomId) => { roomId = _roomId; assert.ifError(err); assert(roomId); - socketModules.chats.canMessage({ uid: fooUid }, _roomId, function (err) { + socketModules.chats.canMessage({ uid: fooUid }, _roomId, (err) => { assert.ifError(err); done(); }); @@ -114,24 +114,24 @@ describe('Messaging Library', function () { }); it('should send a user-join system message when a chat room is created', (done) => { - socketModules.chats.getMessages({ uid: fooUid }, { uid: fooUid, roomId: roomId, start: 0 }, function (err, messages) { + socketModules.chats.getMessages({ uid: fooUid }, { uid: fooUid, roomId: roomId, start: 0 }, (err, messages) => { assert.ifError(err); assert.equal(messages.length, 2); assert.strictEqual(messages[0].system, true); assert.strictEqual(messages[0].content, 'user-join'); - socketModules.chats.edit({ uid: fooUid }, { roomId: roomId, mid: messages[0].messageId, message: 'test' }, function (err) { + socketModules.chats.edit({ uid: fooUid }, { roomId: roomId, mid: messages[0].messageId, message: 'test' }, (err) => { assert.equal(err.message, '[[error:cant-edit-chat-message]]'); done(); }); }); }); - it('should fail to add user to room with invalid data', function (done) { - socketModules.chats.addUserToRoom({ uid: fooUid }, null, function (err) { + it('should fail to add user to room with invalid data', (done) => { + socketModules.chats.addUserToRoom({ uid: fooUid }, null, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); - socketModules.chats.addUserToRoom({ uid: fooUid }, { roomId: null }, function (err) { + socketModules.chats.addUserToRoom({ uid: fooUid }, { roomId: null }, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); - socketModules.chats.addUserToRoom({ uid: fooUid }, { roomId: roomId, username: null }, function (err) { + socketModules.chats.addUserToRoom({ uid: fooUid }, { roomId: roomId, username: null }, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); @@ -139,10 +139,10 @@ describe('Messaging Library', function () { }); }); - it('should add a user to room', function (done) { - socketModules.chats.addUserToRoom({ uid: fooUid }, { roomId: roomId, username: 'herp' }, function (err) { + it('should add a user to room', (done) => { + socketModules.chats.addUserToRoom({ uid: fooUid }, { roomId: roomId, username: 'herp' }, (err) => { assert.ifError(err); - Messaging.isUserInRoom(herpUid, roomId, function (err, isInRoom) { + Messaging.isUserInRoom(herpUid, roomId, (err, isInRoom) => { assert.ifError(err); assert(isInRoom); done(); @@ -150,12 +150,12 @@ describe('Messaging Library', function () { }); }); - it('should get users in room', async function () { + it('should get users in room', async () => { const data = await socketModules.chats.getUsersInRoom({ uid: fooUid }, { roomId: roomId }); assert(Array.isArray(data) && data.length === 3); }); - it('should throw error if user is not in room', async function () { + it('should throw error if user is not in room', async () => { try { const data = await socketModules.chats.getUsersInRoom({ uid: 123123123 }, { roomId: roomId }); } catch (err) { @@ -163,46 +163,46 @@ describe('Messaging Library', function () { } }); - it('should fail to add users to room if max is reached', function (done) { + it('should fail to add users to room if max is reached', (done) => { meta.config.maximumUsersInChatRoom = 2; - socketModules.chats.addUserToRoom({ uid: fooUid }, { roomId: roomId, username: 'test' }, function (err) { + socketModules.chats.addUserToRoom({ uid: fooUid }, { roomId: roomId, username: 'test' }, (err) => { assert.equal(err.message, '[[error:cant-add-more-users-to-chat-room]]'); meta.config.maximumUsersInChatRoom = 0; done(); }); }); - it('should fail to add users to room if user does not exist', function (done) { - socketModules.chats.addUserToRoom({ uid: fooUid }, { roomId: roomId, username: 'doesnotexist' }, function (err) { + it('should fail to add users to room if user does not exist', (done) => { + socketModules.chats.addUserToRoom({ uid: fooUid }, { roomId: roomId, username: 'doesnotexist' }, (err) => { assert.equal(err.message, '[[error:no-user]]'); done(); }); }); - it('should fail to add self to room', function (done) { - socketModules.chats.addUserToRoom({ uid: fooUid }, { roomId: roomId, username: 'foo' }, function (err) { + it('should fail to add self to room', (done) => { + socketModules.chats.addUserToRoom({ uid: fooUid }, { roomId: roomId, username: 'foo' }, (err) => { assert.equal(err.message, '[[error:cant-chat-with-yourself]]'); done(); }); }); - it('should fail to leave room with invalid data', function (done) { - socketModules.chats.leave({ uid: null }, roomId, function (err) { + it('should fail to leave room with invalid data', (done) => { + socketModules.chats.leave({ uid: null }, roomId, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); - socketModules.chats.leave({ uid: fooUid }, null, function (err) { + socketModules.chats.leave({ uid: fooUid }, null, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); }); }); - it('should leave the chat room', function (done) { - socketModules.chats.leave({ uid: bazUid }, roomId, function (err) { + it('should leave the chat room', (done) => { + socketModules.chats.leave({ uid: bazUid }, roomId, (err) => { assert.ifError(err); - Messaging.isUserInRoom(bazUid, roomId, function (err, isUserInRoom) { + Messaging.isUserInRoom(bazUid, roomId, (err, isUserInRoom) => { assert.ifError(err); assert.equal(isUserInRoom, false); - Messaging.getRoomData(roomId, function (err, data) { + Messaging.getRoomData(roomId, (err, data) => { assert.ifError(err); assert.equal(data.owner, fooUid); done(); @@ -212,7 +212,7 @@ describe('Messaging Library', function () { }); it('should send a user-leave system message when a user leaves the chat room', (done) => { - socketModules.chats.getMessages({ uid: fooUid }, { uid: fooUid, roomId: roomId, start: 0 }, function (err, messages) { + socketModules.chats.getMessages({ uid: fooUid }, { uid: fooUid, roomId: roomId, start: 0 }, (err, messages) => { assert.ifError(err); assert.equal(messages.length, 4); const message = messages.pop(); @@ -231,14 +231,14 @@ describe('Messaging Library', function () { assert.strictEqual(message.content, 'user-leave'); }); - it('should change owner when owner leaves room', function (done) { - socketModules.chats.newRoom({ uid: herpUid }, { touid: fooUid }, function (err, roomId) { + it('should change owner when owner leaves room', (done) => { + socketModules.chats.newRoom({ uid: herpUid }, { touid: fooUid }, (err, roomId) => { assert.ifError(err); - socketModules.chats.addUserToRoom({ uid: herpUid }, { roomId: roomId, username: 'baz' }, function (err) { + socketModules.chats.addUserToRoom({ uid: herpUid }, { roomId: roomId, username: 'baz' }, (err) => { assert.ifError(err); - socketModules.chats.leave({ uid: herpUid }, roomId, function (err) { + socketModules.chats.leave({ uid: herpUid }, roomId, (err) => { assert.ifError(err); - Messaging.getRoomData(roomId, function (err, data) { + Messaging.getRoomData(roomId, (err, data) => { assert.ifError(err); assert.equal(data.owner, fooUid); done(); @@ -248,16 +248,16 @@ describe('Messaging Library', function () { }); }); - it('should change owner if owner is deleted', function (done) { - User.create({ username: 'deleted_chat_user' }, function (err, sender) { + it('should change owner if owner is deleted', (done) => { + User.create({ username: 'deleted_chat_user' }, (err, sender) => { assert.ifError(err); - User.create({ username: 'receiver' }, function (err, receiver) { + User.create({ username: 'receiver' }, (err, receiver) => { assert.ifError(err); - socketModules.chats.newRoom({ uid: sender }, { touid: receiver }, function (err, roomId) { + socketModules.chats.newRoom({ uid: sender }, { touid: receiver }, (err, roomId) => { assert.ifError(err); - User.deleteAccount(sender, function (err) { + User.deleteAccount(sender, (err) => { assert.ifError(err); - Messaging.getRoomData(roomId, function (err, data) { + Messaging.getRoomData(roomId, (err, data) => { assert.ifError(err); assert.equal(data.owner, receiver); done(); @@ -268,36 +268,36 @@ describe('Messaging Library', function () { }); }); - it('should fail to remove user from room', function (done) { - socketModules.chats.removeUserFromRoom({ uid: fooUid }, null, function (err) { + it('should fail to remove user from room', (done) => { + socketModules.chats.removeUserFromRoom({ uid: fooUid }, null, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); - socketModules.chats.removeUserFromRoom({ uid: fooUid }, {}, function (err) { + socketModules.chats.removeUserFromRoom({ uid: fooUid }, {}, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); }); }); - it('should fail to remove user from room if user does not exist', function (done) { - socketModules.chats.removeUserFromRoom({ uid: fooUid }, { roomId: roomId, uid: 99 }, function (err) { + it('should fail to remove user from room if user does not exist', (done) => { + socketModules.chats.removeUserFromRoom({ uid: fooUid }, { roomId: roomId, uid: 99 }, (err) => { assert.equal('[[error:no-user]]', err.message); done(); }); }); - it('should remove user from room', function (done) { - socketModules.chats.newRoom({ uid: fooUid }, { touid: herpUid }, function (err, roomId) { + it('should remove user from room', (done) => { + socketModules.chats.newRoom({ uid: fooUid }, { touid: herpUid }, (err, roomId) => { assert.ifError(err); - Messaging.isUserInRoom(herpUid, roomId, function (err, isInRoom) { + Messaging.isUserInRoom(herpUid, roomId, (err, isInRoom) => { assert.ifError(err); assert(isInRoom); - socketModules.chats.removeUserFromRoom({ uid: fooUid }, { roomId: roomId, uid: herpUid }, function (err) { + socketModules.chats.removeUserFromRoom({ uid: fooUid }, { roomId: roomId, uid: herpUid }, (err) => { assert.equal(err.message, '[[error:cant-remove-last-user]]'); - socketModules.chats.addUserToRoom({ uid: fooUid }, { roomId: roomId, username: 'baz' }, function (err) { + socketModules.chats.addUserToRoom({ uid: fooUid }, { roomId: roomId, username: 'baz' }, (err) => { assert.ifError(err); - socketModules.chats.removeUserFromRoom({ uid: fooUid }, { roomId: roomId, uid: herpUid }, function (err) { + socketModules.chats.removeUserFromRoom({ uid: fooUid }, { roomId: roomId, uid: herpUid }, (err) => { assert.ifError(err); - Messaging.isUserInRoom(herpUid, roomId, function (err, isInRoom) { + Messaging.isUserInRoom(herpUid, roomId, (err, isInRoom) => { assert.ifError(err); assert(!isInRoom); done(); @@ -309,12 +309,12 @@ describe('Messaging Library', function () { }); }); - it('should fail to send a message to room with invalid data', function (done) { - socketModules.chats.send({ uid: fooUid }, null, function (err) { + it('should fail to send a message to room with invalid data', (done) => { + socketModules.chats.send({ uid: fooUid }, null, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); - socketModules.chats.send({ uid: fooUid }, { roomId: null }, function (err) { + socketModules.chats.send({ uid: fooUid }, { roomId: null }, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); - socketModules.chats.send({ uid: null }, { roomId: 1 }, function (err) { + socketModules.chats.send({ uid: null }, { roomId: 1 }, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); @@ -322,21 +322,21 @@ describe('Messaging Library', function () { }); }); - it('should fail to send chat if content is empty', function (done) { - socketModules.chats.send({ uid: fooUid }, { roomId: roomId, message: ' ' }, function (err) { + it('should fail to send chat if content is empty', (done) => { + socketModules.chats.send({ uid: fooUid }, { roomId: roomId, message: ' ' }, (err) => { assert.equal(err.message, '[[error:invalid-chat-message]]'); done(); }); }); - it('should send a message to a room', function (done) { - socketModules.chats.send({ uid: fooUid }, { roomId: roomId, message: 'first chat message' }, function (err, messageData) { + it('should send a message to a room', (done) => { + socketModules.chats.send({ uid: fooUid }, { roomId: roomId, message: 'first chat message' }, (err, messageData) => { assert.ifError(err); assert(messageData); assert.equal(messageData.content, 'first chat message'); assert(messageData.fromUser); assert(messageData.roomId, roomId); - socketModules.chats.getRaw({ uid: fooUid }, { mid: messageData.mid }, function (err, raw) { + socketModules.chats.getRaw({ uid: fooUid }, { mid: messageData.mid }, (err, raw) => { assert.ifError(err); assert.equal(raw, 'first chat message'); setTimeout(done, 300); @@ -344,13 +344,13 @@ describe('Messaging Library', function () { }); }); - it('should fail to send second message due to rate limit', function (done) { + it('should fail to send second message due to rate limit', (done) => { var socketMock = { uid: fooUid }; var oldValue = meta.config.chatMessageDelay; meta.config.chatMessageDelay = 1000; - socketModules.chats.send(socketMock, { roomId: roomId, message: 'first chat message' }, function (err) { + socketModules.chats.send(socketMock, { roomId: roomId, message: 'first chat message' }, (err) => { assert.ifError(err); - socketModules.chats.send(socketMock, { roomId: roomId, message: 'first chat message' }, function (err) { + socketModules.chats.send(socketMock, { roomId: roomId, message: 'first chat message' }, (err) => { assert.equal(err.message, '[[error:too-many-messages]]'); meta.config.chatMessageDelay = oldValue; done(); @@ -358,30 +358,30 @@ describe('Messaging Library', function () { }); }); - it('should return invalid-data error', function (done) { - socketModules.chats.getRaw({ uid: fooUid }, null, function (err) { + it('should return invalid-data error', (done) => { + socketModules.chats.getRaw({ uid: fooUid }, null, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); - socketModules.chats.getRaw({ uid: fooUid }, {}, function (err) { + socketModules.chats.getRaw({ uid: fooUid }, {}, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); }); }); - it('should return not allowed error if mid is not in room', function (done) { + it('should return not allowed error if mid is not in room', (done) => { var myRoomId; - User.create({ username: 'dummy' }, function (err, uid) { + User.create({ username: 'dummy' }, (err, uid) => { assert.ifError(err); - socketModules.chats.newRoom({ uid: bazUid }, { touid: uid }, function (err, _roomId) { + socketModules.chats.newRoom({ uid: bazUid }, { touid: uid }, (err, _roomId) => { myRoomId = _roomId; assert.ifError(err); assert(myRoomId); - socketModules.chats.getRaw({ uid: bazUid }, { mid: 200 }, function (err) { + socketModules.chats.getRaw({ uid: bazUid }, { mid: 200 }, (err) => { assert(err); assert.equal(err.message, '[[error:not-allowed]]'); - socketModules.chats.send({ uid: bazUid }, { roomId: myRoomId, message: 'admin will see this' }, function (err, message) { + socketModules.chats.send({ uid: bazUid }, { roomId: myRoomId, message: 'admin will see this' }, (err, message) => { assert.ifError(err); - socketModules.chats.getRaw({ uid: fooUid }, { mid: message.mid }, function (err, raw) { + socketModules.chats.getRaw({ uid: fooUid }, { mid: message.mid }, (err, raw) => { assert.ifError(err); assert.equal(raw, 'admin will see this'); done(); @@ -393,15 +393,15 @@ describe('Messaging Library', function () { }); - it('should notify offline users of message', function (done) { + it('should notify offline users of message', (done) => { meta.config.notificationSendDelay = 0.1; - db.sortedSetAdd('users:online', Date.now() - ((meta.config.onlineCutoff * 60000) + 50000), herpUid, function (err) { + db.sortedSetAdd('users:online', Date.now() - ((meta.config.onlineCutoff * 60000) + 50000), herpUid, (err) => { assert.ifError(err); - socketModules.chats.send({ uid: fooUid }, { roomId: roomId, message: 'second chat message' }, function (err) { + socketModules.chats.send({ uid: fooUid }, { roomId: roomId, message: 'second chat message' }, (err) => { assert.ifError(err); - setTimeout(function () { - User.notifications.get(herpUid, function (err, data) { + setTimeout(() => { + User.notifications.get(herpUid, (err, data) => { assert.ifError(err); assert(data.unread[0]); var notification = data.unread[0]; @@ -415,14 +415,14 @@ describe('Messaging Library', function () { }); }); - it('should fail to get messages from room with invalid data', function (done) { - socketModules.chats.getMessages({ uid: null }, null, function (err) { + it('should fail to get messages from room with invalid data', (done) => { + socketModules.chats.getMessages({ uid: null }, null, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); - socketModules.chats.getMessages({ uid: fooUid }, null, function (err) { + socketModules.chats.getMessages({ uid: fooUid }, null, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); - socketModules.chats.getMessages({ uid: fooUid }, { uid: null }, function (err) { + socketModules.chats.getMessages({ uid: fooUid }, { uid: null }, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); - socketModules.chats.getMessages({ uid: fooUid }, { uid: 1, roomId: null }, function (err) { + socketModules.chats.getMessages({ uid: fooUid }, { uid: 1, roomId: null }, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); @@ -431,12 +431,12 @@ describe('Messaging Library', function () { }); }); - it('should get messages from room', function (done) { + it('should get messages from room', (done) => { socketModules.chats.getMessages({ uid: fooUid }, { uid: fooUid, roomId: roomId, start: 0, - }, function (err, messages) { + }, (err, messages) => { assert.ifError(err); assert(Array.isArray(messages)); assert.equal(messages[4].roomId, roomId); @@ -445,43 +445,43 @@ describe('Messaging Library', function () { }); }); - it('should fail to mark read with invalid data', function (done) { - socketModules.chats.markRead({ uid: null }, roomId, function (err) { + it('should fail to mark read with invalid data', (done) => { + socketModules.chats.markRead({ uid: null }, roomId, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); - socketModules.chats.markRead({ uid: fooUid }, null, function (err) { + socketModules.chats.markRead({ uid: fooUid }, null, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); }); }); - it('should not error if user is not in room', function (done) { - socketModules.chats.markRead({ uid: herpUid }, 10, function (err) { + it('should not error if user is not in room', (done) => { + socketModules.chats.markRead({ uid: herpUid }, 10, (err) => { assert.ifError(err); done(); }); }); - it('should mark room read', function (done) { - socketModules.chats.markRead({ uid: fooUid }, roomId, function (err) { + it('should mark room read', (done) => { + socketModules.chats.markRead({ uid: fooUid }, roomId, (err) => { assert.ifError(err); done(); }); }); - it('should mark all rooms read', function (done) { - socketModules.chats.markAllRead({ uid: fooUid }, {}, function (err) { + it('should mark all rooms read', (done) => { + socketModules.chats.markAllRead({ uid: fooUid }, {}, (err) => { assert.ifError(err); done(); }); }); - it('should fail to rename room with invalid data', function (done) { - socketModules.chats.renameRoom({ uid: fooUid }, null, function (err) { + it('should fail to rename room with invalid data', (done) => { + socketModules.chats.renameRoom({ uid: fooUid }, null, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); - socketModules.chats.renameRoom({ uid: fooUid }, { roomId: null }, function (err) { + socketModules.chats.renameRoom({ uid: fooUid }, { roomId: null }, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); - socketModules.chats.renameRoom({ uid: fooUid }, { roomId: roomId, newName: null }, function (err) { + socketModules.chats.renameRoom({ uid: fooUid }, { roomId: roomId, newName: null }, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); @@ -489,15 +489,15 @@ describe('Messaging Library', function () { }); }); - it('should rename room', function (done) { - socketModules.chats.renameRoom({ uid: fooUid }, { roomId: roomId, newName: 'new room name' }, function (err) { + it('should rename room', (done) => { + socketModules.chats.renameRoom({ uid: fooUid }, { roomId: roomId, newName: 'new room name' }, (err) => { assert.ifError(err); done(); }); }); it('should send a room-rename system message when a room is renamed', (done) => { - socketModules.chats.getMessages({ uid: fooUid }, { uid: fooUid, roomId: roomId, start: 0 }, function (err, messages) { + socketModules.chats.getMessages({ uid: fooUid }, { uid: fooUid, roomId: roomId, start: 0 }, (err, messages) => { assert.ifError(err); const message = messages.pop(); assert.strictEqual(message.system, true); @@ -506,25 +506,25 @@ describe('Messaging Library', function () { }); }); - it('should fail to load room with invalid-data', function (done) { - socketModules.chats.loadRoom({ uid: fooUid }, null, function (err) { + it('should fail to load room with invalid-data', (done) => { + socketModules.chats.loadRoom({ uid: fooUid }, null, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); - socketModules.chats.loadRoom({ uid: fooUid }, { roomId: null }, function (err) { + socketModules.chats.loadRoom({ uid: fooUid }, { roomId: null }, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); }); }); - it('should fail to load room if user is not in', function (done) { - socketModules.chats.loadRoom({ uid: 0 }, { roomId: roomId }, function (err) { + it('should fail to load room if user is not in', (done) => { + socketModules.chats.loadRoom({ uid: 0 }, { roomId: roomId }, (err) => { assert.equal(err.message, '[[error:no-privileges]]'); done(); }); }); - it('should load chat room', function (done) { - socketModules.chats.loadRoom({ uid: fooUid }, { roomId: roomId }, function (err, data) { + it('should load chat room', (done) => { + socketModules.chats.loadRoom({ uid: fooUid }, { roomId: roomId }, (err, data) => { assert.ifError(err); assert(data); assert.equal(data.roomName, 'new room name'); @@ -532,10 +532,10 @@ describe('Messaging Library', function () { }); }); - it('should return true if user is dnd', function (done) { - db.setObjectField(`user:${herpUid}`, 'status', 'dnd', function (err) { + it('should return true if user is dnd', (done) => { + db.setObjectField(`user:${herpUid}`, 'status', 'dnd', (err) => { assert.ifError(err); - socketModules.chats.isDnD({ uid: fooUid }, herpUid, function (err, isDnD) { + socketModules.chats.isDnD({ uid: fooUid }, herpUid, (err, isDnD) => { assert.ifError(err); assert(isDnD); done(); @@ -543,12 +543,12 @@ describe('Messaging Library', function () { }); }); - it('should fail to load recent chats with invalid data', function (done) { - socketModules.chats.getRecentChats({ uid: fooUid }, null, function (err) { + it('should fail to load recent chats with invalid data', (done) => { + socketModules.chats.getRecentChats({ uid: fooUid }, null, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); - socketModules.chats.getRecentChats({ uid: fooUid }, { after: null }, function (err) { + socketModules.chats.getRecentChats({ uid: fooUid }, { after: null }, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); - socketModules.chats.getRecentChats({ uid: fooUid }, { after: 0, uid: null }, function (err) { + socketModules.chats.getRecentChats({ uid: fooUid }, { after: 0, uid: null }, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); @@ -556,18 +556,18 @@ describe('Messaging Library', function () { }); }); - it('should load recent chats of user', function (done) { - socketModules.chats.getRecentChats({ uid: fooUid }, { after: 0, uid: fooUid }, function (err, data) { + it('should load recent chats of user', (done) => { + socketModules.chats.getRecentChats({ uid: fooUid }, { after: 0, uid: fooUid }, (err, data) => { assert.ifError(err); assert(Array.isArray(data.rooms)); done(); }); }); - it('should escape teaser', function (done) { - socketModules.chats.send({ uid: fooUid }, { roomId: roomId, message: ' { + socketModules.chats.send({ uid: fooUid }, { roomId: roomId, message: ' { assert.ifError(err); - socketModules.chats.getRecentChats({ uid: fooUid }, { after: 0, uid: fooUid }, function (err, data) { + socketModules.chats.getRecentChats({ uid: fooUid }, { after: 0, uid: fooUid }, (err, data) => { assert.ifError(err); assert.equal(data.rooms[0].teaser.content, '<svg/onload=alert(document.location);'); done(); @@ -575,18 +575,18 @@ describe('Messaging Library', function () { }); }); - it('should fail to check if user has private chat with invalid data', function (done) { - socketModules.chats.hasPrivateChat({ uid: null }, null, function (err) { + it('should fail to check if user has private chat with invalid data', (done) => { + socketModules.chats.hasPrivateChat({ uid: null }, null, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); - socketModules.chats.hasPrivateChat({ uid: fooUid }, null, function (err) { + socketModules.chats.hasPrivateChat({ uid: fooUid }, null, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); }); }); - it('should check if user has private chat with another uid', function (done) { - socketModules.chats.hasPrivateChat({ uid: fooUid }, herpUid, function (err, roomId) { + it('should check if user has private chat with another uid', (done) => { + socketModules.chats.hasPrivateChat({ uid: fooUid }, herpUid, (err, roomId) => { assert.ifError(err); assert(roomId); done(); @@ -594,11 +594,11 @@ describe('Messaging Library', function () { }); }); - describe('edit/delete', function () { + describe('edit/delete', () => { var socketModules = require('../src/socket.io/modules'); var mid; let mid2; - before(async function () { + before(async () => { await socketModules.chats.addUserToRoom({ uid: fooUid }, { roomId: roomId, username: 'baz' }); mid = (await socketModules.chats.send({ uid: fooUid }, { roomId: roomId, message: 'first chat message' })).mid; mid2 = (await socketModules.chats.send({ uid: bazUid }, { roomId: roomId, message: 'second chat message' })).mid; @@ -608,12 +608,12 @@ describe('Messaging Library', function () { await socketModules.chats.leave({ uid: bazUid }, roomId); }); - it('should fail to edit message with invalid data', function (done) { - socketModules.chats.edit({ uid: fooUid }, null, function (err) { + it('should fail to edit message with invalid data', (done) => { + socketModules.chats.edit({ uid: fooUid }, null, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); - socketModules.chats.edit({ uid: fooUid }, { roomId: null }, function (err) { + socketModules.chats.edit({ uid: fooUid }, { roomId: null }, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); - socketModules.chats.edit({ uid: fooUid }, { roomId: 1, message: null }, function (err) { + socketModules.chats.edit({ uid: fooUid }, { roomId: 1, message: null }, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); @@ -621,24 +621,24 @@ describe('Messaging Library', function () { }); }); - it('should fail to edit message if new content is empty string', function (done) { - socketModules.chats.edit({ uid: fooUid }, { mid: mid, roomId: roomId, message: ' ' }, function (err) { + it('should fail to edit message if new content is empty string', (done) => { + socketModules.chats.edit({ uid: fooUid }, { mid: mid, roomId: roomId, message: ' ' }, (err) => { assert.equal(err.message, '[[error:invalid-chat-message]]'); done(); }); }); - it('should fail to edit message if not own message', function (done) { - socketModules.chats.edit({ uid: herpUid }, { mid: mid, roomId: roomId, message: 'message edited' }, function (err) { + it('should fail to edit message if not own message', (done) => { + socketModules.chats.edit({ uid: herpUid }, { mid: mid, roomId: roomId, message: 'message edited' }, (err) => { assert.equal(err.message, '[[error:cant-edit-chat-message]]'); done(); }); }); - it('should edit message', function (done) { - socketModules.chats.edit({ uid: fooUid }, { mid: mid, roomId: roomId, message: 'message edited' }, function (err) { + it('should edit message', (done) => { + socketModules.chats.edit({ uid: fooUid }, { mid: mid, roomId: roomId, message: 'message edited' }, (err) => { assert.ifError(err); - socketModules.chats.getRaw({ uid: fooUid }, { mid: mid }, function (err, raw) { + socketModules.chats.getRaw({ uid: fooUid }, { mid: mid }, (err, raw) => { assert.ifError(err); assert.equal(raw, 'message edited'); done(); @@ -646,12 +646,12 @@ describe('Messaging Library', function () { }); }); - it('should fail to delete message with invalid data', function (done) { - socketModules.chats.delete({ uid: fooUid }, null, function (err) { + it('should fail to delete message with invalid data', (done) => { + socketModules.chats.delete({ uid: fooUid }, null, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); - socketModules.chats.delete({ uid: fooUid }, { roomId: null }, function (err) { + socketModules.chats.delete({ uid: fooUid }, { roomId: null }, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); - socketModules.chats.delete({ uid: fooUid }, { roomId: 1, messageId: null }, function (err) { + socketModules.chats.delete({ uid: fooUid }, { roomId: 1, messageId: null }, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); @@ -659,17 +659,17 @@ describe('Messaging Library', function () { }); }); - it('should fail to delete message if not owner', function (done) { - socketModules.chats.delete({ uid: herpUid }, { messageId: mid, roomId: roomId }, function (err) { + it('should fail to delete message if not owner', (done) => { + socketModules.chats.delete({ uid: herpUid }, { messageId: mid, roomId: roomId }, (err) => { assert.equal(err.message, '[[error:cant-delete-chat-message]]'); done(); }); }); - it('should mark the message as deleted', function (done) { - socketModules.chats.delete({ uid: fooUid }, { messageId: mid, roomId: roomId }, function (err) { + it('should mark the message as deleted', (done) => { + socketModules.chats.delete({ uid: fooUid }, { messageId: mid, roomId: roomId }, (err) => { assert.ifError(err); - db.getObjectField(`message:${mid}`, 'deleted', function (err, value) { + db.getObjectField(`message:${mid}`, 'deleted', (err, value) => { assert.ifError(err); assert.strictEqual(1, parseInt(value, 10)); done(); @@ -677,12 +677,12 @@ describe('Messaging Library', function () { }); }); - it('should show deleted message to original users', function (done) { - socketModules.chats.getMessages({ uid: fooUid }, { uid: fooUid, roomId: roomId, start: 0 }, function (err, messages) { + it('should show deleted message to original users', (done) => { + socketModules.chats.getMessages({ uid: fooUid }, { uid: fooUid, roomId: roomId, start: 0 }, (err, messages) => { assert.ifError(err); // Reduce messages to their mids - var mids = messages.reduce(function (mids, cur) { + var mids = messages.reduce((mids, cur) => { mids.push(cur.messageId); return mids; }, []); @@ -692,27 +692,27 @@ describe('Messaging Library', function () { }); }); - it('should not show deleted message to other users', function (done) { - socketModules.chats.getMessages({ uid: herpUid }, { uid: herpUid, roomId: roomId, start: 0 }, function (err, messages) { + it('should not show deleted message to other users', (done) => { + socketModules.chats.getMessages({ uid: herpUid }, { uid: herpUid, roomId: roomId, start: 0 }, (err, messages) => { assert.ifError(err); - messages.forEach(function (msg) { + messages.forEach((msg) => { assert(!msg.deleted || msg.content === '[[modules:chat.message-deleted]]', msg.content); }); done(); }); }); - it('should error out if a message is deleted again', function (done) { - socketModules.chats.delete({ uid: fooUid }, { messageId: mid, roomId: roomId }, function (err) { + it('should error out if a message is deleted again', (done) => { + socketModules.chats.delete({ uid: fooUid }, { messageId: mid, roomId: roomId }, (err) => { assert.strictEqual('[[error:chat-deleted-already]]', err.message); done(); }); }); - it('should restore the message', function (done) { - socketModules.chats.restore({ uid: fooUid }, { messageId: mid, roomId: roomId }, function (err) { + it('should restore the message', (done) => { + socketModules.chats.restore({ uid: fooUid }, { messageId: mid, roomId: roomId }, (err) => { assert.ifError(err); - db.getObjectField(`message:${mid}`, 'deleted', function (err, value) { + db.getObjectField(`message:${mid}`, 'deleted', (err, value) => { assert.ifError(err); assert.strictEqual(0, parseInt(value, 10)); done(); @@ -720,8 +720,8 @@ describe('Messaging Library', function () { }); }); - it('should error out if a message is restored again', function (done) { - socketModules.chats.restore({ uid: fooUid }, { messageId: mid, roomId: roomId }, function (err) { + it('should error out if a message is restored again', (done) => { + socketModules.chats.restore({ uid: fooUid }, { messageId: mid, roomId: roomId }, (err) => { assert.strictEqual('[[error:chat-restored-already]]', err.message); done(); }); @@ -760,19 +760,19 @@ describe('Messaging Library', function () { }); }); - describe('controller', function () { - it('should 404 if chat is disabled', function (done) { + describe('controller', () => { + it('should 404 if chat is disabled', (done) => { meta.config.disableChat = 1; - request(`${nconf.get('url')}/user/baz/chats`, function (err, response) { + request(`${nconf.get('url')}/user/baz/chats`, (err, response) => { assert.ifError(err); assert.equal(response.statusCode, 404); done(); }); }); - it('should 500 for guest with no privilege error', function (done) { + it('should 500 for guest with no privilege error', (done) => { meta.config.disableChat = 0; - request(`${nconf.get('url')}/api/user/baz/chats`, { json: true }, function (err, response, body) { + request(`${nconf.get('url')}/api/user/baz/chats`, { json: true }, (err, response, body) => { assert.ifError(err); assert.equal(response.statusCode, 500); assert.equal(body.error, '[[error:no-privileges]]'); @@ -780,8 +780,8 @@ describe('Messaging Library', function () { }); }); - it('should 404 for non-existent user', function (done) { - request(`${nconf.get('url')}/user/doesntexist/chats`, function (err, response) { + it('should 404 for non-existent user', (done) => { + request(`${nconf.get('url')}/user/doesntexist/chats`, (err, response) => { assert.ifError(err); assert.equal(response.statusCode, 404); done(); @@ -789,18 +789,18 @@ describe('Messaging Library', function () { }); }); - describe('logged in chat controller', function () { + describe('logged in chat controller', () => { var jar; - before(function (done) { - helpers.loginUser('herp', 'derpderp', function (err, _jar) { + before((done) => { + helpers.loginUser('herp', 'derpderp', (err, _jar) => { assert.ifError(err); jar = _jar; done(); }); }); - it('should return chats page data', function (done) { - request(`${nconf.get('url')}/api/user/herp/chats`, { json: true, jar: jar }, function (err, response, body) { + it('should return chats page data', (done) => { + request(`${nconf.get('url')}/api/user/herp/chats`, { json: true, jar: jar }, (err, response, body) => { assert.ifError(err); assert.equal(response.statusCode, 200); assert(Array.isArray(body.rooms)); @@ -810,8 +810,8 @@ describe('Messaging Library', function () { }); }); - it('should return room data', function (done) { - request(`${nconf.get('url')}/api/user/herp/chats/${roomId}`, { json: true, jar: jar }, function (err, response, body) { + it('should return room data', (done) => { + request(`${nconf.get('url')}/api/user/herp/chats/${roomId}`, { json: true, jar: jar }, (err, response, body) => { assert.ifError(err); assert.equal(response.statusCode, 200); assert.equal(body.roomId, roomId); @@ -820,8 +820,8 @@ describe('Messaging Library', function () { }); }); - it('should redirect to chats page', function (done) { - request(`${nconf.get('url')}/api/chats`, { jar: jar, json: true }, function (err, res, body) { + it('should redirect to chats page', (done) => { + request(`${nconf.get('url')}/api/chats`, { jar: jar, json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert.equal(res.headers['x-redirect'], '/user/herp/chats'); @@ -830,10 +830,10 @@ describe('Messaging Library', function () { }); }); - it('should return 404 if user is not in room', function (done) { - helpers.loginUser('baz', 'quuxquux', function (err, jar) { + it('should return 404 if user is not in room', (done) => { + helpers.loginUser('baz', 'quuxquux', (err, jar) => { assert.ifError(err); - request(`${nconf.get('url')}/api/user/baz/chats/${roomId}`, { json: true, jar: jar }, function (err, response) { + request(`${nconf.get('url')}/api/user/baz/chats/${roomId}`, { json: true, jar: jar }, (err, response) => { assert.ifError(err); assert.equal(response.statusCode, 404); done(); diff --git a/test/meta.js b/test/meta.js index 1818f866da..82f1e60988 100644 --- a/test/meta.js +++ b/test/meta.js @@ -10,19 +10,19 @@ var meta = require('../src/meta'); var User = require('../src/user'); var Groups = require('../src/groups'); -describe('meta', function () { +describe('meta', () => { var fooUid; var bazUid; var herpUid; - before(function (done) { + before((done) => { Groups.cache.reset(); // Create 3 users: 1 admin, 2 regular async.series([ async.apply(User.create, { username: 'foo', password: 'barbar' }), // admin async.apply(User.create, { username: 'baz', password: 'quuxquux' }), // restricted user async.apply(User.create, { username: 'herp', password: 'derpderp' }), // regular user - ], function (err, uids) { + ], (err, uids) => { if (err) { return done(err); } @@ -35,12 +35,12 @@ describe('meta', function () { }); }); - describe('settings', function () { + describe('settings', () => { var socketAdmin = require('../src/socket.io/admin'); - it('it should set setting', function (done) { - socketAdmin.settings.set({ uid: fooUid }, { hash: 'some:hash', values: { foo: '1', derp: 'value' } }, function (err) { + it('it should set setting', (done) => { + socketAdmin.settings.set({ uid: fooUid }, { hash: 'some:hash', values: { foo: '1', derp: 'value' } }, (err) => { assert.ifError(err); - db.getObject('settings:some:hash', function (err, data) { + db.getObject('settings:some:hash', (err, data) => { assert.ifError(err); assert.equal(data.foo, '1'); assert.equal(data.derp, 'value'); @@ -49,8 +49,8 @@ describe('meta', function () { }); }); - it('it should get setting', function (done) { - socketAdmin.settings.get({ uid: fooUid }, { hash: 'some:hash' }, function (err, data) { + it('it should get setting', (done) => { + socketAdmin.settings.get({ uid: fooUid }, { hash: 'some:hash' }, (err, data) => { assert.ifError(err); assert.equal(data.foo, '1'); assert.equal(data.derp, 'value'); @@ -58,10 +58,10 @@ describe('meta', function () { }); }); - it('should not set setting if not empty', function (done) { - meta.settings.setOnEmpty('some:hash', { foo: 2 }, function (err) { + it('should not set setting if not empty', (done) => { + meta.settings.setOnEmpty('some:hash', { foo: 2 }, (err) => { assert.ifError(err); - db.getObject('settings:some:hash', function (err, data) { + db.getObject('settings:some:hash', (err, data) => { assert.ifError(err); assert.equal(data.foo, '1'); assert.equal(data.derp, 'value'); @@ -70,10 +70,10 @@ describe('meta', function () { }); }); - it('should set setting if empty', function (done) { - meta.settings.setOnEmpty('some:hash', { empty: '2' }, function (err) { + it('should set setting if empty', (done) => { + meta.settings.setOnEmpty('some:hash', { empty: '2' }, (err) => { assert.ifError(err); - db.getObject('settings:some:hash', function (err, data) { + db.getObject('settings:some:hash', (err, data) => { assert.ifError(err); assert.equal(data.foo, '1'); assert.equal(data.derp, 'value'); @@ -83,10 +83,10 @@ describe('meta', function () { }); }); - it('should set one and get one', function (done) { - meta.settings.setOne('some:hash', 'myField', 'myValue', function (err) { + it('should set one and get one', (done) => { + meta.settings.setOne('some:hash', 'myField', 'myValue', (err) => { assert.ifError(err); - meta.settings.getOne('some:hash', 'myField', function (err, myValue) { + meta.settings.getOne('some:hash', 'myField', (err, myValue) => { assert.ifError(err); assert.equal(myValue, 'myValue'); done(); @@ -94,7 +94,7 @@ describe('meta', function () { }); }); - it('should return null if setting field does not exist', async function () { + it('should return null if setting field does not exist', async () => { const val = await meta.settings.getOne('some:hash', 'does not exist'); assert.strictEqual(val, null); }); @@ -105,13 +105,13 @@ describe('meta', function () { ]; const anotherList = []; - it('should set setting with sorted list', function (done) { - socketAdmin.settings.set({ uid: fooUid }, { hash: 'another:hash', values: { foo: '1', derp: 'value', someList: someList, anotherList: anotherList } }, function (err) { + it('should set setting with sorted list', (done) => { + socketAdmin.settings.set({ uid: fooUid }, { hash: 'another:hash', values: { foo: '1', derp: 'value', someList: someList, anotherList: anotherList } }, (err) => { if (err) { return done(err); } - db.getObject('settings:another:hash', function (err, data) { + db.getObject('settings:another:hash', (err, data) => { if (err) { return done(err); } @@ -125,8 +125,8 @@ describe('meta', function () { }); }); - it('should get setting with sorted list', function (done) { - socketAdmin.settings.get({ uid: fooUid }, { hash: 'another:hash' }, function (err, data) { + it('should get setting with sorted list', (done) => { + socketAdmin.settings.get({ uid: fooUid }, { hash: 'another:hash' }, (err, data) => { assert.ifError(err); assert.strictEqual(data.foo, '1'); assert.strictEqual(data.derp, 'value'); @@ -136,10 +136,10 @@ describe('meta', function () { }); }); - it('should not set setting if not empty', function (done) { - meta.settings.setOnEmpty('some:hash', { foo: 2 }, function (err) { + it('should not set setting if not empty', (done) => { + meta.settings.setOnEmpty('some:hash', { foo: 2 }, (err) => { assert.ifError(err); - db.getObject('settings:some:hash', function (err, data) { + db.getObject('settings:some:hash', (err, data) => { assert.ifError(err); assert.equal(data.foo, '1'); assert.equal(data.derp, 'value'); @@ -148,10 +148,10 @@ describe('meta', function () { }); }); - it('should not set setting with sorted list if not empty', function (done) { - meta.settings.setOnEmpty('another:hash', { foo: anotherList }, function (err) { + it('should not set setting with sorted list if not empty', (done) => { + meta.settings.setOnEmpty('another:hash', { foo: anotherList }, (err) => { assert.ifError(err); - socketAdmin.settings.get({ uid: fooUid }, { hash: 'another:hash' }, function (err, data) { + socketAdmin.settings.get({ uid: fooUid }, { hash: 'another:hash' }, (err, data) => { assert.ifError(err); assert.equal(data.foo, '1'); assert.equal(data.derp, 'value'); @@ -160,10 +160,10 @@ describe('meta', function () { }); }); - it('should set setting with sorted list if empty', function (done) { - meta.settings.setOnEmpty('another:hash', { empty: someList }, function (err) { + it('should set setting with sorted list if empty', (done) => { + meta.settings.setOnEmpty('another:hash', { empty: someList }, (err) => { assert.ifError(err); - socketAdmin.settings.get({ uid: fooUid }, { hash: 'another:hash' }, function (err, data) { + socketAdmin.settings.get({ uid: fooUid }, { hash: 'another:hash' }, (err, data) => { assert.ifError(err); assert.equal(data.foo, '1'); assert.equal(data.derp, 'value'); @@ -173,10 +173,10 @@ describe('meta', function () { }); }); - it('should set one and get one sorted list', function (done) { - meta.settings.setOne('another:hash', 'someList', someList, function (err) { + it('should set one and get one sorted list', (done) => { + meta.settings.setOne('another:hash', 'someList', someList, (err) => { assert.ifError(err); - meta.settings.getOne('another:hash', 'someList', function (err, _someList) { + meta.settings.getOne('another:hash', 'someList', (err, _someList) => { assert.ifError(err); assert.deepEqual(_someList, someList); done(); @@ -186,14 +186,14 @@ describe('meta', function () { }); - describe('config', function () { + describe('config', () => { var socketAdmin = require('../src/socket.io/admin'); - before(function (done) { + before((done) => { db.setObject('config', { minimumTagLength: 3, maximumTagLength: 15 }, done); }); - it('should get config fields', function (done) { - meta.configs.getFields(['minimumTagLength', 'maximumTagLength'], function (err, data) { + it('should get config fields', (done) => { + meta.configs.getFields(['minimumTagLength', 'maximumTagLength'], (err, data) => { assert.ifError(err); assert.strictEqual(data.minimumTagLength, 3); assert.strictEqual(data.maximumTagLength, 15); @@ -201,10 +201,10 @@ describe('meta', function () { }); }); - it('should get the correct type and default value', function (done) { - meta.configs.set('loginAttempts', '', function (err) { + it('should get the correct type and default value', (done) => { + meta.configs.set('loginAttempts', '', (err) => { assert.ifError(err); - meta.configs.get('loginAttempts', function (err, value) { + meta.configs.get('loginAttempts', (err, value) => { assert.ifError(err); assert.strictEqual(value, 5); done(); @@ -212,10 +212,10 @@ describe('meta', function () { }); }); - it('should get the correct type and correct value', function (done) { - meta.configs.set('loginAttempts', '0', function (err) { + it('should get the correct type and correct value', (done) => { + meta.configs.set('loginAttempts', '0', (err) => { assert.ifError(err); - meta.configs.get('loginAttempts', function (err, value) { + meta.configs.get('loginAttempts', (err, value) => { assert.ifError(err); assert.strictEqual(value, 0); done(); @@ -223,10 +223,10 @@ describe('meta', function () { }); }); - it('should get the correct value', function (done) { - meta.configs.set('title', 123, function (err) { + it('should get the correct value', (done) => { + meta.configs.set('title', 123, (err) => { assert.ifError(err); - meta.configs.get('title', function (err, value) { + meta.configs.get('title', (err, value) => { assert.ifError(err); assert.strictEqual(value, '123'); done(); @@ -234,10 +234,10 @@ describe('meta', function () { }); }); - it('should get the correct value', function (done) { - meta.configs.set('title', 0, function (err) { + it('should get the correct value', (done) => { + meta.configs.set('title', 0, (err) => { assert.ifError(err); - meta.configs.get('title', function (err, value) { + meta.configs.get('title', (err, value) => { assert.ifError(err); assert.strictEqual(value, '0'); done(); @@ -245,10 +245,10 @@ describe('meta', function () { }); }); - it('should get the correct value', function (done) { - meta.configs.set('title', '', function (err) { + it('should get the correct value', (done) => { + meta.configs.set('title', '', (err) => { assert.ifError(err); - meta.configs.get('title', function (err, value) { + meta.configs.get('title', (err, value) => { assert.ifError(err); assert.strictEqual(value, ''); done(); @@ -256,10 +256,10 @@ describe('meta', function () { }); }); - it('should use default value if value is null', function (done) { - meta.configs.set('teaserPost', null, function (err) { + it('should use default value if value is null', (done) => { + meta.configs.set('teaserPost', null, (err) => { assert.ifError(err); - meta.configs.get('teaserPost', function (err, value) { + meta.configs.get('teaserPost', (err, value) => { assert.ifError(err); assert.strictEqual(value, 'last-reply'); done(); @@ -267,24 +267,24 @@ describe('meta', function () { }); }); - it('should fail if field is invalid', function (done) { - meta.configs.set('', 'someValue', function (err) { + it('should fail if field is invalid', (done) => { + meta.configs.set('', 'someValue', (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); }); - it('should fail if data is invalid', function (done) { - socketAdmin.config.set({ uid: fooUid }, null, function (err) { + it('should fail if data is invalid', (done) => { + socketAdmin.config.set({ uid: fooUid }, null, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); }); - it('should set multiple config values', function (done) { - socketAdmin.config.set({ uid: fooUid }, { key: 'someKey', value: 'someValue' }, function (err) { + it('should set multiple config values', (done) => { + socketAdmin.config.set({ uid: fooUid }, { key: 'someKey', value: 'someValue' }, (err) => { assert.ifError(err); - meta.configs.getFields(['someKey'], function (err, data) { + meta.configs.getFields(['someKey'], (err, data) => { assert.ifError(err); assert.equal(data.someKey, 'someValue'); done(); @@ -292,10 +292,10 @@ describe('meta', function () { }); }); - it('should set config value', function (done) { - meta.configs.set('someField', 'someValue', function (err) { + it('should set config value', (done) => { + meta.configs.set('someField', 'someValue', (err) => { assert.ifError(err); - meta.configs.getFields(['someField'], function (err, data) { + meta.configs.getFields(['someField'], (err, data) => { assert.ifError(err); assert.strictEqual(data.someField, 'someValue'); done(); @@ -303,10 +303,10 @@ describe('meta', function () { }); }); - it('should get back string if field is not in defaults', function (done) { - meta.configs.set('numericField', 123, function (err) { + it('should get back string if field is not in defaults', (done) => { + meta.configs.set('numericField', 123, (err) => { assert.ifError(err); - meta.configs.getFields(['numericField'], function (err, data) { + meta.configs.getFields(['numericField'], (err, data) => { assert.ifError(err); assert.strictEqual(data.numericField, 123); done(); @@ -314,10 +314,10 @@ describe('meta', function () { }); }); - it('should set boolean config value', function (done) { - meta.configs.set('booleanField', true, function (err) { + it('should set boolean config value', (done) => { + meta.configs.set('booleanField', true, (err) => { assert.ifError(err); - meta.configs.getFields(['booleanField'], function (err, data) { + meta.configs.getFields(['booleanField'], (err, data) => { assert.ifError(err); assert.strictEqual(data.booleanField, true); done(); @@ -325,10 +325,10 @@ describe('meta', function () { }); }); - it('should set boolean config value', function (done) { - meta.configs.set('booleanField', 'false', function (err) { + it('should set boolean config value', (done) => { + meta.configs.set('booleanField', 'false', (err) => { assert.ifError(err); - meta.configs.getFields(['booleanField'], function (err, data) { + meta.configs.getFields(['booleanField'], (err, data) => { assert.ifError(err); assert.strictEqual(data.booleanField, false); done(); @@ -336,10 +336,10 @@ describe('meta', function () { }); }); - it('should set string config value', function (done) { - meta.configs.set('stringField', '123', function (err) { + it('should set string config value', (done) => { + meta.configs.set('stringField', '123', (err) => { assert.ifError(err); - meta.configs.getFields(['stringField'], function (err, data) { + meta.configs.getFields(['stringField'], (err, data) => { assert.ifError(err); assert.strictEqual(data.stringField, 123); done(); @@ -347,21 +347,21 @@ describe('meta', function () { }); }); - it('should fail if data is invalid', function (done) { - socketAdmin.config.setMultiple({ uid: fooUid }, null, function (err) { + it('should fail if data is invalid', (done) => { + socketAdmin.config.setMultiple({ uid: fooUid }, null, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); }); - it('should set multiple values', function (done) { + it('should set multiple values', (done) => { socketAdmin.config.setMultiple({ uid: fooUid }, { someField1: 'someValue1', someField2: 'someValue2', customCSS: '.derp{color:#00ff00;}', - }, function (err) { + }, (err) => { assert.ifError(err); - meta.configs.getFields(['someField1', 'someField2'], function (err, data) { + meta.configs.getFields(['someField1', 'someField2'], (err, data) => { assert.ifError(err); assert.equal(data.someField1, 'someValue1'); assert.equal(data.someField2, 'someValue2'); @@ -370,10 +370,10 @@ describe('meta', function () { }); }); - it('should not set config if not empty', function (done) { - meta.configs.setOnEmpty({ someField1: 'foo' }, function (err) { + it('should not set config if not empty', (done) => { + meta.configs.setOnEmpty({ someField1: 'foo' }, (err) => { assert.ifError(err); - meta.configs.get('someField1', function (err, value) { + meta.configs.get('someField1', (err, value) => { assert.ifError(err); assert.equal(value, 'someValue1'); done(); @@ -381,10 +381,10 @@ describe('meta', function () { }); }); - it('should remove config field', function (done) { - socketAdmin.config.remove({ uid: fooUid }, 'someField1', function (err) { + it('should remove config field', (done) => { + socketAdmin.config.remove({ uid: fooUid }, 'someField1', (err) => { assert.ifError(err); - db.isObjectField('config', 'someField1', function (err, isObjectField) { + db.isObjectField('config', 'someField1', (err, isObjectField) => { assert.ifError(err); assert(!isObjectField); done(); @@ -394,83 +394,83 @@ describe('meta', function () { }); - describe('session TTL', function () { - it('should return 14 days in seconds', function (done) { + describe('session TTL', () => { + it('should return 14 days in seconds', (done) => { assert(meta.getSessionTTLSeconds(), 1209600); done(); }); - it('should return 7 days in seconds', function (done) { + it('should return 7 days in seconds', (done) => { meta.config.loginDays = 7; assert(meta.getSessionTTLSeconds(), 604800); done(); }); - it('should return 2 days in seconds', function (done) { + it('should return 2 days in seconds', (done) => { meta.config.loginSeconds = 172800; assert(meta.getSessionTTLSeconds(), 172800); done(); }); }); - describe('dependencies', function () { - it('should return ENOENT if module is not found', function (done) { - meta.dependencies.checkModule('some-module-that-does-not-exist', function (err) { + describe('dependencies', () => { + it('should return ENOENT if module is not found', (done) => { + meta.dependencies.checkModule('some-module-that-does-not-exist', (err) => { assert.equal(err.code, 'ENOENT'); done(); }); }); - it('should not error if module is a nodebb-plugin-*', function (done) { - meta.dependencies.checkModule('nodebb-plugin-somePlugin', function (err) { + it('should not error if module is a nodebb-plugin-*', (done) => { + meta.dependencies.checkModule('nodebb-plugin-somePlugin', (err) => { assert.ifError(err); done(); }); }); - it('should not error if module is nodebb-theme-*', function (done) { - meta.dependencies.checkModule('nodebb-theme-someTheme', function (err) { + it('should not error if module is nodebb-theme-*', (done) => { + meta.dependencies.checkModule('nodebb-theme-someTheme', (err) => { assert.ifError(err); done(); }); }); - it('should parse json package data', function (done) { + it('should parse json package data', (done) => { var pkgData = meta.dependencies.parseModuleData('nodebb-plugin-test', '{"a": 1}'); assert.equal(pkgData.a, 1); done(); }); - it('should return null data with invalid json', function (done) { + it('should return null data with invalid json', (done) => { var pkgData = meta.dependencies.parseModuleData('nodebb-plugin-test', 'asdasd'); assert.strictEqual(pkgData, null); done(); }); - it('should return false if moduleData is falsy', function (done) { + it('should return false if moduleData is falsy', (done) => { assert(!meta.dependencies.doesSatisfy(null, '1.0.0')); done(); }); - it('should return false if moduleData doesnt not satisfy package.json', function (done) { + it('should return false if moduleData doesnt not satisfy package.json', (done) => { assert(!meta.dependencies.doesSatisfy({ name: 'nodebb-plugin-test', version: '0.9.0' }, '1.0.0')); done(); }); - it('should return true if _resolved is from github', function (done) { + it('should return true if _resolved is from github', (done) => { assert(meta.dependencies.doesSatisfy({ name: 'nodebb-plugin-test', _resolved: 'https://github.com/some/repo', version: '0.9.0' }, '1.0.0')); done(); }); }); - describe('debugFork', function () { + describe('debugFork', () => { var oldArgv; - before(function () { + before(() => { oldArgv = process.execArgv; process.execArgv = ['--debug=5858', '--foo=1']; }); - it('should detect debugging', function (done) { + it('should detect debugging', (done) => { var debugFork = require('../src/meta/debugFork'); assert(!debugFork.debugging); @@ -483,26 +483,26 @@ describe('meta', function () { done(); }); - after(function () { + after(() => { process.execArgv = oldArgv; }); }); - describe('Access-Control-Allow-Origin', function () { - it('Access-Control-Allow-Origin header should be empty', function (done) { + describe('Access-Control-Allow-Origin', () => { + it('Access-Control-Allow-Origin header should be empty', (done) => { var jar = request.jar(); request.get(`${nconf.get('url')}/api/search?term=bug`, { form: {}, json: true, jar: jar, - }, function (err, response, body) { + }, (err, response, body) => { assert.ifError(err); assert.equal(response.headers['access-control-allow-origin'], undefined); done(); }); }); - it('should set proper Access-Control-Allow-Origin header', function (done) { + it('should set proper Access-Control-Allow-Origin header', (done) => { var jar = request.jar(); var oldValue = meta.config['access-control-allow-origin']; meta.config['access-control-allow-origin'] = 'test.com, mydomain.com'; @@ -514,7 +514,7 @@ describe('meta', function () { headers: { origin: 'mydomain.com', }, - }, function (err, response, body) { + }, (err, response, body) => { assert.ifError(err); assert.equal(response.headers['access-control-allow-origin'], 'mydomain.com'); meta.config['access-control-allow-origin'] = oldValue; @@ -522,7 +522,7 @@ describe('meta', function () { }); }); - it('Access-Control-Allow-Origin header should be empty if origin does not match', function (done) { + it('Access-Control-Allow-Origin header should be empty if origin does not match', (done) => { var jar = request.jar(); var oldValue = meta.config['access-control-allow-origin']; meta.config['access-control-allow-origin'] = 'test.com, mydomain.com'; @@ -534,7 +534,7 @@ describe('meta', function () { headers: { origin: 'notallowed.com', }, - }, function (err, response, body) { + }, (err, response, body) => { assert.ifError(err); assert.equal(response.headers['access-control-allow-origin'], undefined); meta.config['access-control-allow-origin'] = oldValue; @@ -542,7 +542,7 @@ describe('meta', function () { }); }); - it('should set proper Access-Control-Allow-Origin header', function (done) { + it('should set proper Access-Control-Allow-Origin header', (done) => { var jar = request.jar(); var oldValue = meta.config['access-control-allow-origin-regex']; meta.config['access-control-allow-origin-regex'] = 'match\\.this\\..+\\.domain.com, mydomain\\.com'; @@ -554,7 +554,7 @@ describe('meta', function () { headers: { origin: 'match.this.anything123.domain.com', }, - }, function (err, response, body) { + }, (err, response, body) => { assert.ifError(err); assert.equal(response.headers['access-control-allow-origin'], 'match.this.anything123.domain.com'); meta.config['access-control-allow-origin-regex'] = oldValue; @@ -562,7 +562,7 @@ describe('meta', function () { }); }); - it('Access-Control-Allow-Origin header should be empty if origin does not match', function (done) { + it('Access-Control-Allow-Origin header should be empty if origin does not match', (done) => { var jar = request.jar(); var oldValue = meta.config['access-control-allow-origin-regex']; meta.config['access-control-allow-origin-regex'] = 'match\\.this\\..+\\.domain.com, mydomain\\.com'; @@ -574,7 +574,7 @@ describe('meta', function () { headers: { origin: 'notallowed.com', }, - }, function (err, response, body) { + }, (err, response, body) => { assert.ifError(err); assert.equal(response.headers['access-control-allow-origin'], undefined); meta.config['access-control-allow-origin-regex'] = oldValue; @@ -582,7 +582,7 @@ describe('meta', function () { }); }); - it('should not error with invalid regexp', function (done) { + it('should not error with invalid regexp', (done) => { var jar = request.jar(); var oldValue = meta.config['access-control-allow-origin-regex']; meta.config['access-control-allow-origin-regex'] = '[match\\.this\\..+\\.domain.com, mydomain\\.com'; @@ -594,7 +594,7 @@ describe('meta', function () { headers: { origin: 'mydomain.com', }, - }, function (err, response, body) { + }, (err, response, body) => { assert.ifError(err); assert.equal(response.headers['access-control-allow-origin'], 'mydomain.com'); meta.config['access-control-allow-origin-regex'] = oldValue; diff --git a/test/mocks/databasemock.js b/test/mocks/databasemock.js index 841cd75000..0b001996b5 100644 --- a/test/mocks/databasemock.js +++ b/test/mocks/databasemock.js @@ -161,9 +161,9 @@ before(async function () { await webserver.listen(); // Iterate over all of the test suites/contexts - this.test.parent.suites.forEach(function (suite) { + this.test.parent.suites.forEach((suite) => { // Attach an afterAll listener that resets the defaults - suite.afterAll(async function () { + suite.afterAll(async () => { await setupMockDefaults(); }); }); diff --git a/test/notifications.js b/test/notifications.js index 292db1ee01..c595eeff7c 100644 --- a/test/notifications.js +++ b/test/notifications.js @@ -14,12 +14,12 @@ var groups = require('../src/groups'); var notifications = require('../src/notifications'); var socketNotifications = require('../src/socket.io/notifications'); -describe('Notifications', function () { +describe('Notifications', () => { var uid; var notification; - before(function (done) { - user.create({ username: 'poster' }, function (err, _uid) { + before((done) => { + user.create({ username: 'poster' }, (err, _uid) => { if (err) { return done(err); } @@ -29,27 +29,27 @@ describe('Notifications', function () { }); }); - it('should fail to create notification without a nid', function (done) { - notifications.create({}, function (err) { + it('should fail to create notification without a nid', (done) => { + notifications.create({}, (err) => { assert.equal(err.message, '[[error:no-notification-id]]'); done(); }); }); - it('should create a notification', function (done) { + it('should create a notification', (done) => { notifications.create({ bodyShort: 'bodyShort', nid: 'notification_id', path: '/notification/path', pid: 1, - }, function (err, _notification) { + }, (err, _notification) => { notification = _notification; assert.ifError(err); assert(notification); - db.exists(`notifications:${notification.nid}`, function (err, exists) { + db.exists(`notifications:${notification.nid}`, (err, exists) => { assert.ifError(err); assert(exists); - db.isSortedSetMember('notifications', notification.nid, function (err, isMember) { + db.isSortedSetMember('notifications', notification.nid, (err, isMember) => { assert.ifError(err); assert(isMember); done(); @@ -58,22 +58,22 @@ describe('Notifications', function () { }); }); - it('should return null if pid is same and importance is lower', function (done) { + it('should return null if pid is same and importance is lower', (done) => { notifications.create({ bodyShort: 'bodyShort', nid: 'notification_id', path: '/notification/path', pid: 1, importance: 1, - }, function (err, notification) { + }, (err, notification) => { assert.ifError(err); assert.strictEqual(notification, null); done(); }); }); - it('should get empty array', function (done) { - notifications.getMultiple(null, function (err, data) { + it('should get empty array', (done) => { + notifications.getMultiple(null, (err, data) => { assert.ifError(err); assert(Array.isArray(data)); assert.equal(data.length, 0); @@ -81,8 +81,8 @@ describe('Notifications', function () { }); }); - it('should get notifications', function (done) { - notifications.getMultiple([notification.nid], function (err, notificationsData) { + it('should get notifications', (done) => { + notifications.getMultiple([notification.nid], (err, notificationsData) => { assert.ifError(err); assert(Array.isArray(notificationsData)); assert(notificationsData[0]); @@ -91,12 +91,12 @@ describe('Notifications', function () { }); }); - it('should do nothing', function (done) { - notifications.push(null, [], function (err) { + it('should do nothing', (done) => { + notifications.push(null, [], (err) => { assert.ifError(err); - notifications.push({ nid: null }, [], function (err) { + notifications.push({ nid: null }, [], (err) => { assert.ifError(err); - notifications.push(notification, [], function (err) { + notifications.push(notification, [], (err) => { assert.ifError(err); done(); }); @@ -104,11 +104,11 @@ describe('Notifications', function () { }); }); - it('should push a notification to uid', function (done) { - notifications.push(notification, [uid], function (err) { + it('should push a notification to uid', (done) => { + notifications.push(notification, [uid], (err) => { assert.ifError(err); - setTimeout(function () { - db.isSortedSetMember(`uid:${uid}:notifications:unread`, notification.nid, function (err, isMember) { + setTimeout(() => { + db.isSortedSetMember(`uid:${uid}:notifications:unread`, notification.nid, (err, isMember) => { assert.ifError(err); assert(isMember); done(); @@ -117,11 +117,11 @@ describe('Notifications', function () { }); }); - it('should push a notification to a group', function (done) { - notifications.pushGroup(notification, 'registered-users', function (err) { + it('should push a notification to a group', (done) => { + notifications.pushGroup(notification, 'registered-users', (err) => { assert.ifError(err); - setTimeout(function () { - db.isSortedSetMember(`uid:${uid}:notifications:unread`, notification.nid, function (err, isMember) { + setTimeout(() => { + db.isSortedSetMember(`uid:${uid}:notifications:unread`, notification.nid, (err, isMember) => { assert.ifError(err); assert(isMember); done(); @@ -130,11 +130,11 @@ describe('Notifications', function () { }); }); - it('should push a notification to groups', function (done) { - notifications.pushGroups(notification, ['registered-users', 'administrators'], function (err) { + it('should push a notification to groups', (done) => { + notifications.pushGroups(notification, ['registered-users', 'administrators'], (err) => { assert.ifError(err); - setTimeout(function () { - db.isSortedSetMember(`uid:${uid}:notifications:unread`, notification.nid, function (err, isMember) { + setTimeout(() => { + db.isSortedSetMember(`uid:${uid}:notifications:unread`, notification.nid, (err, isMember) => { assert.ifError(err); assert(isMember); done(); @@ -143,23 +143,23 @@ describe('Notifications', function () { }); }); - it('should not mark anything with invalid uid or nid', function (done) { - socketNotifications.markRead({ uid: null }, null, function (err) { + it('should not mark anything with invalid uid or nid', (done) => { + socketNotifications.markRead({ uid: null }, null, (err) => { assert.ifError(err); - socketNotifications.markRead({ uid: uid }, null, function (err) { + socketNotifications.markRead({ uid: uid }, null, (err) => { assert.ifError(err); done(); }); }); }); - it('should mark a notification read', function (done) { - socketNotifications.markRead({ uid: uid }, notification.nid, function (err) { + it('should mark a notification read', (done) => { + socketNotifications.markRead({ uid: uid }, notification.nid, (err) => { assert.ifError(err); - db.isSortedSetMember(`uid:${uid}:notifications:unread`, notification.nid, function (err, isMember) { + db.isSortedSetMember(`uid:${uid}:notifications:unread`, notification.nid, (err, isMember) => { assert.ifError(err); assert.equal(isMember, false); - db.isSortedSetMember(`uid:${uid}:notifications:read`, notification.nid, function (err, isMember) { + db.isSortedSetMember(`uid:${uid}:notifications:read`, notification.nid, (err, isMember) => { assert.ifError(err); assert.equal(isMember, true); done(); @@ -168,33 +168,33 @@ describe('Notifications', function () { }); }); - it('should not mark anything with invalid uid or nid', function (done) { - socketNotifications.markUnread({ uid: null }, null, function (err) { + it('should not mark anything with invalid uid or nid', (done) => { + socketNotifications.markUnread({ uid: null }, null, (err) => { assert.ifError(err); - socketNotifications.markUnread({ uid: uid }, null, function (err) { + socketNotifications.markUnread({ uid: uid }, null, (err) => { assert.ifError(err); done(); }); }); }); - it('should error if notification does not exist', function (done) { - socketNotifications.markUnread({ uid: uid }, 123123, function (err) { + it('should error if notification does not exist', (done) => { + socketNotifications.markUnread({ uid: uid }, 123123, (err) => { assert.equal(err.message, '[[error:no-notification]]'); done(); }); }); - it('should mark a notification unread', function (done) { - socketNotifications.markUnread({ uid: uid }, notification.nid, function (err) { + it('should mark a notification unread', (done) => { + socketNotifications.markUnread({ uid: uid }, notification.nid, (err) => { assert.ifError(err); - db.isSortedSetMember(`uid:${uid}:notifications:unread`, notification.nid, function (err, isMember) { + db.isSortedSetMember(`uid:${uid}:notifications:unread`, notification.nid, (err, isMember) => { assert.ifError(err); assert.equal(isMember, true); - db.isSortedSetMember(`uid:${uid}:notifications:read`, notification.nid, function (err, isMember) { + db.isSortedSetMember(`uid:${uid}:notifications:read`, notification.nid, (err, isMember) => { assert.ifError(err); assert.equal(isMember, false); - socketNotifications.getCount({ uid: uid }, null, function (err, count) { + socketNotifications.getCount({ uid: uid }, null, (err, count) => { assert.ifError(err); assert.equal(count, 1); done(); @@ -204,13 +204,13 @@ describe('Notifications', function () { }); }); - it('should mark all notifications read', function (done) { - socketNotifications.markAllRead({ uid: uid }, null, function (err) { + it('should mark all notifications read', (done) => { + socketNotifications.markAllRead({ uid: uid }, null, (err) => { assert.ifError(err); - db.isSortedSetMember(`uid:${uid}:notifications:unread`, notification.nid, function (err, isMember) { + db.isSortedSetMember(`uid:${uid}:notifications:unread`, notification.nid, (err, isMember) => { assert.ifError(err); assert.equal(isMember, false); - db.isSortedSetMember(`uid:${uid}:notifications:read`, notification.nid, function (err, isMember) { + db.isSortedSetMember(`uid:${uid}:notifications:read`, notification.nid, (err, isMember) => { assert.ifError(err); assert.equal(isMember, true); done(); @@ -219,14 +219,14 @@ describe('Notifications', function () { }); }); - it('should not do anything', function (done) { - socketNotifications.markAllRead({ uid: 1000 }, null, function (err) { + it('should not do anything', (done) => { + socketNotifications.markAllRead({ uid: 1000 }, null, (err) => { assert.ifError(err); done(); }); }); - it('should link to the first unread post in a watched topic', function (done) { + it('should link to the first unread post in a watched topic', (done) => { var categories = require('../src/categories'); var topics = require('../src/topics'); var watcherUid; @@ -289,14 +289,14 @@ describe('Notifications', function () { assert.equal(`${nconf.get('relative_path')}/post/${pid}`, notifications.unread[0].path, 'the notification should link to the first unread post'); next(); }, - ], function (err) { + ], (err) => { assert.ifError(err); done(); }); }); - it('should get notification by nid', function (done) { - socketNotifications.get({ uid: uid }, { nids: [notification.nid] }, function (err, data) { + it('should get notification by nid', (done) => { + socketNotifications.get({ uid: uid }, { nids: [notification.nid] }, (err, data) => { assert.ifError(err); assert.equal(data[0].bodyShort, 'bodyShort'); assert.equal(data[0].nid, 'notification_id'); @@ -305,8 +305,8 @@ describe('Notifications', function () { }); }); - it('should get user\'s notifications', function (done) { - socketNotifications.get({ uid: uid }, {}, function (err, data) { + it('should get user\'s notifications', (done) => { + socketNotifications.get({ uid: uid }, {}, (err, data) => { assert.ifError(err); assert.equal(data.unread.length, 0); assert.equal(data.read[0].nid, 'notification_id'); @@ -314,17 +314,17 @@ describe('Notifications', function () { }); }); - it('should error if not logged in', function (done) { - socketNotifications.deleteAll({ uid: 0 }, null, function (err) { + it('should error if not logged in', (done) => { + socketNotifications.deleteAll({ uid: 0 }, null, (err) => { assert.equal(err.message, '[[error:no-privileges]]'); done(); }); }); - it('should delete all user notifications', function (done) { - socketNotifications.deleteAll({ uid: uid }, null, function (err) { + it('should delete all user notifications', (done) => { + socketNotifications.deleteAll({ uid: uid }, null, (err) => { assert.ifError(err); - socketNotifications.get({ uid: uid }, {}, function (err, data) { + socketNotifications.get({ uid: uid }, {}, (err, data) => { assert.ifError(err); assert.equal(data.unread.length, 0); assert.equal(data.read.length, 0); @@ -333,8 +333,8 @@ describe('Notifications', function () { }); }); - it('should return empty with falsy uid', function (done) { - user.notifications.get(0, function (err, data) { + it('should return empty with falsy uid', (done) => { + user.notifications.get(0, (err, data) => { assert.ifError(err); assert.equal(data.read.length, 0); assert.equal(data.unread.length, 0); @@ -342,19 +342,19 @@ describe('Notifications', function () { }); }); - it('should get all notifications and filter', function (done) { + it('should get all notifications and filter', (done) => { var nid = 'willbefiltered'; notifications.create({ bodyShort: 'bodyShort', nid: nid, path: '/notification/path', type: 'post', - }, function (err, notification) { + }, (err, notification) => { assert.ifError(err); - notifications.push(notification, [uid], function (err) { + notifications.push(notification, [uid], (err) => { assert.ifError(err); - setTimeout(function () { - user.notifications.getAll(uid, 'post', function (err, nids) { + setTimeout(() => { + user.notifications.getAll(uid, 'post', (err, nids) => { assert.ifError(err); assert(nids.includes(nid)); done(); @@ -364,46 +364,46 @@ describe('Notifications', function () { }); }); - it('should not get anything if notifications does not exist', function (done) { - user.notifications.getNotifications(['doesnotexistnid1', 'doesnotexistnid2'], uid, function (err, data) { + it('should not get anything if notifications does not exist', (done) => { + user.notifications.getNotifications(['doesnotexistnid1', 'doesnotexistnid2'], uid, (err, data) => { assert.ifError(err); assert.deepEqual(data, []); done(); }); }); - it('should get daily notifications', function (done) { - user.notifications.getDailyUnread(uid, function (err, data) { + it('should get daily notifications', (done) => { + user.notifications.getDailyUnread(uid, (err, data) => { assert.ifError(err); assert.equal(data[0].nid, 'willbefiltered'); done(); }); }); - it('should return empty array for invalid interval', function (done) { - user.notifications.getUnreadInterval(uid, '2 aeons', function (err, data) { + it('should return empty array for invalid interval', (done) => { + user.notifications.getUnreadInterval(uid, '2 aeons', (err, data) => { assert.ifError(err); assert.deepEqual(data, []); done(); }); }); - it('should return 0 for falsy uid', function (done) { - user.notifications.getUnreadCount(0, function (err, count) { + it('should return 0 for falsy uid', (done) => { + user.notifications.getUnreadCount(0, (err, count) => { assert.ifError(err); assert.equal(count, 0); done(); }); }); - it('should not do anything if uid is falsy', function (done) { - user.notifications.deleteAll(0, function (err) { + it('should not do anything if uid is falsy', (done) => { + user.notifications.deleteAll(0, (err) => { assert.ifError(err); done(); }); }); - it('should send notification to followers of user when he posts', function (done) { + it('should send notification to followers of user when he posts', (done) => { var followerUid; async.waterfall([ function (next) { @@ -433,21 +433,21 @@ describe('Notifications', function () { function (next) { user.notifications.getAll(followerUid, '', next); }, - ], function (err, data) { + ], (err, data) => { assert.ifError(err); assert(data); done(); }); }); - it('should send welcome notification', function (done) { + it('should send welcome notification', (done) => { meta.config.welcomeNotification = 'welcome to the forums'; - user.notifications.sendWelcomeNotification(uid, function (err) { + user.notifications.sendWelcomeNotification(uid, (err) => { assert.ifError(err); - user.notifications.sendWelcomeNotification(uid, function (err) { + user.notifications.sendWelcomeNotification(uid, (err) => { assert.ifError(err); - setTimeout(function () { - user.notifications.getAll(uid, '', function (err, data) { + setTimeout(() => { + user.notifications.getAll(uid, '', (err, data) => { meta.config.welcomeNotification = ''; assert.ifError(err); assert(data.includes(`welcome_${uid}`), data); @@ -458,21 +458,21 @@ describe('Notifications', function () { }); }); - it('should prune notifications', function (done) { + it('should prune notifications', (done) => { notifications.create({ bodyShort: 'bodyShort', nid: 'tobedeleted', path: '/notification/path', - }, function (err, notification) { + }, (err, notification) => { assert.ifError(err); - notifications.prune(function (err) { + notifications.prune((err) => { assert.ifError(err); var week = 604800000; - db.sortedSetAdd('notifications', Date.now() - (2 * week), notification.nid, function (err) { + db.sortedSetAdd('notifications', Date.now() - (2 * week), notification.nid, (err) => { assert.ifError(err); - notifications.prune(function (err) { + notifications.prune((err) => { assert.ifError(err); - notifications.get(notification.nid, function (err, data) { + notifications.get(notification.nid, (err, data) => { assert.ifError(err); assert(!data); done(); diff --git a/test/package-install.js b/test/package-install.js index 6886cbc45d..da0d2f8a1f 100644 --- a/test/package-install.js +++ b/test/package-install.js @@ -7,8 +7,8 @@ const { readFileSync } = require('fs'); var assert = require('assert'); -describe('Package install', function () { - it('should remove non-`nodebb-` modules not specified in `install/package.json`', function () { +describe('Package install', () => { + it('should remove non-`nodebb-` modules not specified in `install/package.json`', () => { const packageFilePath = path.join(__dirname, '../package.json'); // install an extra package diff --git a/test/pagination.js b/test/pagination.js index 30f79a718e..2952748f62 100644 --- a/test/pagination.js +++ b/test/pagination.js @@ -4,8 +4,8 @@ var assert = require('assert'); var pagination = require('../src/pagination'); -describe('Pagination', function () { - it('should create empty pagination for 1 page', function (done) { +describe('Pagination', () => { + it('should create empty pagination for 1 page', (done) => { var data = pagination.create(1, 1); assert.equal(data.pages.length, 0); assert.equal(data.rel.length, 0); @@ -15,7 +15,7 @@ describe('Pagination', function () { done(); }); - it('should create pagination for 10 pages', function (done) { + it('should create pagination for 10 pages', (done) => { var data = pagination.create(2, 10); // [1, (2), 3, 4, 5, separator, 9, 10] assert.equal(data.pages.length, 8); @@ -26,7 +26,7 @@ describe('Pagination', function () { done(); }); - it('should create pagination for 3 pages with query params', function (done) { + it('should create pagination for 3 pages with query params', (done) => { var data = pagination.create(1, 3, { key: 'value' }); assert.equal(data.pages.length, 3); assert.equal(data.rel.length, 1); diff --git a/test/plugins-installed.js b/test/plugins-installed.js index 0401248f69..9b9ebc834d 100644 --- a/test/plugins-installed.js +++ b/test/plugins-installed.js @@ -7,7 +7,7 @@ const db = require('./mocks/databasemock'); const installedPlugins = fs.readdirSync(path.join(__dirname, '../node_modules')) .filter(p => p.startsWith('nodebb-')); -describe('Installed Plugins', function () { +describe('Installed Plugins', () => { installedPlugins.forEach((plugin) => { const pathToTests = path.join(__dirname, '../node_modules', plugin, 'test'); try { diff --git a/test/plugins.js b/test/plugins.js index 61e8c77652..9fed358e77 100644 --- a/test/plugins.js +++ b/test/plugins.js @@ -10,10 +10,10 @@ var fs = require('fs'); var db = require('./mocks/databasemock'); var plugins = require('../src/plugins'); -describe('Plugins', function () { - it('should load plugin data', function (done) { +describe('Plugins', () => { + it('should load plugin data', (done) => { var pluginId = 'nodebb-plugin-markdown'; - plugins.loadPlugin(path.join(nconf.get('base_dir'), `node_modules/${pluginId}`), function (err) { + plugins.loadPlugin(path.join(nconf.get('base_dir'), `node_modules/${pluginId}`), (err) => { assert.ifError(err); assert(plugins.libraries[pluginId]); assert(plugins.loadedHooks['static:app.load']); @@ -22,12 +22,12 @@ describe('Plugins', function () { }); }); - it('should return true if hook has listeners', function (done) { + it('should return true if hook has listeners', (done) => { assert(plugins.hooks.hasListeners('filter:parse.post')); done(); }); - it('should register and fire a filter hook', function (done) { + it('should register and fire a filter hook', (done) => { function filterMethod1(data, callback) { data.foo += 1; callback(null, data); @@ -40,20 +40,20 @@ describe('Plugins', function () { plugins.hooks.register('test-plugin', { hook: 'filter:test.hook', method: filterMethod1 }); plugins.hooks.register('test-plugin', { hook: 'filter:test.hook', method: filterMethod2 }); - plugins.hooks.fire('filter:test.hook', { foo: 1 }, function (err, data) { + plugins.hooks.fire('filter:test.hook', { foo: 1 }, (err, data) => { assert.ifError(err); assert.equal(data.foo, 7); done(); }); }); - it('should register and fire a filter hook having 2 methods, one returning a promise and the other calling the callback', function (done) { + it('should register and fire a filter hook having 2 methods, one returning a promise and the other calling the callback', (done) => { function method1(data, callback) { data.foo += 1; callback(null, data); } function method2(data) { - return new Promise(function (resolve) { + return new Promise((resolve) => { data.foo += 5; resolve(data); }); @@ -62,28 +62,28 @@ describe('Plugins', function () { plugins.hooks.register('test-plugin', { hook: 'filter:test.hook2', method: method1 }); plugins.hooks.register('test-plugin', { hook: 'filter:test.hook2', method: method2 }); - plugins.hooks.fire('filter:test.hook2', { foo: 1 }, function (err, data) { + plugins.hooks.fire('filter:test.hook2', { foo: 1 }, (err, data) => { assert.ifError(err); assert.equal(data.foo, 7); done(); }); }); - it('should register and fire a filter hook that returns a promise that gets rejected', function (done) { + it('should register and fire a filter hook that returns a promise that gets rejected', (done) => { function method(data) { - return new Promise(function (resolve, reject) { + return new Promise((resolve, reject) => { data.foo += 5; reject(new Error('nope')); }); } plugins.hooks.register('test-plugin', { hook: 'filter:test.hook3', method: method }); - plugins.hooks.fire('filter:test.hook3', { foo: 1 }, function (err) { + plugins.hooks.fire('filter:test.hook3', { foo: 1 }, (err) => { assert(err); done(); }); }); - it('should register and fire an action hook', function (done) { + it('should register and fire an action hook', (done) => { function actionMethod(data) { assert.equal(data.bar, 'test'); done(); @@ -93,20 +93,20 @@ describe('Plugins', function () { plugins.hooks.fire('action:test.hook', { bar: 'test' }); }); - it('should register and fire a static hook', function (done) { + it('should register and fire a static hook', (done) => { function actionMethod(data, callback) { assert.equal(data.bar, 'test'); callback(); } plugins.hooks.register('test-plugin', { hook: 'static:test.hook', method: actionMethod }); - plugins.hooks.fire('static:test.hook', { bar: 'test' }, function (err) { + plugins.hooks.fire('static:test.hook', { bar: 'test' }, (err) => { assert.ifError(err); done(); }); }); - it('should register and fire a static hook returning a promise', function (done) { + it('should register and fire a static hook returning a promise', (done) => { function method(data) { assert.equal(data.bar, 'test'); return new Promise((resolve) => { @@ -114,76 +114,74 @@ describe('Plugins', function () { }); } plugins.hooks.register('test-plugin', { hook: 'static:test.hook', method: method }); - plugins.hooks.fire('static:test.hook', { bar: 'test' }, function (err) { + plugins.hooks.fire('static:test.hook', { bar: 'test' }, (err) => { assert.ifError(err); done(); }); }); - it('should register and fire a static hook returning a promise that gets rejected with a error', function (done) { + it('should register and fire a static hook returning a promise that gets rejected with a error', (done) => { function method(data) { assert.equal(data.bar, 'test'); - return new Promise(function (resolve, reject) { + return new Promise((resolve, reject) => { reject(new Error('just because')); }); } plugins.hooks.register('test-plugin', { hook: 'static:test.hook', method: method }); - plugins.hooks.fire('static:test.hook', { bar: 'test' }, function (err) { + plugins.hooks.fire('static:test.hook', { bar: 'test' }, (err) => { assert.strictEqual(err.message, 'just because'); plugins.hooks.unregister('test-plugin', 'static:test.hook', method); done(); }); }); - it('should register and timeout a static hook returning a promise but takes too long', function (done) { + it('should register and timeout a static hook returning a promise but takes too long', (done) => { function method(data) { assert.equal(data.bar, 'test'); - return new Promise(function (resolve) { + return new Promise((resolve) => { setTimeout(resolve, 6000); }); } plugins.hooks.register('test-plugin', { hook: 'static:test.hook', method: method }); - plugins.hooks.fire('static:test.hook', { bar: 'test' }, function (err) { + plugins.hooks.fire('static:test.hook', { bar: 'test' }, (err) => { assert.ifError(err); plugins.hooks.unregister('test-plugin', 'static:test.hook', method); done(); }); }); - it('should get plugin data from nbbpm', function (done) { - plugins.get('nodebb-plugin-markdown', function (err, data) { + it('should get plugin data from nbbpm', (done) => { + plugins.get('nodebb-plugin-markdown', (err, data) => { assert.ifError(err); var keys = ['id', 'name', 'url', 'description', 'latest', 'installed', 'active', 'latest']; assert.equal(data.name, 'nodebb-plugin-markdown'); assert.equal(data.id, 'nodebb-plugin-markdown'); - keys.forEach(function (key) { + keys.forEach((key) => { assert(data.hasOwnProperty(key)); }); done(); }); }); - it('should get a list of plugins', function (done) { - plugins.list(function (err, data) { + it('should get a list of plugins', (done) => { + plugins.list((err, data) => { assert.ifError(err); var keys = ['id', 'name', 'url', 'description', 'latest', 'installed', 'active', 'latest']; assert(Array.isArray(data)); - keys.forEach(function (key) { + keys.forEach((key) => { assert(data[0].hasOwnProperty(key)); }); done(); }); }); - it('should show installed plugins', function (done) { + it('should show installed plugins', (done) => { var nodeModulesPath = plugins.nodeModulesPath; plugins.nodeModulesPath = path.join(__dirname, './mocks/plugin_modules'); - plugins.showInstalled(function (err, pluginsData) { + plugins.showInstalled((err, pluginsData) => { assert.ifError(err); - var paths = pluginsData.map(function (plugin) { - return path.relative(plugins.nodeModulesPath, plugin.path).replace(/\\/g, '/'); - }); + var paths = pluginsData.map(plugin => path.relative(plugins.nodeModulesPath, plugin.path).replace(/\\/g, '/')); assert(paths.indexOf('nodebb-plugin-xyz') > -1); assert(paths.indexOf('@nodebb/nodebb-plugin-abc') > -1); @@ -192,12 +190,12 @@ describe('Plugins', function () { }); }); - describe('install/activate/uninstall', function () { + describe('install/activate/uninstall', () => { var latest; var pluginName = 'nodebb-plugin-imgur'; it('should install a plugin', function (done) { this.timeout(0); - plugins.toggleInstall(pluginName, '1.0.16', function (err, pluginData) { + plugins.toggleInstall(pluginName, '1.0.16', (err, pluginData) => { assert.ifError(err); latest = pluginData.latest; @@ -215,10 +213,10 @@ describe('Plugins', function () { }); }); - it('should activate plugin', function (done) { - plugins.toggleActive(pluginName, function (err) { + it('should activate plugin', (done) => { + plugins.toggleActive(pluginName, (err) => { assert.ifError(err); - plugins.isActive(pluginName, function (err, isActive) { + plugins.isActive(pluginName, (err, isActive) => { assert.ifError(err); assert(isActive); done(); @@ -228,10 +226,10 @@ describe('Plugins', function () { it('should upgrade plugin', function (done) { this.timeout(0); - plugins.upgrade(pluginName, 'latest', function (err, isActive) { + plugins.upgrade(pluginName, 'latest', (err, isActive) => { assert.ifError(err); assert(isActive); - plugins.loadPluginInfo(path.join(nconf.get('base_dir'), 'node_modules', pluginName), function (err, pluginInfo) { + plugins.loadPluginInfo(path.join(nconf.get('base_dir'), 'node_modules', pluginName), (err, pluginInfo) => { assert.ifError(err); assert.equal(pluginInfo.version, latest); done(); @@ -241,7 +239,7 @@ describe('Plugins', function () { it('should uninstall a plugin', function (done) { this.timeout(0); - plugins.toggleInstall(pluginName, 'latest', function (err, pluginData) { + plugins.toggleInstall(pluginName, 'latest', (err, pluginData) => { assert.ifError(err); assert.equal(pluginData.installed, false); assert.equal(pluginData.active, false); @@ -254,9 +252,9 @@ describe('Plugins', function () { }); }); - describe('static assets', function () { - it('should 404 if resource does not exist', function (done) { - request.get(`${nconf.get('url')}/plugins/doesnotexist/should404.tpl`, function (err, res, body) { + describe('static assets', () => { + it('should 404 if resource does not exist', (done) => { + request.get(`${nconf.get('url')}/plugins/doesnotexist/should404.tpl`, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 404); assert(body); @@ -264,8 +262,8 @@ describe('Plugins', function () { }); }); - it('should 404 if resource does not exist', function (done) { - request.get(`${nconf.get('url')}/plugins/nodebb-plugin-dbsearch/dbsearch/templates/admin/plugins/should404.tpl`, function (err, res, body) { + it('should 404 if resource does not exist', (done) => { + request.get(`${nconf.get('url')}/plugins/nodebb-plugin-dbsearch/dbsearch/templates/admin/plugins/should404.tpl`, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 404); assert(body); @@ -273,8 +271,8 @@ describe('Plugins', function () { }); }); - it('should get resource', function (done) { - request.get(`${nconf.get('url')}/plugins/nodebb-plugin-dbsearch/dbsearch/templates/admin/plugins/dbsearch.tpl`, function (err, res, body) { + it('should get resource', (done) => { + request.get(`${nconf.get('url')}/plugins/nodebb-plugin-dbsearch/dbsearch/templates/admin/plugins/dbsearch.tpl`, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); diff --git a/test/posts.js b/test/posts.js index 2cd1f6ffaf..1527089217 100644 --- a/test/posts.js +++ b/test/posts.js @@ -21,7 +21,7 @@ var socketTopics = require('../src/socket.io/topics'); var meta = require('../src/meta'); var helpers = require('./helpers'); -describe('Post\'s', function () { +describe('Post\'s', () => { var voterUid; var voteeUid; var globalModUid; @@ -29,7 +29,7 @@ describe('Post\'s', function () { var topicData; var cid; - before(function (done) { + before((done) => { async.series({ voterUid: function (next) { user.create({ username: 'upvoter' }, next); @@ -46,7 +46,7 @@ describe('Post\'s', function () { description: 'Test category created by testing script', }, next); }, - }, function (err, results) { + }, (err, results) => { if (err) { return done(err); } @@ -61,7 +61,7 @@ describe('Post\'s', function () { cid: results.category.cid, title: 'Test Topic Title', content: 'The content of test topic', - }, function (err, data) { + }, (err, data) => { if (err) { return done(err); } @@ -73,10 +73,10 @@ describe('Post\'s', function () { }); }); - it('should update category teaser properly', async function () { + it('should update category teaser properly', async () => { const util = require('util'); - const getCategoriesAsync = util.promisify(async function getCategories(callback) { - request(`${nconf.get('url')}/api/categories`, { json: true }, function (err, res, body) { + const getCategoriesAsync = util.promisify(async (callback) => { + request(`${nconf.get('url')}/api/categories`, { json: true }, (err, res, body) => { callback(err, body); }); }); @@ -104,7 +104,7 @@ describe('Post\'s', function () { assert.equal(data.categories[0].posts[0].pid, postResult.postData.pid); }); - it('should change owner of post and topic properly', async function () { + it('should change owner of post and topic properly', async () => { const oldUid = await user.create({ username: 'olduser' }); const newUid = await user.create({ username: 'newuser' }); const postResult = await topics.post({ uid: oldUid, cid: cid, title: 'change owner', content: 'original post' }); @@ -134,7 +134,7 @@ describe('Post\'s', function () { assert.strictEqual(await topics.isOwner(postResult.topicData.tid, newUid), true); }); - it('should fail to change owner if new owner does not exist', async function () { + it('should fail to change owner if new owner does not exist', async () => { try { await posts.changeOwner([1], '9999999'); } catch (err) { @@ -142,7 +142,7 @@ describe('Post\'s', function () { } }); - it('should fail to change owner if user is not authorized', async function () { + it('should fail to change owner if user is not authorized', async () => { try { await socketPosts.changeOwner({ uid: voterUid }, { pids: [1, 2], toUid: voterUid }); } catch (err) { @@ -150,23 +150,23 @@ describe('Post\'s', function () { } }); - it('should return falsy if post does not exist', function (done) { - posts.getPostData(9999, function (err, postData) { + it('should return falsy if post does not exist', (done) => { + posts.getPostData(9999, (err, postData) => { assert.ifError(err); assert.equal(postData, null); done(); }); }); - describe('voting', function () { - it('should fail to upvote post if group does not have upvote permission', function (done) { - privileges.categories.rescind(['groups:posts:upvote', 'groups:posts:downvote'], cid, 'registered-users', function (err) { + describe('voting', () => { + it('should fail to upvote post if group does not have upvote permission', (done) => { + privileges.categories.rescind(['groups:posts:upvote', 'groups:posts:downvote'], cid, 'registered-users', (err) => { assert.ifError(err); - socketPosts.upvote({ uid: voterUid }, { pid: postData.pid, room_id: 'topic_1' }, function (err) { + socketPosts.upvote({ uid: voterUid }, { pid: postData.pid, room_id: 'topic_1' }, (err) => { assert.equal(err.message, '[[error:no-privileges]]'); - socketPosts.downvote({ uid: voterUid }, { pid: postData.pid, room_id: 'topic_1' }, function (err) { + socketPosts.downvote({ uid: voterUid }, { pid: postData.pid, room_id: 'topic_1' }, (err) => { assert.equal(err.message, '[[error:no-privileges]]'); - privileges.categories.give(['groups:posts:upvote', 'groups:posts:downvote'], cid, 'registered-users', function (err) { + privileges.categories.give(['groups:posts:upvote', 'groups:posts:downvote'], cid, 'registered-users', (err) => { assert.ifError(err); done(); }); @@ -175,14 +175,14 @@ describe('Post\'s', function () { }); }); - it('should upvote a post', function (done) { - socketPosts.upvote({ uid: voterUid }, { pid: postData.pid, room_id: 'topic_1' }, function (err, result) { + it('should upvote a post', (done) => { + socketPosts.upvote({ uid: voterUid }, { pid: postData.pid, room_id: 'topic_1' }, (err, result) => { assert.ifError(err); assert.equal(result.post.upvotes, 1); assert.equal(result.post.downvotes, 0); assert.equal(result.post.votes, 1); assert.equal(result.user.reputation, 1); - posts.hasVoted(postData.pid, voterUid, function (err, data) { + posts.hasVoted(postData.pid, voterUid, (err, data) => { assert.ifError(err); assert.equal(data.upvoted, true); assert.equal(data.downvoted, false); @@ -191,8 +191,8 @@ describe('Post\'s', function () { }); }); - it('should get voters', function (done) { - socketPosts.getVoters({ uid: globalModUid }, { pid: postData.pid, cid: cid }, function (err, data) { + it('should get voters', (done) => { + socketPosts.getVoters({ uid: globalModUid }, { pid: postData.pid, cid: cid }, (err, data) => { assert.ifError(err); assert.equal(data.upvoteCount, 1); assert.equal(data.downvoteCount, 0); @@ -202,8 +202,8 @@ describe('Post\'s', function () { }); }); - it('should get upvoters', function (done) { - socketPosts.getUpvoters({ uid: globalModUid }, [postData.pid], function (err, data) { + it('should get upvoters', (done) => { + socketPosts.getUpvoters({ uid: globalModUid }, [postData.pid], (err, data) => { assert.ifError(err); assert.equal(data[0].otherCount, 0); assert.equal(data[0].usernames, 'upvoter'); @@ -211,14 +211,14 @@ describe('Post\'s', function () { }); }); - it('should unvote a post', function (done) { - socketPosts.unvote({ uid: voterUid }, { pid: postData.pid, room_id: 'topic_1' }, function (err, result) { + it('should unvote a post', (done) => { + socketPosts.unvote({ uid: voterUid }, { pid: postData.pid, room_id: 'topic_1' }, (err, result) => { assert.ifError(err); assert.equal(result.post.upvotes, 0); assert.equal(result.post.downvotes, 0); assert.equal(result.post.votes, 0); assert.equal(result.user.reputation, 0); - posts.hasVoted(postData.pid, voterUid, function (err, data) { + posts.hasVoted(postData.pid, voterUid, (err, data) => { assert.ifError(err); assert.equal(data.upvoted, false); assert.equal(data.downvoted, false); @@ -227,14 +227,14 @@ describe('Post\'s', function () { }); }); - it('should downvote a post', function (done) { - socketPosts.downvote({ uid: voterUid }, { pid: postData.pid, room_id: 'topic_1' }, function (err, result) { + it('should downvote a post', (done) => { + socketPosts.downvote({ uid: voterUid }, { pid: postData.pid, room_id: 'topic_1' }, (err, result) => { assert.ifError(err); assert.equal(result.post.upvotes, 0); assert.equal(result.post.downvotes, 1); assert.equal(result.post.votes, -1); assert.equal(result.user.reputation, -1); - posts.hasVoted(postData.pid, voterUid, function (err, data) { + posts.hasVoted(postData.pid, voterUid, (err, data) => { assert.ifError(err); assert.equal(data.upvoted, false); assert.equal(data.downvoted, true); @@ -280,12 +280,12 @@ describe('Post\'s', function () { }); }); - describe('bookmarking', function () { - it('should bookmark a post', function (done) { - socketPosts.bookmark({ uid: voterUid }, { pid: postData.pid, room_id: `topic_${postData.tid}` }, function (err, data) { + describe('bookmarking', () => { + it('should bookmark a post', (done) => { + socketPosts.bookmark({ uid: voterUid }, { pid: postData.pid, room_id: `topic_${postData.tid}` }, (err, data) => { assert.ifError(err); assert.equal(data.isBookmarked, true); - posts.hasBookmarked(postData.pid, voterUid, function (err, hasBookmarked) { + posts.hasBookmarked(postData.pid, voterUid, (err, hasBookmarked) => { assert.ifError(err); assert.equal(hasBookmarked, true); done(); @@ -293,11 +293,11 @@ describe('Post\'s', function () { }); }); - it('should unbookmark a post', function (done) { - socketPosts.unbookmark({ uid: voterUid }, { pid: postData.pid, room_id: `topic_${postData.tid}` }, function (err, data) { + it('should unbookmark a post', (done) => { + socketPosts.unbookmark({ uid: voterUid }, { pid: postData.pid, room_id: `topic_${postData.tid}` }, (err, data) => { assert.ifError(err); assert.equal(data.isBookmarked, false); - posts.hasBookmarked([postData.pid], voterUid, function (err, hasBookmarked) { + posts.hasBookmarked([postData.pid], voterUid, (err, hasBookmarked) => { assert.ifError(err); assert.equal(hasBookmarked[0], false); done(); @@ -306,16 +306,16 @@ describe('Post\'s', function () { }); }); - describe('post tools', function () { - it('should error if data is invalid', function (done) { - socketPosts.loadPostTools({ uid: globalModUid }, null, function (err) { + describe('post tools', () => { + it('should error if data is invalid', (done) => { + socketPosts.loadPostTools({ uid: globalModUid }, null, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); }); - it('should load post tools', function (done) { - socketPosts.loadPostTools({ uid: globalModUid }, { pid: postData.pid, cid: cid }, function (err, data) { + it('should load post tools', (done) => { + socketPosts.loadPostTools({ uid: globalModUid }, { pid: postData.pid, cid: cid }, (err, data) => { assert.ifError(err); assert(data.posts.display_edit_tools); assert(data.posts.display_delete_tools); @@ -326,21 +326,21 @@ describe('Post\'s', function () { }); }); - describe('delete/restore/purge', function () { + describe('delete/restore/purge', () => { function createTopicWithReply(callback) { topics.post({ uid: voterUid, cid: cid, title: 'topic to delete/restore/purge', content: 'A post to delete/restore/purge', - }, function (err, topicPostData) { + }, (err, topicPostData) => { assert.ifError(err); topics.reply({ uid: voterUid, tid: topicPostData.topicData.tid, timestamp: Date.now(), content: 'A post to delete/restore and purge', - }, function (err, replyData) { + }, (err, replyData) => { assert.ifError(err); callback(topicPostData, replyData); }); @@ -351,8 +351,8 @@ describe('Post\'s', function () { var mainPid; var replyPid; - before(function (done) { - createTopicWithReply(function (topicPostData, replyData) { + before((done) => { + createTopicWithReply((topicPostData, replyData) => { tid = topicPostData.topicData.tid; mainPid = topicPostData.postData.pid; replyPid = replyData.pid; @@ -360,17 +360,17 @@ describe('Post\'s', function () { }); }); - it('should error with invalid data', function (done) { - socketPosts.delete({ uid: voterUid }, null, function (err) { + it('should error with invalid data', (done) => { + socketPosts.delete({ uid: voterUid }, null, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); }); - it('should delete a post', function (done) { - socketPosts.delete({ uid: voterUid }, { pid: replyPid, tid: tid }, function (err) { + it('should delete a post', (done) => { + socketPosts.delete({ uid: voterUid }, { pid: replyPid, tid: tid }, (err) => { assert.ifError(err); - posts.getPostField(replyPid, 'deleted', function (err, isDeleted) { + posts.getPostField(replyPid, 'deleted', (err, isDeleted) => { assert.ifError(err); assert.strictEqual(isDeleted, 1); done(); @@ -378,7 +378,7 @@ describe('Post\'s', function () { }); }); - it('should not see post content if global mod does not have posts:view_deleted privilege', function (done) { + it('should not see post content if global mod does not have posts:view_deleted privilege', (done) => { async.waterfall([ function (next) { user.create({ username: 'global mod', password: '123456' }, next); @@ -390,11 +390,11 @@ describe('Post\'s', function () { privileges.categories.rescind(['groups:posts:view_deleted'], cid, 'Global Moderators', next); }, function (next) { - helpers.loginUser('global mod', '123456', function (err, _jar) { + helpers.loginUser('global mod', '123456', (err, _jar) => { assert.ifError(err); var jar = _jar; - request(`${nconf.get('url')}/api/topic/${tid}`, { jar: jar, json: true }, function (err, res, body) { + request(`${nconf.get('url')}/api/topic/${tid}`, { jar: jar, json: true }, (err, res, body) => { assert.ifError(err); assert.equal(body.posts[1].content, '[[topic:post_is_deleted]]'); privileges.categories.give(['groups:posts:view_deleted'], cid, 'Global Moderators', next); @@ -404,10 +404,10 @@ describe('Post\'s', function () { ], done); }); - it('should restore a post', function (done) { - socketPosts.restore({ uid: voterUid }, { pid: replyPid, tid: tid }, function (err) { + it('should restore a post', (done) => { + socketPosts.restore({ uid: voterUid }, { pid: replyPid, tid: tid }, (err) => { assert.ifError(err); - posts.getPostField(replyPid, 'deleted', function (err, isDeleted) { + posts.getPostField(replyPid, 'deleted', (err, isDeleted) => { assert.ifError(err); assert.strictEqual(isDeleted, 0); done(); @@ -415,13 +415,13 @@ describe('Post\'s', function () { }); }); - it('should delete posts', function (done) { - socketPosts.deletePosts({ uid: globalModUid }, { pids: [replyPid, mainPid] }, function (err) { + it('should delete posts', (done) => { + socketPosts.deletePosts({ uid: globalModUid }, { pids: [replyPid, mainPid] }, (err) => { assert.ifError(err); - posts.getPostField(replyPid, 'deleted', function (err, deleted) { + posts.getPostField(replyPid, 'deleted', (err, deleted) => { assert.ifError(err); assert.strictEqual(deleted, 1); - posts.getPostField(mainPid, 'deleted', function (err, deleted) { + posts.getPostField(mainPid, 'deleted', (err, deleted) => { assert.ifError(err); assert.strictEqual(deleted, 1); done(); @@ -430,12 +430,12 @@ describe('Post\'s', function () { }); }); - it('should delete topic if last main post is deleted', function (done) { - topics.post({ uid: voterUid, cid: cid, title: 'test topic', content: 'test topic' }, function (err, data) { + it('should delete topic if last main post is deleted', (done) => { + topics.post({ uid: voterUid, cid: cid, title: 'test topic', content: 'test topic' }, (err, data) => { assert.ifError(err); - socketPosts.deletePosts({ uid: globalModUid }, { pids: [data.postData.pid] }, function (err) { + socketPosts.deletePosts({ uid: globalModUid }, { pids: [data.postData.pid] }, (err) => { assert.ifError(err); - topics.getTopicField(data.topicData.tid, 'deleted', function (err, deleted) { + topics.getTopicField(data.topicData.tid, 'deleted', (err, deleted) => { assert.ifError(err); assert.strictEqual(deleted, 1); done(); @@ -444,14 +444,14 @@ describe('Post\'s', function () { }); }); - it('should purge posts and purge topic', function (done) { - createTopicWithReply(function (topicPostData, replyData) { - socketPosts.purgePosts({ uid: voterUid }, { pids: [replyData.pid, topicPostData.postData.pid], tid: topicPostData.topicData.tid }, function (err) { + it('should purge posts and purge topic', (done) => { + createTopicWithReply((topicPostData, replyData) => { + socketPosts.purgePosts({ uid: voterUid }, { pids: [replyData.pid, topicPostData.postData.pid], tid: topicPostData.topicData.tid }, (err) => { assert.ifError(err); - posts.exists(`post:${replyData.pid}`, function (err, exists) { + posts.exists(`post:${replyData.pid}`, (err, exists) => { assert.ifError(err); assert.equal(exists, false); - topics.exists(topicPostData.topicData.tid, function (err, exists) { + topics.exists(topicPostData.topicData.tid, (err, exists) => { assert.ifError(err); assert(!exists); done(); @@ -462,17 +462,17 @@ describe('Post\'s', function () { }); }); - describe('edit', function () { + describe('edit', () => { var pid; var replyPid; var tid; - before(function (done) { + before((done) => { topics.post({ uid: voterUid, cid: cid, title: 'topic to edit', content: 'A post to edit', - }, function (err, data) { + }, (err, data) => { assert.ifError(err); pid = data.postData.pid; tid = data.topicData.tid; @@ -481,7 +481,7 @@ describe('Post\'s', function () { tid: tid, timestamp: Date.now(), content: 'A reply to edit', - }, function (err, data) { + }, (err, data) => { assert.ifError(err); replyPid = data.pid; privileges.categories.give(['groups:posts:edit'], cid, 'registered-users', done); @@ -489,72 +489,72 @@ describe('Post\'s', function () { }); }); - it('should error if user is not logged in', function (done) { - socketPosts.edit({ uid: 0 }, {}, function (err) { + it('should error if user is not logged in', (done) => { + socketPosts.edit({ uid: 0 }, {}, (err) => { assert.equal(err.message, '[[error:not-logged-in]]'); done(); }); }); - it('should error if data is invalid or missing', function (done) { - socketPosts.edit({ uid: voterUid }, {}, function (err) { + it('should error if data is invalid or missing', (done) => { + socketPosts.edit({ uid: voterUid }, {}, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); }); - it('should error if title is too short', function (done) { - socketPosts.edit({ uid: voterUid }, { pid: pid, content: 'edited post content', title: 'a' }, function (err) { + it('should error if title is too short', (done) => { + socketPosts.edit({ uid: voterUid }, { pid: pid, content: 'edited post content', title: 'a' }, (err) => { assert.equal(err.message, `[[error:title-too-short, ${meta.config.minimumTitleLength}]]`); done(); }); }); - it('should error if title is too long', function (done) { + it('should error if title is too long', (done) => { var longTitle = new Array(meta.config.maximumTitleLength + 2).join('a'); - socketPosts.edit({ uid: voterUid }, { pid: pid, content: 'edited post content', title: longTitle }, function (err) { + socketPosts.edit({ uid: voterUid }, { pid: pid, content: 'edited post content', title: longTitle }, (err) => { assert.equal(err.message, `[[error:title-too-long, ${meta.config.maximumTitleLength}]]`); done(); }); }); - it('should error with too few tags', function (done) { + it('should error with too few tags', (done) => { var oldValue = meta.config.minimumTagsPerTopic; meta.config.minimumTagsPerTopic = 1; - socketPosts.edit({ uid: voterUid }, { pid: pid, content: 'edited post content', tags: [] }, function (err) { + socketPosts.edit({ uid: voterUid }, { pid: pid, content: 'edited post content', tags: [] }, (err) => { assert.equal(err.message, `[[error:not-enough-tags, ${meta.config.minimumTagsPerTopic}]]`); meta.config.minimumTagsPerTopic = oldValue; done(); }); }); - it('should error with too many tags', function (done) { + it('should error with too many tags', (done) => { var tags = []; for (var i = 0; i < meta.config.maximumTagsPerTopic + 1; i += 1) { tags.push(`tag${i}`); } - socketPosts.edit({ uid: voterUid }, { pid: pid, content: 'edited post content', tags: tags }, function (err) { + socketPosts.edit({ uid: voterUid }, { pid: pid, content: 'edited post content', tags: tags }, (err) => { assert.equal(err.message, `[[error:too-many-tags, ${meta.config.maximumTagsPerTopic}]]`); done(); }); }); - it('should error if content is too short', function (done) { - socketPosts.edit({ uid: voterUid }, { pid: pid, content: 'e' }, function (err) { + it('should error if content is too short', (done) => { + socketPosts.edit({ uid: voterUid }, { pid: pid, content: 'e' }, (err) => { assert.equal(err.message, `[[error:content-too-short, ${meta.config.minimumPostLength}]]`); done(); }); }); - it('should error if content is too long', function (done) { + it('should error if content is too long', (done) => { var longContent = new Array(meta.config.maximumPostLength + 2).join('a'); - socketPosts.edit({ uid: voterUid }, { pid: pid, content: longContent }, function (err) { + socketPosts.edit({ uid: voterUid }, { pid: pid, content: longContent }, (err) => { assert.equal(err.message, `[[error:content-too-long, ${meta.config.maximumPostLength}]]`); done(); }); }); - it('should edit post', async function () { + it('should edit post', async () => { const data = await socketPosts.edit({ uid: voterUid }, { pid: pid, content: 'edited post content', @@ -570,10 +570,10 @@ describe('Post\'s', function () { assert(!res.hasOwnProperty('bookmarks')); }); - it('should disallow post editing for new users if post was made past the threshold for editing', function (done) { + it('should disallow post editing for new users if post was made past the threshold for editing', (done) => { meta.config.newbiePostEditDuration = 1; - setTimeout(function () { - socketPosts.edit({ uid: voterUid }, { pid: pid, content: 'edited post content again', title: 'edited title again', tags: ['edited-twice'] }, function (err, data) { + setTimeout(() => { + socketPosts.edit({ uid: voterUid }, { pid: pid, content: 'edited post content again', title: 'edited title again', tags: ['edited-twice'] }, (err, data) => { assert.equal(err.message, '[[error:post-edit-duration-expired, 1]]'); meta.config.newbiePostEditDuration = 3600; done(); @@ -581,10 +581,10 @@ describe('Post\'s', function () { }, 1000); }); - it('should edit a deleted post', function (done) { - socketPosts.delete({ uid: voterUid }, { pid: pid, tid: tid }, function (err) { + it('should edit a deleted post', (done) => { + socketPosts.delete({ uid: voterUid }, { pid: pid, tid: tid }, (err) => { assert.ifError(err); - socketPosts.edit({ uid: voterUid }, { pid: pid, content: 'edited deleted content', title: 'edited deleted title', tags: ['deleted'] }, function (err, data) { + socketPosts.edit({ uid: voterUid }, { pid: pid, content: 'edited deleted content', title: 'edited deleted title', tags: ['deleted'] }, (err, data) => { assert.ifError(err); assert.equal(data.content, 'edited deleted content'); assert.equal(data.editor, voterUid); @@ -595,8 +595,8 @@ describe('Post\'s', function () { }); }); - it('should edit a reply post', function (done) { - socketPosts.edit({ uid: voterUid }, { pid: replyPid, content: 'edited reply' }, function (err, data) { + it('should edit a reply post', (done) => { + socketPosts.edit({ uid: voterUid }, { pid: replyPid, content: 'edited reply' }, (err, data) => { assert.ifError(err); assert.equal(data.content, 'edited reply'); assert.equal(data.editor, voterUid); @@ -606,8 +606,8 @@ describe('Post\'s', function () { }); }); - it('should return diffs', function (done) { - posts.diffs.get(replyPid, 0, function (err, data) { + it('should return diffs', (done) => { + posts.diffs.get(replyPid, 0, (err, data) => { assert.ifError(err); assert(Array.isArray(data)); assert(data[0].pid, replyPid); @@ -616,23 +616,23 @@ describe('Post\'s', function () { }); }); - it('should load diffs and reconstruct post', function (done) { - posts.diffs.load(replyPid, 0, voterUid, function (err, data) { + it('should load diffs and reconstruct post', (done) => { + posts.diffs.load(replyPid, 0, voterUid, (err, data) => { assert.ifError(err); assert.equal(data.content, 'A reply to edit'); done(); }); }); - it('should not allow guests to view diffs', function (done) { - socketPosts.getDiffs({ uid: 0 }, { pid: 1 }, function (err) { + it('should not allow guests to view diffs', (done) => { + socketPosts.getDiffs({ uid: 0 }, { pid: 1 }, (err) => { assert.equal(err.message, '[[error:no-privileges]]'); done(); }); }); - it('should allow registered-users group to view diffs', function (done) { - socketPosts.getDiffs({ uid: 1 }, { pid: 1 }, function (err, data) { + it('should allow registered-users group to view diffs', (done) => { + socketPosts.getDiffs({ uid: 1 }, { pid: 1 }, (err, data) => { assert.ifError(err); assert.strictEqual('boolean', typeof data.editable); @@ -648,7 +648,7 @@ describe('Post\'s', function () { }); }); - it('should not delete first diff of a post', async function () { + it('should not delete first diff of a post', async () => { const timestamps = await posts.diffs.list(replyPid); await assert.rejects(async () => { await posts.diffs.delete(replyPid, timestamps[0], voterUid); @@ -657,7 +657,7 @@ describe('Post\'s', function () { }); }); - it('should delete a post diff', async function () { + it('should delete a post diff', async () => { await socketPosts.edit({ uid: voterUid }, { pid: replyPid, content: 'another edit has been made' }); await socketPosts.edit({ uid: voterUid }, { pid: replyPid, content: 'most recent edit' }); const timestamp = (await posts.diffs.list(replyPid)).pop(); @@ -666,18 +666,18 @@ describe('Post\'s', function () { assert.notStrictEqual(timestamp, differentTimestamp); }); - it('should load (oldest) diff and reconstruct post correctly after a diff deletion', async function () { + it('should load (oldest) diff and reconstruct post correctly after a diff deletion', async () => { const data = await posts.diffs.load(replyPid, 0, voterUid); assert.strictEqual(data.content, 'A reply to edit'); }); }); - describe('move', function () { + describe('move', () => { var replyPid; var tid; var moveTid; - before(function (done) { + before((done) => { async.waterfall([ function (next) { topics.post({ @@ -703,7 +703,7 @@ describe('Post\'s', function () { tid: tid, timestamp: Date.now(), content: 'A reply to move', - }, function (err, data) { + }, (err, data) => { assert.ifError(err); replyPid = data.pid; next(); @@ -712,32 +712,32 @@ describe('Post\'s', function () { ], done); }); - it('should error if uid is not logged in', function (done) { - socketPosts.movePost({ uid: 0 }, {}, function (err) { + it('should error if uid is not logged in', (done) => { + socketPosts.movePost({ uid: 0 }, {}, (err) => { assert.equal(err.message, '[[error:not-logged-in]]'); done(); }); }); - it('should error if data is invalid', function (done) { - socketPosts.movePost({ uid: globalModUid }, {}, function (err) { + it('should error if data is invalid', (done) => { + socketPosts.movePost({ uid: globalModUid }, {}, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); }); - it('should error if user does not have move privilege', function (done) { - socketPosts.movePost({ uid: voterUid }, { pid: replyPid, tid: moveTid }, function (err) { + it('should error if user does not have move privilege', (done) => { + socketPosts.movePost({ uid: voterUid }, { pid: replyPid, tid: moveTid }, (err) => { assert.equal(err.message, '[[error:no-privileges]]'); done(); }); }); - it('should move a post', function (done) { - socketPosts.movePost({ uid: globalModUid }, { pid: replyPid, tid: moveTid }, function (err) { + it('should move a post', (done) => { + socketPosts.movePost({ uid: globalModUid }, { pid: replyPid, tid: moveTid }, (err) => { assert.ifError(err); - posts.getPostField(replyPid, 'tid', function (err, tid) { + posts.getPostField(replyPid, 'tid', (err, tid) => { assert.ifError(err); assert(tid, moveTid); done(); @@ -745,7 +745,7 @@ describe('Post\'s', function () { }); }); - it('should fail to move post if not moderator of target category', async function () { + it('should fail to move post if not moderator of target category', async () => { const cat1 = await categories.create({ name: 'Test Category', description: 'Test category created by testing script' }); const cat2 = await categories.create({ name: 'Test Category', description: 'Test category created by testing script' }); const result = await socketTopics.post({ uid: globalModUid }, { title: 'target topic', content: 'queued topic', cid: cat2.cid }); @@ -761,17 +761,17 @@ describe('Post\'s', function () { }); }); - describe('getPostSummaryByPids', function () { - it('should return empty array for empty pids', function (done) { - posts.getPostSummaryByPids([], 0, {}, function (err, data) { + describe('getPostSummaryByPids', () => { + it('should return empty array for empty pids', (done) => { + posts.getPostSummaryByPids([], 0, {}, (err, data) => { assert.ifError(err); assert.equal(data.length, 0); done(); }); }); - it('should get post summaries', function (done) { - posts.getPostSummaryByPids([postData.pid], 0, {}, function (err, data) { + it('should get post summaries', (done) => { + posts.getPostSummaryByPids([postData.pid], 0, {}, (err, data) => { assert.ifError(err); assert(data[0].user); assert(data[0].topic); @@ -781,15 +781,15 @@ describe('Post\'s', function () { }); }); - it('should get recent poster uids', function (done) { + it('should get recent poster uids', (done) => { topics.reply({ uid: voterUid, tid: topicData.tid, timestamp: Date.now(), content: 'some content', - }, function (err) { + }, (err) => { assert.ifError(err); - posts.getRecentPosterUids(0, 1, function (err, uids) { + posts.getRecentPosterUids(0, 1, (err, uids) => { assert.ifError(err); assert(Array.isArray(uids)); assert.equal(uids.length, 2); @@ -799,25 +799,25 @@ describe('Post\'s', function () { }); }); - describe('parse', function () { - it('should not crash and return falsy if post data is falsy', function (done) { - posts.parsePost(null, function (err, postData) { + describe('parse', () => { + it('should not crash and return falsy if post data is falsy', (done) => { + posts.parsePost(null, (err, postData) => { assert.ifError(err); assert.strictEqual(postData, null); done(); }); }); - it('should store post content in cache', function (done) { + it('should store post content in cache', (done) => { var oldValue = global.env; global.env = 'production'; var postData = { pid: 9999, content: 'some post content', }; - posts.parsePost(postData, function (err) { + posts.parsePost(postData, (err) => { assert.ifError(err); - posts.parsePost(postData, function (err) { + posts.parsePost(postData, (err) => { assert.ifError(err); global.env = oldValue; done(); @@ -825,14 +825,14 @@ describe('Post\'s', function () { }); }); - it('should parse signature and remove links and images', function (done) { + it('should parse signature and remove links and images', (done) => { meta.config['signatures:disableLinks'] = 1; meta.config['signatures:disableImages'] = 1; var userData = { signature: 'test derp', }; - posts.parseSignature(userData, 1, function (err, data) { + posts.parseSignature(userData, 1, (err, data) => { assert.ifError(err); assert.equal(data.userData.signature, 'test derp'); meta.config['signatures:disableLinks'] = 0; @@ -841,7 +841,7 @@ describe('Post\'s', function () { }); }); - it('should turn relative links in post body to absolute urls', function (done) { + it('should turn relative links in post body to absolute urls', (done) => { var nconf = require('nconf'); var content = 'test youtube'; var parsedContent = posts.relativeToAbsolute(content, posts.urlRegex); @@ -849,7 +849,7 @@ describe('Post\'s', function () { done(); }); - it('should turn relative links in post body to absolute urls', function (done) { + it('should turn relative links in post body to absolute urls', (done) => { var nconf = require('nconf'); var content = 'test youtube some test '; var parsedContent = posts.relativeToAbsolute(content, posts.urlRegex); @@ -859,56 +859,56 @@ describe('Post\'s', function () { }); }); - describe('socket methods', function () { + describe('socket methods', () => { var pid; - before(function (done) { + before((done) => { topics.reply({ uid: voterUid, tid: topicData.tid, timestamp: Date.now(), content: 'raw content', - }, function (err, postData) { + }, (err, postData) => { assert.ifError(err); pid = postData.pid; privileges.categories.rescind(['groups:topics:read'], cid, 'guests', done); }); }); - it('should error with invalid data', function (done) { - socketPosts.reply({ uid: 0 }, null, function (err) { + it('should error with invalid data', (done) => { + socketPosts.reply({ uid: 0 }, null, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); }); - it('should error with invalid tid', function (done) { - socketPosts.reply({ uid: 0 }, { tid: 0, content: 'derp' }, function (err) { + it('should error with invalid tid', (done) => { + socketPosts.reply({ uid: 0 }, { tid: 0, content: 'derp' }, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); }); - it('should fail to get raw post because of privilege', function (done) { - socketPosts.getRawPost({ uid: 0 }, pid, function (err) { + it('should fail to get raw post because of privilege', (done) => { + socketPosts.getRawPost({ uid: 0 }, pid, (err) => { assert.equal(err.message, '[[error:no-privileges]]'); done(); }); }); - it('should fail to get raw post because post is deleted', function (done) { - posts.setPostField(pid, 'deleted', 1, function (err) { + it('should fail to get raw post because post is deleted', (done) => { + posts.setPostField(pid, 'deleted', 1, (err) => { assert.ifError(err); - socketPosts.getRawPost({ uid: voterUid }, pid, function (err) { + socketPosts.getRawPost({ uid: voterUid }, pid, (err) => { assert.equal(err.message, '[[error:no-post]]'); done(); }); }); }); - it('should get raw post content', function (done) { - posts.setPostField(pid, 'deleted', 0, function (err) { + it('should get raw post content', (done) => { + posts.setPostField(pid, 'deleted', 0, (err) => { assert.ifError(err); - socketPosts.getRawPost({ uid: voterUid }, pid, function (err, postContent) { + socketPosts.getRawPost({ uid: voterUid }, pid, (err, postContent) => { assert.ifError(err); assert.equal(postContent, 'raw content'); done(); @@ -916,93 +916,93 @@ describe('Post\'s', function () { }); }); - it('should get post', function (done) { - socketPosts.getPost({ uid: voterUid }, pid, function (err, postData) { + it('should get post', (done) => { + socketPosts.getPost({ uid: voterUid }, pid, (err, postData) => { assert.ifError(err); assert(postData); done(); }); }); - it('shold error with invalid data', function (done) { - socketPosts.loadMoreBookmarks({ uid: voterUid }, { uid: voterUid, after: null }, function (err) { + it('shold error with invalid data', (done) => { + socketPosts.loadMoreBookmarks({ uid: voterUid }, { uid: voterUid, after: null }, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); }); - it('should load more bookmarks', function (done) { - socketPosts.loadMoreBookmarks({ uid: voterUid }, { uid: voterUid, after: 0 }, function (err, data) { + it('should load more bookmarks', (done) => { + socketPosts.loadMoreBookmarks({ uid: voterUid }, { uid: voterUid, after: 0 }, (err, data) => { assert.ifError(err); assert(data); done(); }); }); - it('should load more user posts', function (done) { - socketPosts.loadMoreUserPosts({ uid: voterUid }, { uid: voterUid, after: 0 }, function (err, data) { + it('should load more user posts', (done) => { + socketPosts.loadMoreUserPosts({ uid: voterUid }, { uid: voterUid, after: 0 }, (err, data) => { assert.ifError(err); assert(data); done(); }); }); - it('should load more best posts', function (done) { - socketPosts.loadMoreBestPosts({ uid: voterUid }, { uid: voterUid, after: 0 }, function (err, data) { + it('should load more best posts', (done) => { + socketPosts.loadMoreBestPosts({ uid: voterUid }, { uid: voterUid, after: 0 }, (err, data) => { assert.ifError(err); assert(data); done(); }); }); - it('should load more up voted posts', function (done) { - socketPosts.loadMoreUpVotedPosts({ uid: voterUid }, { uid: voterUid, after: 0 }, function (err, data) { + it('should load more up voted posts', (done) => { + socketPosts.loadMoreUpVotedPosts({ uid: voterUid }, { uid: voterUid, after: 0 }, (err, data) => { assert.ifError(err); assert(data); done(); }); }); - it('should load more down voted posts', function (done) { - socketPosts.loadMoreDownVotedPosts({ uid: voterUid }, { uid: voterUid, after: 0 }, function (err, data) { + it('should load more down voted posts', (done) => { + socketPosts.loadMoreDownVotedPosts({ uid: voterUid }, { uid: voterUid, after: 0 }, (err, data) => { assert.ifError(err); assert(data); done(); }); }); - it('should get post category', function (done) { - socketPosts.getCategory({ uid: voterUid }, pid, function (err, postCid) { + it('should get post category', (done) => { + socketPosts.getCategory({ uid: voterUid }, pid, (err, postCid) => { assert.ifError(err); assert.equal(cid, postCid); done(); }); }); - it('should error with invalid data', function (done) { - socketPosts.getPidIndex({ uid: voterUid }, null, function (err) { + it('should error with invalid data', (done) => { + socketPosts.getPidIndex({ uid: voterUid }, null, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); }); - it('should get pid index', function (done) { - socketPosts.getPidIndex({ uid: voterUid }, { pid: pid, tid: topicData.tid, topicPostSort: 'oldest_to_newest' }, function (err, index) { + it('should get pid index', (done) => { + socketPosts.getPidIndex({ uid: voterUid }, { pid: pid, tid: topicData.tid, topicPostSort: 'oldest_to_newest' }, (err, index) => { assert.ifError(err); assert.equal(index, 4); done(); }); }); - it('should get pid index in reverse', function (done) { + it('should get pid index in reverse', (done) => { topics.reply({ uid: voterUid, tid: topicData.tid, content: 'raw content', - }, function (err, postData) { + }, (err, postData) => { assert.ifError(err); - socketPosts.getPidIndex({ uid: voterUid }, { pid: postData.pid, tid: topicData.tid, topicPostSort: 'newest_to_oldest' }, function (err, index) { + socketPosts.getPidIndex({ uid: voterUid }, { pid: postData.pid, tid: topicData.tid, topicPostSort: 'newest_to_oldest' }, (err, index) => { assert.ifError(err); assert.equal(index, 1); done(); @@ -1011,33 +1011,33 @@ describe('Post\'s', function () { }); }); - describe('filterPidsByCid', function () { - it('should return pids as is if cid is falsy', function (done) { - posts.filterPidsByCid([1, 2, 3], null, function (err, pids) { + describe('filterPidsByCid', () => { + it('should return pids as is if cid is falsy', (done) => { + posts.filterPidsByCid([1, 2, 3], null, (err, pids) => { assert.ifError(err); assert.deepEqual([1, 2, 3], pids); done(); }); }); - it('should filter pids by single cid', function (done) { - posts.filterPidsByCid([postData.pid, 100, 101], cid, function (err, pids) { + it('should filter pids by single cid', (done) => { + posts.filterPidsByCid([postData.pid, 100, 101], cid, (err, pids) => { assert.ifError(err); assert.deepEqual([postData.pid], pids); done(); }); }); - it('should filter pids by multiple cids', function (done) { - posts.filterPidsByCid([postData.pid, 100, 101], [cid, 2, 3], function (err, pids) { + it('should filter pids by multiple cids', (done) => { + posts.filterPidsByCid([postData.pid, 100, 101], [cid, 2, 3], (err, pids) => { assert.ifError(err); assert.deepEqual([postData.pid], pids); done(); }); }); - it('should filter pids by multiple cids', function (done) { - posts.filterPidsByCid([postData.pid, 100, 101], [cid], function (err, pids) { + it('should filter pids by multiple cids', (done) => { + posts.filterPidsByCid([postData.pid, 100, 101], [cid], (err, pids) => { assert.ifError(err); assert.deepEqual([postData.pid], pids); done(); @@ -1045,35 +1045,35 @@ describe('Post\'s', function () { }); }); - it('should error if user does not exist', function (done) { - user.isReadyToPost(21123123, 1, function (err) { + it('should error if user does not exist', (done) => { + user.isReadyToPost(21123123, 1, (err) => { assert.equal(err.message, '[[error:no-user]]'); done(); }); }); - describe('post queue', function () { + describe('post queue', () => { var uid; var queueId; var topicQueueId; var jar; - before(function (done) { + before((done) => { meta.config.postQueue = 1; - user.create({ username: 'newuser' }, function (err, _uid) { + user.create({ username: 'newuser' }, (err, _uid) => { assert.ifError(err); uid = _uid; done(); }); }); - after(function (done) { + after((done) => { meta.config.postQueue = 0; meta.config.groupsExemptFromPostQueue = []; done(); }); - it('should add topic to post queue', function (done) { - socketTopics.post({ uid: uid }, { title: 'should be queued', content: 'queued topic content', cid: cid }, function (err, result) { + it('should add topic to post queue', (done) => { + socketTopics.post({ uid: uid }, { title: 'should be queued', content: 'queued topic content', cid: cid }, (err, result) => { assert.ifError(err); assert.strictEqual(result.queued, true); assert.equal(result.message, '[[success:post-queued]]'); @@ -1083,8 +1083,8 @@ describe('Post\'s', function () { }); }); - it('should add reply to post queue', function (done) { - socketPosts.reply({ uid: uid }, { content: 'this is a queued reply', tid: topicData.tid }, function (err, result) { + it('should add reply to post queue', (done) => { + socketPosts.reply({ uid: uid }, { content: 'this is a queued reply', tid: topicData.tid }, (err, result) => { assert.ifError(err); assert.strictEqual(result.queued, true); assert.equal(result.message, '[[success:post-queued]]'); @@ -1093,11 +1093,11 @@ describe('Post\'s', function () { }); }); - it('should load queued posts', function (done) { - helpers.loginUser('globalmod', 'globalmodpwd', function (err, _jar) { + it('should load queued posts', (done) => { + helpers.loginUser('globalmod', 'globalmodpwd', (err, _jar) => { jar = _jar; assert.ifError(err); - request(`${nconf.get('url')}/api/post-queue`, { jar: jar, json: true }, function (err, res, body) { + request(`${nconf.get('url')}/api/post-queue`, { jar: jar, json: true }, (err, res, body) => { assert.ifError(err); assert.equal(body.posts[0].type, 'topic'); assert.equal(body.posts[0].data.content, 'queued topic content'); @@ -1108,17 +1108,17 @@ describe('Post\'s', function () { }); }); - it('should error if data is invalid', function (done) { - socketPosts.editQueuedContent({ uid: globalModUid }, null, function (err) { + it('should error if data is invalid', (done) => { + socketPosts.editQueuedContent({ uid: globalModUid }, null, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); }); - it('should edit post in queue', function (done) { - socketPosts.editQueuedContent({ uid: globalModUid }, { id: queueId, content: 'newContent' }, function (err) { + it('should edit post in queue', (done) => { + socketPosts.editQueuedContent({ uid: globalModUid }, { id: queueId, content: 'newContent' }, (err) => { assert.ifError(err); - request(`${nconf.get('url')}/api/post-queue`, { jar: jar, json: true }, function (err, res, body) { + request(`${nconf.get('url')}/api/post-queue`, { jar: jar, json: true }, (err, res, body) => { assert.ifError(err); assert.equal(body.posts[1].type, 'reply'); assert.equal(body.posts[1].data.content, 'newContent'); @@ -1127,10 +1127,10 @@ describe('Post\'s', function () { }); }); - it('should edit topic title in queue', function (done) { - socketPosts.editQueuedContent({ uid: globalModUid }, { id: topicQueueId, title: 'new topic title' }, function (err) { + it('should edit topic title in queue', (done) => { + socketPosts.editQueuedContent({ uid: globalModUid }, { id: topicQueueId, title: 'new topic title' }, (err) => { assert.ifError(err); - request(`${nconf.get('url')}/api/post-queue`, { jar: jar, json: true }, function (err, res, body) { + request(`${nconf.get('url')}/api/post-queue`, { jar: jar, json: true }, (err, res, body) => { assert.ifError(err); assert.equal(body.posts[0].type, 'topic'); assert.equal(body.posts[0].data.title, 'new topic title'); @@ -1139,14 +1139,14 @@ describe('Post\'s', function () { }); }); - it('should edit topic category in queue', function (done) { - socketPosts.editQueuedContent({ uid: globalModUid }, { id: topicQueueId, cid: 2 }, function (err) { + it('should edit topic category in queue', (done) => { + socketPosts.editQueuedContent({ uid: globalModUid }, { id: topicQueueId, cid: 2 }, (err) => { assert.ifError(err); - request(`${nconf.get('url')}/api/post-queue`, { jar: jar, json: true }, function (err, res, body) { + request(`${nconf.get('url')}/api/post-queue`, { jar: jar, json: true }, (err, res, body) => { assert.ifError(err); assert.equal(body.posts[0].type, 'topic'); assert.equal(body.posts[0].data.cid, 2); - socketPosts.editQueuedContent({ uid: globalModUid }, { id: topicQueueId, cid: cid }, function (err) { + socketPosts.editQueuedContent({ uid: globalModUid }, { id: topicQueueId, cid: cid }, (err) => { assert.ifError(err); done(); }); @@ -1154,21 +1154,21 @@ describe('Post\'s', function () { }); }); - it('should prevent regular users from approving posts', function (done) { - socketPosts.accept({ uid: uid }, { id: queueId }, function (err) { + it('should prevent regular users from approving posts', (done) => { + socketPosts.accept({ uid: uid }, { id: queueId }, (err) => { assert.equal(err.message, '[[error:no-privileges]]'); done(); }); }); - it('should prevent regular users from approving non existing posts', function (done) { - socketPosts.accept({ uid: uid }, { id: 123123 }, function (err) { + it('should prevent regular users from approving non existing posts', (done) => { + socketPosts.accept({ uid: uid }, { id: 123123 }, (err) => { assert.equal(err.message, '[[error:no-privileges]]'); done(); }); }); - it('should accept queued posts and submit', function (done) { + it('should accept queued posts and submit', (done) => { var ids; async.waterfall([ function (next) { @@ -1184,16 +1184,16 @@ describe('Post\'s', function () { ], done); }); - it('should not crash if id does not exist', function (done) { - socketPosts.reject({ uid: globalModUid }, { id: '123123123' }, function (err) { + it('should not crash if id does not exist', (done) => { + socketPosts.reject({ uid: globalModUid }, { id: '123123123' }, (err) => { assert.equal(err.message, '[[error:no-privileges]]'); done(); }); }); - it('should bypass post queue if user is in exempt group', function (done) { + it('should bypass post queue if user is in exempt group', (done) => { meta.config.groupsExemptFromPostQueue = ['registered-users']; - socketTopics.post({ uid: uid, emit: () => {} }, { title: 'should not be queued', content: 'topic content', cid: cid }, function (err, result) { + socketTopics.post({ uid: uid, emit: () => {} }, { title: 'should not be queued', content: 'topic content', cid: cid }, (err, result) => { assert.ifError(err); assert.strictEqual(result.title, 'should not be queued'); done(); @@ -1201,7 +1201,7 @@ describe('Post\'s', function () { }); }); - describe('upload methods', function () { + describe('upload methods', () => { let pid; let purgePid; @@ -1227,12 +1227,12 @@ describe('Post\'s', function () { purgePid = purgePostData.postData.pid; }); - describe('.sync()', function () { - it('should properly add new images to the post\'s zset', function (done) { - posts.uploads.sync(pid, function (err) { + describe('.sync()', () => { + it('should properly add new images to the post\'s zset', (done) => { + posts.uploads.sync(pid, (err) => { assert.ifError(err); - db.sortedSetCard(`post:${pid}:uploads`, function (err, length) { + db.sortedSetCard(`post:${pid}:uploads`, (err, length) => { assert.ifError(err); assert.strictEqual(length, 2); done(); @@ -1240,7 +1240,7 @@ describe('Post\'s', function () { }); }); - it('should remove an image if it is edited out of the post', function (done) { + it('should remove an image if it is edited out of the post', (done) => { async.series([ function (next) { posts.edit({ @@ -1250,9 +1250,9 @@ describe('Post\'s', function () { }, next); }, async.apply(posts.uploads.sync, pid), - ], function (err) { + ], (err) => { assert.ifError(err); - db.sortedSetCard(`post:${pid}:uploads`, function (err, length) { + db.sortedSetCard(`post:${pid}:uploads`, (err, length) => { assert.ifError(err); assert.strictEqual(1, length); done(); @@ -1261,9 +1261,9 @@ describe('Post\'s', function () { }); }); - describe('.list()', function () { - it('should display the uploaded files for a specific post', function (done) { - posts.uploads.list(pid, function (err, uploads) { + describe('.list()', () => { + it('should display the uploaded files for a specific post', (done) => { + posts.uploads.list(pid, (err, uploads) => { assert.ifError(err); assert.equal(true, Array.isArray(uploads)); assert.strictEqual(1, uploads.length); @@ -1273,17 +1273,17 @@ describe('Post\'s', function () { }); }); - describe('.isOrphan()', function () { - it('should return false if upload is not an orphan', function (done) { - posts.uploads.isOrphan('abracadabra.png', function (err, isOrphan) { + describe('.isOrphan()', () => { + it('should return false if upload is not an orphan', (done) => { + posts.uploads.isOrphan('abracadabra.png', (err, isOrphan) => { assert.ifError(err); assert.equal(false, isOrphan); done(); }); }); - it('should return true if upload is an orphan', function (done) { - posts.uploads.isOrphan('shazam.jpg', function (err, isOrphan) { + it('should return true if upload is an orphan', (done) => { + posts.uploads.isOrphan('shazam.jpg', (err, isOrphan) => { assert.ifError(err); assert.equal(true, isOrphan); done(); @@ -1291,12 +1291,12 @@ describe('Post\'s', function () { }); }); - describe('.associate()', function () { - it('should add an image to the post\'s maintained list of uploads', function (done) { + describe('.associate()', () => { + it('should add an image to the post\'s maintained list of uploads', (done) => { async.waterfall([ async.apply(posts.uploads.associate, pid, 'whoa.gif'), async.apply(posts.uploads.list, pid), - ], function (err, uploads) { + ], (err, uploads) => { assert.ifError(err); assert.strictEqual(2, uploads.length); assert.strictEqual(true, uploads.includes('whoa.gif')); @@ -1304,11 +1304,11 @@ describe('Post\'s', function () { }); }); - it('should allow arrays to be passed in', function (done) { + it('should allow arrays to be passed in', (done) => { async.waterfall([ async.apply(posts.uploads.associate, pid, ['amazeballs.jpg', 'wut.txt']), async.apply(posts.uploads.list, pid), - ], function (err, uploads) { + ], (err, uploads) => { assert.ifError(err); assert.strictEqual(4, uploads.length); assert.strictEqual(true, uploads.includes('amazeballs.jpg')); @@ -1317,7 +1317,7 @@ describe('Post\'s', function () { }); }); - it('should save a reverse association of md5sum to pid', function (done) { + it('should save a reverse association of md5sum to pid', (done) => { const md5 = filename => crypto.createHash('md5').update(filename).digest('hex'); async.waterfall([ @@ -1325,7 +1325,7 @@ describe('Post\'s', function () { function (next) { db.getSortedSetRange(`upload:${md5('test.bmp')}:pids`, 0, -1, next); }, - ], function (err, pids) { + ], (err, pids) => { assert.ifError(err); assert.strictEqual(true, Array.isArray(pids)); assert.strictEqual(true, pids.length > 0); @@ -1334,11 +1334,11 @@ describe('Post\'s', function () { }); }); - it('should not associate a file that does not exist on the local disk', function (done) { + it('should not associate a file that does not exist on the local disk', (done) => { async.waterfall([ async.apply(posts.uploads.associate, pid, ['nonexistant.xls']), async.apply(posts.uploads.list, pid), - ], function (err, uploads) { + ], (err, uploads) => { assert.ifError(err); assert.strictEqual(uploads.length, 5); assert.strictEqual(false, uploads.includes('nonexistant.xls')); @@ -1347,12 +1347,12 @@ describe('Post\'s', function () { }); }); - describe('.dissociate()', function () { - it('should remove an image from the post\'s maintained list of uploads', function (done) { + describe('.dissociate()', () => { + it('should remove an image from the post\'s maintained list of uploads', (done) => { async.waterfall([ async.apply(posts.uploads.dissociate, pid, 'whoa.gif'), async.apply(posts.uploads.list, pid), - ], function (err, uploads) { + ], (err, uploads) => { assert.ifError(err); assert.strictEqual(4, uploads.length); assert.strictEqual(false, uploads.includes('whoa.gif')); @@ -1360,11 +1360,11 @@ describe('Post\'s', function () { }); }); - it('should allow arrays to be passed in', function (done) { + it('should allow arrays to be passed in', (done) => { async.waterfall([ async.apply(posts.uploads.dissociate, pid, ['amazeballs.jpg', 'wut.txt']), async.apply(posts.uploads.list, pid), - ], function (err, uploads) { + ], (err, uploads) => { assert.ifError(err); assert.strictEqual(2, uploads.length); assert.strictEqual(false, uploads.includes('amazeballs.jpg')); @@ -1400,23 +1400,23 @@ describe('Post\'s', function () { }); }); - describe('post uploads management', function () { + describe('post uploads management', () => { let topic; let reply; - before(function (done) { + before((done) => { topics.post({ uid: 1, cid: cid, title: 'topic to test uploads with', content: '[abcdef](/assets/uploads/files/abracadabra.png)', - }, function (err, topicPostData) { + }, (err, topicPostData) => { assert.ifError(err); topics.reply({ uid: 1, tid: topicPostData.topicData.tid, timestamp: Date.now(), content: '[abcdef](/assets/uploads/files/shazam.jpg)', - }, function (err, replyData) { + }, (err, replyData) => { assert.ifError(err); topic = topicPostData; reply = replyData; @@ -1425,8 +1425,8 @@ describe('Post\'s', function () { }); }); - it('should automatically sync uploads on topic create and reply', function (done) { - db.sortedSetsCard([`post:${topic.topicData.mainPid}:uploads`, `post:${reply.pid}:uploads`], function (err, lengths) { + it('should automatically sync uploads on topic create and reply', (done) => { + db.sortedSetsCard([`post:${topic.topicData.mainPid}:uploads`, `post:${reply.pid}:uploads`], (err, lengths) => { assert.ifError(err); assert.strictEqual(1, lengths[0]); assert.strictEqual(1, lengths[1]); @@ -1434,7 +1434,7 @@ describe('Post\'s', function () { }); }); - it('should automatically sync uploads on post edit', function (done) { + it('should automatically sync uploads on post edit', (done) => { async.waterfall([ async.apply(posts.edit, { pid: reply.pid, @@ -1444,7 +1444,7 @@ describe('Post\'s', function () { function (postData, next) { posts.uploads.list(reply.pid, next); }, - ], function (err, uploads) { + ], (err, uploads) => { assert.ifError(err); assert.strictEqual(true, Array.isArray(uploads)); assert.strictEqual(0, uploads.length); diff --git a/test/pubsub.js b/test/pubsub.js index 9a18c4a4c2..512dd3bd85 100644 --- a/test/pubsub.js +++ b/test/pubsub.js @@ -6,11 +6,11 @@ var nconf = require('nconf'); var db = require('./mocks/databasemock'); var pubsub = require('../src/pubsub'); -describe('pubsub', function () { - it('should use the plain event emitter', function (done) { +describe('pubsub', () => { + it('should use the plain event emitter', (done) => { nconf.set('isCluster', false); pubsub.reset(); - pubsub.on('testEvent', function (message) { + pubsub.on('testEvent', (message) => { assert.equal(message.foo, 1); pubsub.removeAllListeners('testEvent'); done(); @@ -18,8 +18,8 @@ describe('pubsub', function () { pubsub.publish('testEvent', { foo: 1 }); }); - it('should use same event emitter', function (done) { - pubsub.on('dummyEvent', function (message) { + it('should use same event emitter', (done) => { + pubsub.on('dummyEvent', (message) => { assert.equal(message.foo, 2); pubsub.removeAllListeners('dummyEvent'); pubsub.reset(); @@ -28,10 +28,10 @@ describe('pubsub', function () { pubsub.publish('dummyEvent', { foo: 2 }); }); - it('should use singleHostCluster', function (done) { + it('should use singleHostCluster', (done) => { var oldValue = nconf.get('singleHostCluster'); nconf.set('singleHostCluster', true); - pubsub.on('testEvent', function (message) { + pubsub.on('testEvent', (message) => { assert.equal(message.foo, 3); nconf.set('singleHostCluster', oldValue); pubsub.removeAllListeners('testEvent'); @@ -40,9 +40,9 @@ describe('pubsub', function () { pubsub.publish('testEvent', { foo: 3 }); }); - it('should use same event emitter', function (done) { + it('should use same event emitter', (done) => { var oldValue = nconf.get('singleHostCluster'); - pubsub.on('dummyEvent', function (message) { + pubsub.on('dummyEvent', (message) => { assert.equal(message.foo, 4); nconf.set('singleHostCluster', oldValue); pubsub.removeAllListeners('dummyEvent'); diff --git a/test/rewards.js b/test/rewards.js index bd693ecbc1..5ca090188f 100644 --- a/test/rewards.js +++ b/test/rewards.js @@ -8,18 +8,18 @@ var meta = require('../src/meta'); var User = require('../src/user'); var Groups = require('../src/groups'); -describe('rewards', function () { +describe('rewards', () => { var adminUid; var bazUid; var herpUid; - before(function (done) { + before((done) => { // Create 3 users: 1 admin, 2 regular async.series([ async.apply(User.create, { username: 'foo' }), async.apply(User.create, { username: 'baz' }), async.apply(User.create, { username: 'herp' }), - ], function (err, uids) { + ], (err, uids) => { if (err) { return done(err); } @@ -39,10 +39,10 @@ describe('rewards', function () { }); }); - describe('rewards create', function () { + describe('rewards create', () => { var socketAdmin = require('../src/socket.io/admin'); var rewards = require('../src/rewards'); - it('it should save a reward', function (done) { + it('it should save a reward', (done) => { var data = [ { rewards: { groupname: 'Gamers' }, @@ -56,13 +56,13 @@ describe('rewards', function () { }, ]; - socketAdmin.rewards.save({ uid: adminUid }, data, function (err) { + socketAdmin.rewards.save({ uid: adminUid }, data, (err) => { assert.ifError(err); done(); }); }); - it('should check condition', function (done) { + it('should check condition', (done) => { function method(next) { next(null, 1); } @@ -70,7 +70,7 @@ describe('rewards', function () { uid: adminUid, condition: 'essentials/user.postcount', method: method, - }, function (err, data) { + }, (err, data) => { assert.ifError(err); done(); }); diff --git a/test/search-admin.js b/test/search-admin.js index 3c2620dfc1..ec4163c9e1 100644 --- a/test/search-admin.js +++ b/test/search-admin.js @@ -4,9 +4,9 @@ var assert = require('assert'); var search = require('../src/admin/search'); -describe('admin search', function () { - describe('filterDirectories', function () { - it('should resolve all paths to relative paths', function (done) { +describe('admin search', () => { + describe('filterDirectories', () => { + it('should resolve all paths to relative paths', (done) => { assert.deepEqual(search.filterDirectories([ 'hfjksfd/fdsgagag/admin/gdhgfsdg/sggag.tpl', ]), [ @@ -14,7 +14,7 @@ describe('admin search', function () { ]); done(); }); - it('should exclude .js files', function (done) { + it('should exclude .js files', (done) => { assert.deepEqual(search.filterDirectories([ 'hfjksfd/fdsgagag/admin/gdhgfsdg/sggag.tpl', 'dfahdfsgf/admin/hgkfds/fdhsdfh.js', @@ -23,7 +23,7 @@ describe('admin search', function () { ]); done(); }); - it('should exclude partials', function (done) { + it('should exclude partials', (done) => { assert.deepEqual(search.filterDirectories([ 'hfjksfd/fdsgagag/admin/gdhgfsdg/sggag.tpl', 'dfahdfsgf/admin/partials/hgkfds/fdhsdfh.tpl', @@ -32,7 +32,7 @@ describe('admin search', function () { ]); done(); }); - it('should exclude files in the admin directory', function (done) { + it('should exclude files in the admin directory', (done) => { assert.deepEqual(search.filterDirectories([ 'hfjksfd/fdsgagag/admin/gdhgfsdg/sggag.tpl', 'dfdasg/admin/hjkdfsk.tpl', @@ -43,8 +43,8 @@ describe('admin search', function () { }); }); - describe('sanitize', function () { - it('should strip out scripts', function (done) { + describe('sanitize', () => { + it('should strip out scripts', (done) => { assert.equal( search.sanitize('Pellentesque tristique senectus' + ' habitant morbi'), @@ -53,7 +53,7 @@ describe('admin search', function () { ); done(); }); - it('should remove all tags', function (done) { + it('should remove all tags', (done) => { assert.equal( search.sanitize('Pellentesque habitant morbi tristique senectus' + 'Aenean vitae est.Mauris eleifend leo.'), @@ -64,8 +64,8 @@ describe('admin search', function () { }); }); - describe('simplify', function () { - it('should remove all mustaches', function (done) { + describe('simplify', () => { + it('should remove all mustaches', (done) => { assert.equal( search.simplify('Pellentesque tristique {{senectus}}habitant morbi' + 'liquam tincidunt {mauris.eu}risus'), @@ -74,7 +74,7 @@ describe('admin search', function () { ); done(); }); - it('should collapse all whitespace', function (done) { + it('should collapse all whitespace', (done) => { assert.equal( search.simplify('Pellentesque tristique habitant morbi' + ' \n\n liquam tincidunt mauris eu risus.'), diff --git a/test/search.js b/test/search.js index 6c2c690674..880695a4b4 100644 --- a/test/search.js +++ b/test/search.js @@ -13,7 +13,7 @@ var user = require('../src/user'); var search = require('../src/search'); var privileges = require('../src/privileges'); -describe('Search', function () { +describe('Search', () => { var phoebeUid; var gingerUid; @@ -26,7 +26,7 @@ describe('Search', function () { var cid2; var cid3; - before(function (done) { + before((done) => { async.waterfall([ function (next) { async.series({ @@ -104,15 +104,15 @@ describe('Search', function () { ], done); }); - it('should search term in titles and posts', function (done) { + it('should search term in titles and posts', (done) => { var meta = require('../src/meta'); var qs = `/api/search?term=cucumber&in=titlesposts&categories[]=${cid1}&by=phoebe&replies=1&repliesFilter=atleast&sortBy=timestamp&sortDirection=desc&showAs=posts`; - privileges.global.give(['groups:search:content'], 'guests', function (err) { + privileges.global.give(['groups:search:content'], 'guests', (err) => { assert.ifError(err); request({ url: nconf.get('url') + qs, json: true, - }, function (err, response, body) { + }, (err, response, body) => { assert.ifError(err); assert(body); assert.equal(body.matchCount, 1); @@ -125,11 +125,11 @@ describe('Search', function () { }); }); - it('should search for a user', function (done) { + it('should search for a user', (done) => { search.search({ query: 'gin', searchIn: 'users', - }, function (err, data) { + }, (err, data) => { assert.ifError(err); assert(data); assert.equal(data.matchCount, 1); @@ -140,11 +140,11 @@ describe('Search', function () { }); }); - it('should search for a tag', function (done) { + it('should search for a tag', (done) => { search.search({ query: 'plug', searchIn: 'tags', - }, function (err, data) { + }, (err, data) => { assert.ifError(err); assert(data); assert.equal(data.matchCount, 1); @@ -155,43 +155,43 @@ describe('Search', function () { }); }); - it('should fail if searchIn is wrong', function (done) { + it('should fail if searchIn is wrong', (done) => { search.search({ query: 'plug', searchIn: 'invalidfilter', - }, function (err) { + }, (err) => { assert.equal(err.message, '[[error:unknown-search-filter]]'); done(); }); }); - it('should search with tags filter', function (done) { + it('should search with tags filter', (done) => { search.search({ query: 'mongodb', searchIn: 'titles', hasTags: ['nodebb', 'javascript'], - }, function (err, data) { + }, (err, data) => { assert.ifError(err); assert.equal(data.posts[0].tid, topic2Data.tid); done(); }); }); - it('should not crash if tags is not an array', function (done) { + it('should not crash if tags is not an array', (done) => { search.search({ query: 'mongodb', searchIn: 'titles', hasTags: 'nodebb,javascript', - }, function (err, data) { + }, (err, data) => { assert.ifError(err); done(); }); }); - it('should not find anything', function (done) { + it('should not find anything', (done) => { search.search({ query: 'xxxxxxxxxxxxxx', - }, function (err, data) { + }, (err, data) => { assert.ifError(err); assert(Array.isArray(data.posts)); assert(!data.matchCount); @@ -199,7 +199,7 @@ describe('Search', function () { }); }); - it('should search child categories', function (done) { + it('should search child categories', (done) => { async.waterfall([ function (next) { topics.post({ @@ -228,14 +228,14 @@ describe('Search', function () { ], done); }); - it('should return json search data with no categories', function (done) { + it('should return json search data with no categories', (done) => { var qs = '/api/search?term=cucumber&in=titlesposts&searchOnly=1'; - privileges.global.give(['groups:search:content'], 'guests', function (err) { + privileges.global.give(['groups:search:content'], 'guests', (err) => { assert.ifError(err); request({ url: nconf.get('url') + qs, json: true, - }, function (err, response, body) { + }, (err, response, body) => { assert.ifError(err); assert(body); assert(body.hasOwnProperty('matchCount')); diff --git a/test/settings.js b/test/settings.js index c9d29953b5..6f58dd020b 100644 --- a/test/settings.js +++ b/test/settings.js @@ -6,44 +6,44 @@ var nconf = require('nconf'); var db = require('./mocks/databasemock'); var settings = require('../src/settings'); -describe('settings v3', function () { +describe('settings v3', () => { var settings1; var settings2; - it('should create a new settings object', function (done) { + it('should create a new settings object', (done) => { settings1 = new settings('my-plugin', '1.0', { foo: 1, bar: { derp: 2 } }, done); }); - it('should get the saved settings ', function (done) { + it('should get the saved settings ', (done) => { assert.equal(settings1.get('foo'), 1); assert.equal(settings1.get('bar.derp'), 2); done(); }); - it('should create a new settings instance for same key', function (done) { + it('should create a new settings instance for same key', (done) => { settings2 = new settings('my-plugin', '1.0', { foo: 1, bar: { derp: 2 } }, done); }); - it('should pass change between settings object over pubsub', function (done) { + it('should pass change between settings object over pubsub', (done) => { settings1.set('foo', 3); - settings1.persist(function (err) { + settings1.persist((err) => { assert.ifError(err); // give pubsub time to complete - setTimeout(function () { + setTimeout(() => { assert.equal(settings2.get('foo'), 3); done(); }, 500); }); }); - it('should set a nested value', function (done) { + it('should set a nested value', (done) => { settings1.set('bar.derp', 5); assert.equal(settings1.get('bar.derp'), 5); done(); }); - it('should reset the settings to default', function (done) { - settings1.reset(function (err) { + it('should reset the settings to default', (done) => { + settings1.reset((err) => { assert.ifError(err); assert.equal(settings1.get('foo'), 1); assert.equal(settings1.get('bar.derp'), 2); @@ -51,7 +51,7 @@ describe('settings v3', function () { }); }); - it('should get value from default value', function (done) { + it('should get value from default value', (done) => { var newSettings = new settings('some-plugin', '1.0', { default: { value: 1 } }); assert.equal(newSettings.get('default.value'), 1); done(); diff --git a/test/socket.io.js b/test/socket.io.js index 679dec1ba2..5b537db991 100644 --- a/test/socket.io.js +++ b/test/socket.io.js @@ -25,14 +25,14 @@ const events = require('../src/events'); var socketAdmin = require('../src/socket.io/admin'); -describe('socket.io', function () { +describe('socket.io', () => { var io; var cid; var tid; var adminUid; var regularUid; - before(function (done) { + before((done) => { async.series([ async.apply(user.create, { username: 'admin', password: 'adminpwd' }), async.apply(user.create, { username: 'regular', password: 'regularpwd', email: 'regular@test.com' }), @@ -40,7 +40,7 @@ describe('socket.io', function () { name: 'Test Category', description: 'Test category created by testing script', }), - ], function (err, data) { + ], (err, data) => { if (err) { return done(err); } @@ -53,12 +53,12 @@ describe('socket.io', function () { }); - it('should connect and auth properly', function (done) { + it('should connect and auth properly', (done) => { request.get({ url: `${nconf.get('url')}/api/config`, jar: cookies, json: true, - }, function (err, res, body) { + }, (err, res, body) => { assert.ifError(err); request.post(`${nconf.get('url')}/login`, { @@ -71,10 +71,10 @@ describe('socket.io', function () { 'x-csrf-token': body.csrf_token, }, json: true, - }, function (err, res) { + }, (err, res) => { assert.ifError(err); - helpers.connectSocketIO(res, function (err, _io) { + helpers.connectSocketIO(res, (err, _io) => { io = _io; assert.ifError(err); @@ -84,31 +84,29 @@ describe('socket.io', function () { }); }); - it('should return error for unknown event', function (done) { - io.emit('unknown.event', function (err) { + it('should return error for unknown event', (done) => { + io.emit('unknown.event', (err) => { assert(err); assert.equal(err.message, '[[error:invalid-event]]'); done(); }); }); - it('should get installed themes', function (done) { + it('should get installed themes', (done) => { var themes = ['nodebb-theme-lavender', 'nodebb-theme-persona', 'nodebb-theme-vanilla']; - io.emit('admin.themes.getInstalled', function (err, data) { + io.emit('admin.themes.getInstalled', (err, data) => { assert.ifError(err); assert(data); - var installed = data.map(function (theme) { - return theme.id; - }); - themes.forEach(function (theme) { + var installed = data.map(theme => theme.id); + themes.forEach((theme) => { assert.notEqual(installed.indexOf(theme), -1); }); done(); }); }); - it('should post a topic', function (done) { - io.emit('topics.post', { title: 'test topic title', content: 'test topic main post content', uid: adminUid, cid: cid }, function (err, result) { + it('should post a topic', (done) => { + io.emit('topics.post', { title: 'test topic title', content: 'test topic main post content', uid: adminUid, cid: cid }, (err, result) => { assert.ifError(err); assert.equal(result.user.username, 'admin'); assert.equal(result.category.cid, cid); @@ -118,8 +116,8 @@ describe('socket.io', function () { }); }); - it('should reply to topic', function (done) { - io.emit('posts.reply', { tid: tid, uid: adminUid, content: 'test post content' }, function (err, result) { + it('should reply to topic', (done) => { + io.emit('posts.reply', { tid: tid, uid: adminUid, content: 'test post content' }, (err, result) => { assert.ifError(err); assert.equal(result.uid, adminUid); assert.equal(result.user.username, 'admin'); @@ -128,19 +126,19 @@ describe('socket.io', function () { }); }); - it('should get more unread topics', function (done) { - io.emit('topics.loadMoreSortedTopics', { after: 0, count: 10, direction: 1, sort: 'unread' }, function (err, result) { + it('should get more unread topics', (done) => { + io.emit('topics.loadMoreSortedTopics', { after: 0, count: 10, direction: 1, sort: 'unread' }, (err, result) => { assert.ifError(err); assert(Array.isArray(result.topics)); done(); }); }); - it('should ban a user', function (done) { + it('should ban a user', (done) => { var socketUser = require('../src/socket.io/user'); - socketUser.banUsers({ uid: adminUid }, { uids: [regularUid], reason: 'spammer' }, function (err) { + socketUser.banUsers({ uid: adminUid }, { uids: [regularUid], reason: 'spammer' }, (err) => { assert.ifError(err); - user.getLatestBanInfo(regularUid, function (err, data) { + user.getLatestBanInfo(regularUid, (err, data) => { assert.ifError(err); assert(data.uid); assert(data.timestamp); @@ -152,19 +150,19 @@ describe('socket.io', function () { }); }); - it('should return ban reason', function (done) { - user.bans.getReason(regularUid, function (err, reason) { + it('should return ban reason', (done) => { + user.bans.getReason(regularUid, (err, reason) => { assert.ifError(err); assert.equal(reason, 'spammer'); done(); }); }); - it('should unban a user', function (done) { + it('should unban a user', (done) => { var socketUser = require('../src/socket.io/user'); - socketUser.unbanUsers({ uid: adminUid }, [regularUid], function (err) { + socketUser.unbanUsers({ uid: adminUid }, [regularUid], (err) => { assert.ifError(err); - user.bans.isBanned(regularUid, function (err, isBanned) { + user.bans.isBanned(regularUid, (err, isBanned) => { assert.ifError(err); assert(!isBanned); done(); @@ -172,10 +170,10 @@ describe('socket.io', function () { }); }); - it('should make user admin', function (done) { - socketAdmin.user.makeAdmins({ uid: adminUid }, [regularUid], function (err) { + it('should make user admin', (done) => { + socketAdmin.user.makeAdmins({ uid: adminUid }, [regularUid], (err) => { assert.ifError(err); - groups.isMember(regularUid, 'administrators', function (err, isMember) { + groups.isMember(regularUid, 'administrators', (err, isMember) => { assert.ifError(err); assert(isMember); done(); @@ -183,10 +181,10 @@ describe('socket.io', function () { }); }); - it('should make user non-admin', function (done) { - socketAdmin.user.removeAdmins({ uid: adminUid }, [regularUid], function (err) { + it('should make user non-admin', (done) => { + socketAdmin.user.removeAdmins({ uid: adminUid }, [regularUid], (err) => { assert.ifError(err); - groups.isMember(regularUid, 'administrators', function (err, isMember) { + groups.isMember(regularUid, 'administrators', (err, isMember) => { assert.ifError(err); assert(!isMember); done(); @@ -194,30 +192,30 @@ describe('socket.io', function () { }); }); - describe('user create/delete', function () { + describe('user create/delete', () => { let uid; - it('should create a user', async function () { + it('should create a user', async () => { const userData = await socketAdmin.user.createUser({ uid: adminUid }, { username: 'foo1' }); uid = userData.uid; const isMember = await groups.isMember(userData.uid, 'registered-users'); assert(isMember); }); - it('should delete users', async function () { + it('should delete users', async () => { await socketAdmin.user.deleteUsers({ uid: adminUid }, [uid]); await sleep(500); const isMember = await groups.isMember(uid, 'registered-users'); assert(!isMember); }); - it('should error if user does not exist', function (done) { - socketAdmin.user.deleteUsersAndContent({ uid: adminUid }, [uid], function (err) { + it('should error if user does not exist', (done) => { + socketAdmin.user.deleteUsersAndContent({ uid: adminUid }, [uid], (err) => { assert.strictEqual(err.message, '[[error:no-user]]'); done(); }); }); - it('should delete users and their content', async function () { + it('should delete users and their content', async () => { const userData = await socketAdmin.user.createUser({ uid: adminUid }, { username: 'foo2' }); await socketAdmin.user.deleteUsersAndContent({ uid: adminUid }, [userData.uid]); await sleep(500); @@ -226,42 +224,42 @@ describe('socket.io', function () { }); }); - it('should error with invalid data', function (done) { - socketAdmin.user.createUser({ uid: adminUid }, null, function (err) { + it('should error with invalid data', (done) => { + socketAdmin.user.createUser({ uid: adminUid }, null, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); }); - it('should reset lockouts', function (done) { - socketAdmin.user.resetLockouts({ uid: adminUid }, [regularUid], function (err) { + it('should reset lockouts', (done) => { + socketAdmin.user.resetLockouts({ uid: adminUid }, [regularUid], (err) => { assert.ifError(err); done(); }); }); - describe('validation emails', function () { + describe('validation emails', () => { var meta = require('../src/meta'); var plugins = require('../src/plugins'); async function dummyEmailerHook(data) { // pretend to handle sending emails } - before(function () { + before(() => { // Attach an emailer hook so related requests do not error plugins.hooks.register('emailer-test', { hook: 'filter:email.send', method: dummyEmailerHook, }); }); - after(function () { + after(() => { plugins.hooks.unregister('emailer-test', 'filter:email.send'); }); - it('should validate emails', function (done) { - socketAdmin.user.validateEmail({ uid: adminUid }, [regularUid], function (err) { + it('should validate emails', (done) => { + socketAdmin.user.validateEmail({ uid: adminUid }, [regularUid], (err) => { assert.ifError(err); - user.getUserField(regularUid, 'email:confirmed', function (err, emailConfirmed) { + user.getUserField(regularUid, 'email:confirmed', (err, emailConfirmed) => { assert.ifError(err); assert.equal(parseInt(emailConfirmed, 10), 1); done(); @@ -269,23 +267,23 @@ describe('socket.io', function () { }); }); - it('should error with invalid uids', function (done) { - socketAdmin.user.sendValidationEmail({ uid: adminUid }, null, function (err) { + it('should error with invalid uids', (done) => { + socketAdmin.user.sendValidationEmail({ uid: adminUid }, null, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); }); - it('should error if email validation is not required', function (done) { - socketAdmin.user.sendValidationEmail({ uid: adminUid }, [regularUid], function (err) { + it('should error if email validation is not required', (done) => { + socketAdmin.user.sendValidationEmail({ uid: adminUid }, [regularUid], (err) => { assert.equal(err.message, '[[error:email-confirmations-are-disabled]]'); done(); }); }); - it('should send validation email', function (done) { + it('should send validation email', (done) => { meta.config.requireEmailConfirmation = 1; - socketAdmin.user.sendValidationEmail({ uid: adminUid }, [regularUid], function (err) { + socketAdmin.user.sendValidationEmail({ uid: adminUid }, [regularUid], (err) => { assert.ifError(err); meta.config.requireEmailConfirmation = 0; done(); @@ -293,61 +291,61 @@ describe('socket.io', function () { }); }); - it('should push unread notifications on reconnect', function (done) { + it('should push unread notifications on reconnect', (done) => { var socketMeta = require('../src/socket.io/meta'); - socketMeta.reconnected({ uid: 1 }, {}, function (err) { + socketMeta.reconnected({ uid: 1 }, {}, (err) => { assert.ifError(err); done(); }); }); - it('should error if the room is missing', function (done) { - io.emit('meta.rooms.enter', null, function (err) { + it('should error if the room is missing', (done) => { + io.emit('meta.rooms.enter', null, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); }); - it('should return if uid is 0', function (done) { + it('should return if uid is 0', (done) => { var socketMeta = require('../src/socket.io/meta'); - socketMeta.rooms.enter({ uid: 0 }, null, function (err) { + socketMeta.rooms.enter({ uid: 0 }, null, (err) => { assert.ifError(err); done(); }); }); - it('should join a room', function (done) { - io.emit('meta.rooms.enter', { enter: 'recent_topics' }, function (err) { + it('should join a room', (done) => { + io.emit('meta.rooms.enter', { enter: 'recent_topics' }, (err) => { assert.ifError(err); done(); }); }); - it('should leave current room', function (done) { - io.emit('meta.rooms.leaveCurrent', {}, function (err) { + it('should leave current room', (done) => { + io.emit('meta.rooms.leaveCurrent', {}, (err) => { assert.ifError(err); done(); }); }); - it('should get server time', function (done) { - io.emit('admin.getServerTime', null, function (err, time) { + it('should get server time', (done) => { + io.emit('admin.getServerTime', null, (err, time) => { assert.ifError(err); assert(time); done(); }); }); - it('should error to get daily analytics with invalid data', function (done) { - io.emit('admin.analytics.get', null, function (err) { + it('should error to get daily analytics with invalid data', (done) => { + io.emit('admin.analytics.get', null, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); }); - it('should get daily analytics', function (done) { - io.emit('admin.analytics.get', { graph: 'traffic', units: 'days' }, function (err, data) { + it('should get daily analytics', (done) => { + io.emit('admin.analytics.get', { graph: 'traffic', units: 'days' }, (err, data) => { assert.ifError(err); assert(data); assert(data.summary); @@ -355,8 +353,8 @@ describe('socket.io', function () { }); }); - it('should get hourly analytics', function (done) { - io.emit('admin.analytics.get', { graph: 'traffic', units: 'hours' }, function (err, data) { + it('should get hourly analytics', (done) => { + io.emit('admin.analytics.get', { graph: 'traffic', units: 'hours' }, (err, data) => { assert.ifError(err); assert(data); assert(data.summary); @@ -364,8 +362,8 @@ describe('socket.io', function () { }); }); - it('should allow a custom date range for traffic graph analytics', function (done) { - io.emit('admin.analytics.get', { graph: 'traffic', units: 'days', amount: '7' }, function (err, data) { + it('should allow a custom date range for traffic graph analytics', (done) => { + io.emit('admin.analytics.get', { graph: 'traffic', units: 'days', amount: '7' }, (err, data) => { assert.ifError(err); assert(data); assert(data.pageviews); @@ -376,20 +374,20 @@ describe('socket.io', function () { }); }); - it('should return error', function (done) { - socketAdmin.before({ uid: 10 }, 'someMethod', {}, function (err) { + it('should return error', (done) => { + socketAdmin.before({ uid: 10 }, 'someMethod', {}, (err) => { assert.equal(err.message, '[[error:no-privileges]]'); done(); }); }); - it('should get room stats', function (done) { - io.emit('meta.rooms.enter', { enter: 'topic_1' }, function (err) { + it('should get room stats', (done) => { + io.emit('meta.rooms.enter', { enter: 'topic_1' }, (err) => { assert.ifError(err); - socketAdmin.rooms.getAll({ uid: 10 }, {}, function (err) { + socketAdmin.rooms.getAll({ uid: 10 }, {}, (err) => { assert.ifError(err); - setTimeout(function () { - socketAdmin.rooms.getAll({ uid: 10 }, {}, function (err, data) { + setTimeout(() => { + socketAdmin.rooms.getAll({ uid: 10 }, {}, (err, data) => { assert.ifError(err); assert(data.hasOwnProperty('onlineGuestCount')); assert(data.hasOwnProperty('onlineRegisteredCount')); @@ -403,13 +401,13 @@ describe('socket.io', function () { }); }); - it('should get room stats', function (done) { - io.emit('meta.rooms.enter', { enter: 'category_1' }, function (err) { + it('should get room stats', (done) => { + io.emit('meta.rooms.enter', { enter: 'category_1' }, (err) => { assert.ifError(err); - socketAdmin.rooms.getAll({ uid: 10 }, {}, function (err) { + socketAdmin.rooms.getAll({ uid: 10 }, {}, (err) => { assert.ifError(err); - setTimeout(function () { - socketAdmin.rooms.getAll({ uid: 10 }, {}, function (err, data) { + setTimeout(() => { + socketAdmin.rooms.getAll({ uid: 10 }, {}, (err, data) => { assert.ifError(err); assert.equal(data.users.category, 1, JSON.stringify(data, null, 4)); done(); @@ -419,8 +417,8 @@ describe('socket.io', function () { }); }); - it('should get admin search dictionary', function (done) { - socketAdmin.getSearchDict({ uid: adminUid }, {}, function (err, data) { + it('should get admin search dictionary', (done) => { + socketAdmin.getSearchDict({ uid: adminUid }, {}, (err, data) => { assert.ifError(err); assert(Array.isArray(data)); assert(data[0].namespace); @@ -430,31 +428,31 @@ describe('socket.io', function () { }); }); - it('should fire event', function (done) { - io.on('testEvent', function (data) { + it('should fire event', (done) => { + io.on('testEvent', (data) => { assert.equal(data.foo, 1); done(); }); - socketAdmin.fireEvent({ uid: adminUid }, { name: 'testEvent', payload: { foo: 1 } }, function (err) { + socketAdmin.fireEvent({ uid: adminUid }, { name: 'testEvent', payload: { foo: 1 } }, (err) => { assert.ifError(err); }); }); - it('should error with invalid data', function (done) { - socketAdmin.themes.set({ uid: adminUid }, null, function (err) { + it('should error with invalid data', (done) => { + socketAdmin.themes.set({ uid: adminUid }, null, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); }); - it('should set theme to bootswatch', function (done) { + it('should set theme to bootswatch', (done) => { socketAdmin.themes.set({ uid: adminUid }, { type: 'bootswatch', src: '//maxcdn.bootstrapcdn.com/bootswatch/latest/darkly/bootstrap.min.css', id: 'darkly', - }, function (err) { + }, (err) => { assert.ifError(err); - meta.configs.getFields(['theme:src', 'bootswatchSkin'], function (err, fields) { + meta.configs.getFields(['theme:src', 'bootswatchSkin'], (err, fields) => { assert.ifError(err); assert.equal(fields['theme:src'], '//maxcdn.bootstrapcdn.com/bootswatch/latest/darkly/bootstrap.min.css'); assert.equal(fields.bootswatchSkin, 'darkly'); @@ -463,10 +461,10 @@ describe('socket.io', function () { }); }); - it('should set theme to local persona', function (done) { - socketAdmin.themes.set({ uid: adminUid }, { type: 'local', id: 'nodebb-theme-persona' }, function (err) { + it('should set theme to local persona', (done) => { + socketAdmin.themes.set({ uid: adminUid }, { type: 'local', id: 'nodebb-theme-persona' }, (err) => { assert.ifError(err); - meta.configs.get('theme:id', function (err, id) { + meta.configs.get('theme:id', (err, id) => { assert.ifError(err); assert.equal(id, 'nodebb-theme-persona'); done(); @@ -474,8 +472,8 @@ describe('socket.io', function () { }); }); - it('should toggle plugin active', function (done) { - socketAdmin.plugins.toggleActive({ uid: adminUid }, 'nodebb-plugin-location-to-map', function (err, data) { + it('should toggle plugin active', (done) => { + socketAdmin.plugins.toggleActive({ uid: adminUid }, 'nodebb-plugin-location-to-map', (err, data) => { assert.ifError(err); assert.deepEqual(data, { id: 'nodebb-plugin-location-to-map', active: true }); done(); @@ -484,31 +482,31 @@ describe('socket.io', function () { it('should toggle plugin install', function (done) { this.timeout(0); - socketAdmin.plugins.toggleInstall({ uid: adminUid }, { id: 'nodebb-plugin-location-to-map', version: 'latest' }, function (err, data) { + socketAdmin.plugins.toggleInstall({ uid: adminUid }, { id: 'nodebb-plugin-location-to-map', version: 'latest' }, (err, data) => { assert.ifError(err); assert.equal(data.name, 'nodebb-plugin-location-to-map'); done(); }); }); - it('should get list of active plugins', function (done) { - socketAdmin.plugins.getActive({ uid: adminUid }, {}, function (err, data) { + it('should get list of active plugins', (done) => { + socketAdmin.plugins.getActive({ uid: adminUid }, {}, (err, data) => { assert.ifError(err); assert(Array.isArray(data)); done(); }); }); - it('should order active plugins', function (done) { + it('should order active plugins', (done) => { var data = [ { name: 'nodebb-theme-persona', order: 0 }, { name: 'nodebb-plugin-dbsearch', order: 1 }, { name: 'nodebb-plugin-markdown', order: 2 }, { ignoreme: 'wrong data' }, ]; - socketAdmin.plugins.orderActivePlugins({ uid: adminUid }, data, function (err) { + socketAdmin.plugins.orderActivePlugins({ uid: adminUid }, data, (err) => { assert.ifError(err); - db.sortedSetRank('plugins:active', 'nodebb-plugin-dbsearch', function (err, rank) { + db.sortedSetRank('plugins:active', 'nodebb-plugin-dbsearch', (err, rank) => { assert.ifError(err); assert.equal(rank, 1); done(); @@ -518,24 +516,24 @@ describe('socket.io', function () { it('should upgrade plugin', function (done) { this.timeout(0); - socketAdmin.plugins.upgrade({ uid: adminUid }, { id: 'nodebb-plugin-location-to-map', version: 'latest' }, function (err) { + socketAdmin.plugins.upgrade({ uid: adminUid }, { id: 'nodebb-plugin-location-to-map', version: 'latest' }, (err) => { assert.ifError(err); done(); }); }); - it('should error with invalid data', function (done) { - socketAdmin.widgets.set({ uid: adminUid }, null, function (err) { + it('should error with invalid data', (done) => { + socketAdmin.widgets.set({ uid: adminUid }, null, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); }); - it('should error with invalid data', function (done) { + it('should error with invalid data', (done) => { var data = [{ template: 'global', location: 'sidebar', widgets: [{ widget: 'html', data: { html: 'test', title: 'test', container: '' } }] }]; - socketAdmin.widgets.set({ uid: adminUid }, data, function (err) { + socketAdmin.widgets.set({ uid: adminUid }, data, (err) => { assert.ifError(err); - db.getObjectField('widgets:global', 'sidebar', function (err, widgetData) { + db.getObjectField('widgets:global', 'sidebar', (err, widgetData) => { assert.ifError(err); assert.equal(JSON.parse(widgetData)[0].data.html, 'test'); @@ -544,28 +542,28 @@ describe('socket.io', function () { }); }); - it('should clear sitemap cache', function (done) { - socketAdmin.settings.clearSitemapCache({ uid: adminUid }, {}, function (err) { + it('should clear sitemap cache', (done) => { + socketAdmin.settings.clearSitemapCache({ uid: adminUid }, {}, (err) => { assert.ifError(err); done(); }); }); - it('should send test email', function (done) { - socketAdmin.email.test({ uid: adminUid }, { template: 'digest.tpl' }, function (err) { + it('should send test email', (done) => { + socketAdmin.email.test({ uid: adminUid }, { template: 'digest.tpl' }, (err) => { assert.ifError(err); done(); }); }); - it('should get logs', function (done) { + it('should get logs', (done) => { var fs = require('fs'); var path = require('path'); meta.logs.path = path.join(nconf.get('base_dir'), 'test/files', 'output.log'); - fs.appendFile(meta.logs.path, 'some logs', function (err) { + fs.appendFile(meta.logs.path, 'some logs', (err) => { assert.ifError(err); - socketAdmin.logs.get({ uid: adminUid }, {}, function (err, data) { + socketAdmin.logs.get({ uid: adminUid }, {}, (err, data) => { assert.ifError(err); assert(data); done(); @@ -573,10 +571,10 @@ describe('socket.io', function () { }); }); - it('should clear logs', function (done) { - socketAdmin.logs.clear({ uid: adminUid }, {}, function (err) { + it('should clear logs', (done) => { + socketAdmin.logs.clear({ uid: adminUid }, {}, (err) => { assert.ifError(err); - socketAdmin.logs.get({ uid: adminUid }, {}, function (err, data) { + socketAdmin.logs.get({ uid: adminUid }, {}, (err, data) => { assert.ifError(err); assert.equal(data.length, 0); done(); @@ -584,10 +582,10 @@ describe('socket.io', function () { }); }); - it('should clear errors', function (done) { - socketAdmin.errors.clear({ uid: adminUid }, {}, function (err) { + it('should clear errors', (done) => { + socketAdmin.errors.clear({ uid: adminUid }, {}, (err) => { assert.ifError(err); - db.exists('error:404', function (err, exists) { + db.exists('error:404', (err, exists) => { assert.ifError(err); assert(!exists); done(); @@ -595,12 +593,12 @@ describe('socket.io', function () { }); }); - it('should delete a single event', function (done) { - db.getSortedSetRevRange('events:time', 0, 0, function (err, eids) { + it('should delete a single event', (done) => { + db.getSortedSetRevRange('events:time', 0, 0, (err, eids) => { assert.ifError(err); - events.deleteEvents(eids, function (err) { + events.deleteEvents(eids, (err) => { assert.ifError(err); - db.isSortedSetMembers('events:time', eids, function (err, isMembers) { + db.isSortedSetMembers('events:time', eids, (err, isMembers) => { assert.ifError(err); assert(!isMembers.includes(true)); done(); @@ -609,10 +607,10 @@ describe('socket.io', function () { }); }); - it('should delete all events', function (done) { - events.deleteAll(function (err) { + it('should delete all events', (done) => { + events.deleteAll((err) => { assert.ifError(err); - db.sortedSetCard('events:time', function (err, count) { + db.sortedSetCard('events:time', (err, count) => { assert.ifError(err); assert.equal(count, 0); done(); @@ -620,21 +618,21 @@ describe('socket.io', function () { }); }); - describe('logger', function () { + describe('logger', () => { var logger = require('../src/logger'); var index = require('../src/socket.io'); var fs = require('fs'); var path = require('path'); - it('should enable logging', function (done) { + it('should enable logging', (done) => { meta.config.loggerStatus = 1; meta.config.loggerIOStatus = 1; var loggerPath = path.join(__dirname, '..', 'logs', 'logger.log'); logger.monitorConfig({ io: index.server }, { key: 'loggerPath', value: loggerPath }); - setTimeout(function () { - io.emit('meta.rooms.enter', { enter: 'recent_topics' }, function (err) { + setTimeout(() => { + io.emit('meta.rooms.enter', { enter: 'recent_topics' }, (err) => { assert.ifError(err); - fs.readFile(loggerPath, 'utf-8', function (err, content) { + fs.readFile(loggerPath, 'utf-8', (err, content) => { assert.ifError(err); assert(content); done(); @@ -643,24 +641,24 @@ describe('socket.io', function () { }, 500); }); - after(function (done) { + after((done) => { meta.config.loggerStatus = 0; meta.config.loggerIOStatus = 0; done(); }); }); - describe('password reset', function () { + describe('password reset', () => { const socketUser = require('../src/socket.io/user'); - it('should not error on valid email', function (done) { - socketUser.reset.send({ uid: 0 }, 'regular@test.com', function (err) { + it('should not error on valid email', (done) => { + socketUser.reset.send({ uid: 0 }, 'regular@test.com', (err) => { assert.ifError(err); async.parallel({ count: async.apply(db.sortedSetCount.bind(db), 'reset:issueDate', 0, Date.now()), event: async.apply(events.getEvents, '', 0, 0), - }, function (err, data) { + }, (err, data) => { assert.ifError(err); assert.strictEqual(data.count, 1); @@ -675,14 +673,14 @@ describe('socket.io', function () { }); }); - it('should not generate code if rate limited', function (done) { - socketUser.reset.send({ uid: 0 }, 'regular@test.com', function (err) { + it('should not generate code if rate limited', (done) => { + socketUser.reset.send({ uid: 0 }, 'regular@test.com', (err) => { assert.ifError(err); async.parallel({ count: async.apply(db.sortedSetCount.bind(db), 'reset:issueDate', 0, Date.now()), event: async.apply(events.getEvents, '', 0, 0), - }, function (err, data) { + }, (err, data) => { assert.ifError(err); assert.strictEqual(data.count, 1); // should still equal 1 @@ -697,11 +695,11 @@ describe('socket.io', function () { }); }); - it('should not error on invalid email (but not generate reset code)', function (done) { - socketUser.reset.send({ uid: 0 }, 'irregular@test.com', function (err) { + it('should not error on invalid email (but not generate reset code)', (done) => { + socketUser.reset.send({ uid: 0 }, 'irregular@test.com', (err) => { assert.ifError(err); - db.sortedSetCount('reset:issueDate', 0, Date.now(), function (err, count) { + db.sortedSetCount('reset:issueDate', 0, Date.now(), (err, count) => { assert.ifError(err); assert.strictEqual(count, 1); done(); @@ -709,8 +707,8 @@ describe('socket.io', function () { }); }); - it('should error on no email', function (done) { - socketUser.reset.send({ uid: 0 }, '', function (err) { + it('should error on no email', (done) => { + socketUser.reset.send({ uid: 0 }, '', (err) => { assert(err instanceof Error); assert.strictEqual(err.message, '[[error:invalid-data]]'); done(); diff --git a/test/template-helpers.js b/test/template-helpers.js index c48d436c64..8d10ddba5e 100644 --- a/test/template-helpers.js +++ b/test/template-helpers.js @@ -6,14 +6,14 @@ var assert = require('assert'); var db = require('./mocks/databasemock'); var helpers = require('../public/src/modules/helpers'); -describe('helpers', function () { - it('should return false if item doesn\'t exist', function (done) { +describe('helpers', () => { + it('should return false if item doesn\'t exist', (done) => { var flag = helpers.displayMenuItem({ navigation: [] }, 0); assert(!flag); done(); }); - it('should return false if route is /users and user does not have view:users privilege', function (done) { + it('should return false if route is /users and user does not have view:users privilege', (done) => { var flag = helpers.displayMenuItem({ navigation: [{ route: '/users' }], user: { @@ -26,7 +26,7 @@ describe('helpers', function () { done(); }); - it('should return false if route is /tags and user does not have view:tags privilege', function (done) { + it('should return false if route is /tags and user does not have view:tags privilege', (done) => { var flag = helpers.displayMenuItem({ navigation: [{ route: '/tags' }], user: { @@ -39,7 +39,7 @@ describe('helpers', function () { done(); }); - it('should return false if route is /groups and user does not have view:groups privilege', function (done) { + it('should return false if route is /groups and user does not have view:groups privilege', (done) => { var flag = helpers.displayMenuItem({ navigation: [{ route: '/groups' }], user: { @@ -52,24 +52,24 @@ describe('helpers', function () { done(); }); - it('should stringify object', function (done) { + it('should stringify object', (done) => { var str = helpers.stringify({ a: 'herp < derp > and & quote "' }); assert.equal(str, '{"a":"herp < derp > and & quote \\""}'); done(); }); - it('should escape html', function (done) { + it('should escape html', (done) => { var str = helpers.escape('gdkfhgk < some > and &'); assert.equal(str, 'gdkfhgk < some > and &'); done(); }); - it('should return empty string if category is falsy', function (done) { + it('should return empty string if category is falsy', (done) => { assert.equal(helpers.generateCategoryBackground(null), ''); done(); }); - it('should generate category background', function (done) { + it('should generate category background', (done) => { var category = { bgColor: '#ff0000', color: '#00ff00', @@ -81,7 +81,7 @@ describe('helpers', function () { done(); }); - it('should return empty string if category has no children', function (done) { + it('should return empty string if category has no children', (done) => { var category = { children: [], }; @@ -90,7 +90,7 @@ describe('helpers', function () { done(); }); - it('should generate html for children', function (done) { + it('should generate html for children', (done) => { var category = { children: [ { @@ -106,43 +106,43 @@ describe('helpers', function () { done(); }); - it('should generate topic class', function (done) { + it('should generate topic class', (done) => { var className = helpers.generateTopicClass({ locked: true, pinned: true, deleted: true, unread: true }); assert.equal(className, 'locked pinned deleted unread'); done(); }); - it('should show leave button if isMember and group is not administrators', function (done) { + it('should show leave button if isMember and group is not administrators', (done) => { var btn = helpers.membershipBtn({ displayName: 'some group', name: 'some group', isMember: true }); assert.equal(btn, ' [[groups:membership.leave-group]]'); done(); }); - it('should show pending button if isPending and group is not administrators', function (done) { + it('should show pending button if isPending and group is not administrators', (done) => { var btn = helpers.membershipBtn({ displayName: 'some group', name: 'some group', isPending: true }); assert.equal(btn, ' [[groups:membership.invitation-pending]]'); done(); }); - it('should show reject invite button if isInvited', function (done) { + it('should show reject invite button if isInvited', (done) => { var btn = helpers.membershipBtn({ displayName: 'some group', name: 'some group', isInvited: true }); assert.equal(btn, '[[groups:membership.reject]] [[groups:membership.accept-invitation]]'); done(); }); - it('should show join button if join requests are not disabled and group is not administrators', function (done) { + it('should show join button if join requests are not disabled and group is not administrators', (done) => { var btn = helpers.membershipBtn({ displayName: 'some group', name: 'some group', disableJoinRequests: false }); assert.equal(btn, ' [[groups:membership.join-group]]'); done(); }); - it('should show nothing if group is administrators ', function (done) { + it('should show nothing if group is administrators ', (done) => { var btn = helpers.membershipBtn({ displayName: 'administrators', name: 'administrators' }); assert.equal(btn, ''); done(); }); - it('should spawn privilege states', function (done) { + it('should spawn privilege states', (done) => { var privs = { find: true, read: true, @@ -152,85 +152,85 @@ describe('helpers', function () { done(); }); - it('should render thumb as topic image', function (done) { + it('should render thumb as topic image', (done) => { var topicObj = { thumb: '/uploads/1.png', user: { username: 'baris' } }; var html = helpers.renderTopicImage(topicObj); assert.equal(html, ``); done(); }); - it('should render user picture as topic image', function (done) { + it('should render user picture as topic image', (done) => { var topicObj = { thumb: '', user: { uid: 1, username: 'baris', picture: '/uploads/2.png' } }; var html = helpers.renderTopicImage(topicObj); assert.equal(html, ``); done(); }); - it('should render digest avatar', function (done) { + it('should render digest avatar', (done) => { var block = { teaser: { user: { username: 'baris', picture: '/uploads/1.png' } } }; var html = helpers.renderDigestAvatar(block); assert.equal(html, ``); done(); }); - it('should render digest avatar', function (done) { + it('should render digest avatar', (done) => { var block = { teaser: { user: { username: 'baris', 'icon:text': 'B', 'icon:bgColor': '#ff000' } } }; var html = helpers.renderDigestAvatar(block); assert.equal(html, `${block.teaser.user['icon:text']}`); done(); }); - it('should render digest avatar', function (done) { + it('should render digest avatar', (done) => { var block = { user: { username: 'baris', picture: '/uploads/1.png' } }; var html = helpers.renderDigestAvatar(block); assert.equal(html, ``); done(); }); - it('should render digest avatar', function (done) { + it('should render digest avatar', (done) => { var block = { user: { username: 'baris', 'icon:text': 'B', 'icon:bgColor': '#ff000' } }; var html = helpers.renderDigestAvatar(block); assert.equal(html, `${block.user['icon:text']}`); done(); }); - it('shoud render user agent/browser icons', function (done) { + it('shoud render user agent/browser icons', (done) => { var html = helpers.userAgentIcons({ platform: 'Linux', browser: 'Chrome' }); assert.equal(html, ''); done(); }); - it('shoud render user agent/browser icons', function (done) { + it('shoud render user agent/browser icons', (done) => { var html = helpers.userAgentIcons({ platform: 'Microsoft Windows', browser: 'Firefox' }); assert.equal(html, ''); done(); }); - it('shoud render user agent/browser icons', function (done) { + it('shoud render user agent/browser icons', (done) => { var html = helpers.userAgentIcons({ platform: 'Apple Mac', browser: 'Safari' }); assert.equal(html, ''); done(); }); - it('shoud render user agent/browser icons', function (done) { + it('shoud render user agent/browser icons', (done) => { var html = helpers.userAgentIcons({ platform: 'Android', browser: 'IE' }); assert.equal(html, ''); done(); }); - it('shoud render user agent/browser icons', function (done) { + it('shoud render user agent/browser icons', (done) => { var html = helpers.userAgentIcons({ platform: 'iPad', browser: 'Edge' }); assert.equal(html, ''); done(); }); - it('shoud render user agent/browser icons', function (done) { + it('shoud render user agent/browser icons', (done) => { var html = helpers.userAgentIcons({ platform: 'iPhone', browser: 'unknow' }); assert.equal(html, ''); done(); }); - it('shoud render user agent/browser icons', function (done) { + it('shoud render user agent/browser icons', (done) => { var html = helpers.userAgentIcons({ platform: 'unknow', browser: 'unknown' }); assert.equal(html, ''); done(); diff --git a/test/topicThumbs.js b/test/topicThumbs.js index bbd898b269..9b17cecd90 100644 --- a/test/topicThumbs.js +++ b/test/topicThumbs.js @@ -247,7 +247,7 @@ describe('Topic thumbs', () => { }); it('should succeed with a valid tid', (done) => { - helpers.uploadFile(`${nconf.get('url')}/api/v3/topics/1/thumbs`, path.join(__dirname, './files/test.png'), {}, adminJar, adminCSRF, function (err, res, body) { + helpers.uploadFile(`${nconf.get('url')}/api/v3/topics/1/thumbs`, path.join(__dirname, './files/test.png'), {}, adminJar, adminCSRF, (err, res, body) => { assert.ifError(err); assert.strictEqual(res.statusCode, 200); done(); @@ -255,7 +255,7 @@ describe('Topic thumbs', () => { }); it('should succeed with a uuid', (done) => { - helpers.uploadFile(`${nconf.get('url')}/api/v3/topics/${uuid}/thumbs`, path.join(__dirname, './files/test.png'), {}, adminJar, adminCSRF, function (err, res, body) { + helpers.uploadFile(`${nconf.get('url')}/api/v3/topics/${uuid}/thumbs`, path.join(__dirname, './files/test.png'), {}, adminJar, adminCSRF, (err, res, body) => { assert.ifError(err); assert.strictEqual(res.statusCode, 200); done(); @@ -273,7 +273,7 @@ describe('Topic thumbs', () => { }); await new Promise((resolve) => { - helpers.uploadFile(`${nconf.get('url')}/api/v3/topics/${uuid}/thumbs`, path.join(__dirname, './files/test.png'), {}, adminJar, adminCSRF, function (err, res, body) { + helpers.uploadFile(`${nconf.get('url')}/api/v3/topics/${uuid}/thumbs`, path.join(__dirname, './files/test.png'), {}, adminJar, adminCSRF, (err, res, body) => { assert.ifError(err); assert.strictEqual(res.statusCode, 200); resolve(); @@ -284,7 +284,7 @@ describe('Topic thumbs', () => { }); it('should fail with a non-existant tid', (done) => { - helpers.uploadFile(`${nconf.get('url')}/api/v3/topics/3/thumbs`, path.join(__dirname, './files/test.png'), {}, adminJar, adminCSRF, function (err, res, body) { + helpers.uploadFile(`${nconf.get('url')}/api/v3/topics/3/thumbs`, path.join(__dirname, './files/test.png'), {}, adminJar, adminCSRF, (err, res, body) => { assert.ifError(err); assert.strictEqual(res.statusCode, 404); done(); @@ -292,7 +292,7 @@ describe('Topic thumbs', () => { }); it('should fail when garbage is passed in', (done) => { - helpers.uploadFile(`${nconf.get('url')}/api/v3/topics/abracadabra/thumbs`, path.join(__dirname, './files/test.png'), {}, adminJar, adminCSRF, function (err, res, body) { + helpers.uploadFile(`${nconf.get('url')}/api/v3/topics/abracadabra/thumbs`, path.join(__dirname, './files/test.png'), {}, adminJar, adminCSRF, (err, res, body) => { assert.ifError(err); assert.strictEqual(res.statusCode, 404); done(); @@ -300,7 +300,7 @@ describe('Topic thumbs', () => { }); it('should fail when calling user cannot edit the tid', (done) => { - helpers.uploadFile(`${nconf.get('url')}/api/v3/topics/1/thumbs`, path.join(__dirname, './files/test.png'), {}, fooJar, fooCSRF, function (err, res, body) { + helpers.uploadFile(`${nconf.get('url')}/api/v3/topics/1/thumbs`, path.join(__dirname, './files/test.png'), {}, fooJar, fooCSRF, (err, res, body) => { assert.ifError(err); assert.strictEqual(res.statusCode, 403); done(); @@ -310,7 +310,7 @@ describe('Topic thumbs', () => { it('should fail if thumbnails are not enabled', (done) => { meta.config.allowTopicsThumbnail = 0; - helpers.uploadFile(`${nconf.get('url')}/api/v3/topics/${uuid}/thumbs`, path.join(__dirname, './files/test.png'), {}, adminJar, adminCSRF, function (err, res, body) { + helpers.uploadFile(`${nconf.get('url')}/api/v3/topics/${uuid}/thumbs`, path.join(__dirname, './files/test.png'), {}, adminJar, adminCSRF, (err, res, body) => { assert.ifError(err); assert.strictEqual(res.statusCode, 503); assert(body && body.status); @@ -319,10 +319,10 @@ describe('Topic thumbs', () => { }); }); - it('should fail if file is not image', function (done) { + it('should fail if file is not image', (done) => { meta.config.allowTopicsThumbnail = 1; - helpers.uploadFile(`${nconf.get('url')}/api/v3/topics/${uuid}/thumbs`, path.join(__dirname, './files/503.html'), {}, adminJar, adminCSRF, function (err, res, body) { + helpers.uploadFile(`${nconf.get('url')}/api/v3/topics/${uuid}/thumbs`, path.join(__dirname, './files/503.html'), {}, adminJar, adminCSRF, (err, res, body) => { assert.ifError(err); assert.strictEqual(res.statusCode, 500); assert(body && body.status); diff --git a/test/topics.js b/test/topics.js index b38e672ff7..27a9e84b5d 100644 --- a/test/topics.js +++ b/test/topics.js @@ -20,18 +20,18 @@ const socketPosts = require('../src/socket.io/posts'); const socketTopics = require('../src/socket.io/topics'); -const requestType = util.promisify(function (type, url, opts, cb) { +const requestType = util.promisify((type, url, opts, cb) => { request[type](url, opts, (err, res, body) => cb(err, { res: res, body: body })); }); -describe('Topic\'s', function () { +describe('Topic\'s', () => { var topic; var categoryObj; var adminUid; var adminJar; var fooUid; - before(async function () { + before(async () => { adminUid = await User.create({ username: 'admin', password: '123456' }); fooUid = await User.create({ username: 'foo' }); await groups.join('administrators', adminUid); @@ -49,16 +49,16 @@ describe('Topic\'s', function () { }; }); - describe('.post', function () { - it('should fail to create topic with invalid data', function (done) { - socketTopics.post({ uid: 0 }, null, function (err) { + describe('.post', () => { + it('should fail to create topic with invalid data', (done) => { + socketTopics.post({ uid: 0 }, null, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); }); - it('should create a new topic with proper parameters', function (done) { - topics.post({ uid: topic.userId, title: topic.title, content: topic.content, cid: topic.categoryId }, function (err, result) { + it('should create a new topic with proper parameters', (done) => { + topics.post({ uid: topic.userId, title: topic.title, content: topic.content, cid: topic.categoryId }, (err, result) => { assert.ifError(err); assert(result); topic.tid = result.topicData.tid; @@ -66,59 +66,59 @@ describe('Topic\'s', function () { }); }); - it('should get post count', function (done) { - socketTopics.postcount({ uid: adminUid }, topic.tid, function (err, count) { + it('should get post count', (done) => { + socketTopics.postcount({ uid: adminUid }, topic.tid, (err, count) => { assert.ifError(err); assert.equal(count, 1); done(); }); }); - it('should load topic', function (done) { - socketTopics.getTopic({ uid: adminUid }, topic.tid, function (err, data) { + it('should load topic', (done) => { + socketTopics.getTopic({ uid: adminUid }, topic.tid, (err, data) => { assert.ifError(err); assert.equal(data.tid, topic.tid); done(); }); }); - it('should fail to create new topic with invalid user id', function (done) { - topics.post({ uid: null, title: topic.title, content: topic.content, cid: topic.categoryId }, function (err) { + it('should fail to create new topic with invalid user id', (done) => { + topics.post({ uid: null, title: topic.title, content: topic.content, cid: topic.categoryId }, (err) => { assert.equal(err.message, '[[error:no-privileges]]'); done(); }); }); - it('should fail to create new topic with empty title', function (done) { - topics.post({ uid: topic.userId, title: '', content: topic.content, cid: topic.categoryId }, function (err) { + it('should fail to create new topic with empty title', (done) => { + topics.post({ uid: topic.userId, title: '', content: topic.content, cid: topic.categoryId }, (err) => { assert.ok(err); done(); }); }); - it('should fail to create new topic with empty content', function (done) { - topics.post({ uid: topic.userId, title: topic.title, content: '', cid: topic.categoryId }, function (err) { + it('should fail to create new topic with empty content', (done) => { + topics.post({ uid: topic.userId, title: topic.title, content: '', cid: topic.categoryId }, (err) => { assert.ok(err); done(); }); }); - it('should fail to create new topic with non-existant category id', function (done) { - topics.post({ uid: topic.userId, title: topic.title, content: topic.content, cid: 99 }, function (err) { + it('should fail to create new topic with non-existant category id', (done) => { + topics.post({ uid: topic.userId, title: topic.title, content: topic.content, cid: 99 }, (err) => { assert.equal(err.message, '[[error:no-category]]', 'received no error'); done(); }); }); - it('should return false for falsy uid', function (done) { - topics.isOwner(topic.tid, 0, function (err, isOwner) { + it('should return false for falsy uid', (done) => { + topics.isOwner(topic.tid, 0, (err, isOwner) => { assert.ifError(err); assert(!isOwner); done(); }); }); - it('should fail to post a topic as guest if no privileges', async function () { + it('should fail to post a topic as guest if no privileges', async () => { const categoryObj = await categories.create({ name: 'Test Category', description: 'Test category created by testing script', @@ -134,7 +134,7 @@ describe('Topic\'s', function () { assert.strictEqual(result.body.status.message, '[[error:no-privileges]]'); }); - it('should post a topic as guest if guest group has privileges', async function () { + it('should post a topic as guest if guest group has privileges', async () => { const categoryObj = await categories.create({ name: 'Test Category', description: 'Test category created by testing script', @@ -165,12 +165,12 @@ describe('Topic\'s', function () { }); }); - describe('.reply', function () { + describe('.reply', () => { var newTopic; var newPost; - before(function (done) { - topics.post({ uid: topic.userId, title: topic.title, content: topic.content, cid: topic.categoryId }, function (err, result) { + before((done) => { + topics.post({ uid: topic.userId, title: topic.title, content: topic.content, cid: topic.categoryId }, (err, result) => { if (err) { return done(err); } @@ -181,8 +181,8 @@ describe('Topic\'s', function () { }); }); - it('should create a new reply with proper parameters', function (done) { - topics.reply({ uid: topic.userId, content: 'test post', tid: newTopic.tid }, function (err, result) { + it('should create a new reply with proper parameters', (done) => { + topics.reply({ uid: topic.userId, content: 'test post', tid: newTopic.tid }, (err, result) => { assert.equal(err, null, 'was created with error'); assert.ok(result); @@ -190,12 +190,12 @@ describe('Topic\'s', function () { }); }); - it('should handle direct replies', function (done) { - topics.reply({ uid: topic.userId, content: 'test reply', tid: newTopic.tid, toPid: newPost.pid }, function (err, result) { + it('should handle direct replies', (done) => { + topics.reply({ uid: topic.userId, content: 'test reply', tid: newTopic.tid, toPid: newPost.pid }, (err, result) => { assert.equal(err, null, 'was created with error'); assert.ok(result); - socketPosts.getReplies({ uid: 0 }, newPost.pid, function (err, postData) { + socketPosts.getReplies({ uid: 0 }, newPost.pid, (err, postData) => { assert.ifError(err); assert.ok(postData); @@ -208,42 +208,42 @@ describe('Topic\'s', function () { }); }); - it('should error if pid is not a number', function (done) { - socketPosts.getReplies({ uid: 0 }, 'abc', function (err) { + it('should error if pid is not a number', (done) => { + socketPosts.getReplies({ uid: 0 }, 'abc', (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); }); - it('should fail to create new reply with invalid user id', function (done) { - topics.reply({ uid: null, content: 'test post', tid: newTopic.tid }, function (err) { + it('should fail to create new reply with invalid user id', (done) => { + topics.reply({ uid: null, content: 'test post', tid: newTopic.tid }, (err) => { assert.equal(err.message, '[[error:no-privileges]]'); done(); }); }); - it('should fail to create new reply with empty content', function (done) { - topics.reply({ uid: topic.userId, content: '', tid: newTopic.tid }, function (err) { + it('should fail to create new reply with empty content', (done) => { + topics.reply({ uid: topic.userId, content: '', tid: newTopic.tid }, (err) => { assert.ok(err); done(); }); }); - it('should fail to create new reply with invalid topic id', function (done) { - topics.reply({ uid: null, content: 'test post', tid: 99 }, function (err) { + it('should fail to create new reply with invalid topic id', (done) => { + topics.reply({ uid: null, content: 'test post', tid: 99 }, (err) => { assert.equal(err.message, '[[error:no-topic]]'); done(); }); }); - it('should fail to create new reply with invalid toPid', function (done) { - topics.reply({ uid: topic.userId, content: 'test post', tid: newTopic.tid, toPid: '"onmouseover=alert(1);//' }, function (err) { + it('should fail to create new reply with invalid toPid', (done) => { + topics.reply({ uid: topic.userId, content: 'test post', tid: newTopic.tid, toPid: '"onmouseover=alert(1);//' }, (err) => { assert.equal(err.message, '[[error:invalid-pid]]'); done(); }); }); - it('should delete nested relies properly', async function () { + it('should delete nested relies properly', async () => { const result = await topics.post({ uid: fooUid, title: 'nested test', content: 'main post', cid: topic.categoryId }); const reply1 = await topics.reply({ uid: fooUid, content: 'reply post 1', tid: result.topicData.tid }); const reply2 = await topics.reply({ uid: fooUid, content: 'reply post 2', tid: result.topicData.tid, toPid: reply1.pid }); @@ -260,12 +260,12 @@ describe('Topic\'s', function () { }); }); - describe('Get methods', function () { + describe('Get methods', () => { var newTopic; var newPost; - before(function (done) { - topics.post({ uid: topic.userId, title: topic.title, content: topic.content, cid: topic.categoryId }, function (err, result) { + before((done) => { + topics.post({ uid: topic.userId, title: topic.title, content: topic.content, cid: topic.categoryId }, (err, result) => { if (err) { return done(err); } @@ -277,8 +277,8 @@ describe('Topic\'s', function () { }); - it('should not receive errors', function (done) { - topics.getTopicData(newTopic.tid, function (err, topicData) { + it('should not receive errors', (done) => { + topics.getTopicData(newTopic.tid, (err, topicData) => { assert.ifError(err); assert(typeof topicData.tid === 'number'); assert(typeof topicData.uid === 'number'); @@ -298,8 +298,8 @@ describe('Topic\'s', function () { }); }); - it('should get a single field', function (done) { - topics.getTopicFields(newTopic.tid, ['slug'], function (err, data) { + it('should get a single field', (done) => { + topics.getTopicFields(newTopic.tid, ['slug'], (err, data) => { assert.ifError(err); assert(Object.keys(data).length === 1); assert(data.hasOwnProperty('slug')); @@ -307,25 +307,25 @@ describe('Topic\'s', function () { }); }); - it('should get topic title by pid', function (done) { - topics.getTitleByPid(newPost.pid, function (err, title) { + it('should get topic title by pid', (done) => { + topics.getTitleByPid(newPost.pid, (err, title) => { assert.ifError(err); assert.equal(title, topic.title); done(); }); }); - it('should get topic data by pid', function (done) { - topics.getTopicDataByPid(newPost.pid, function (err, data) { + it('should get topic data by pid', (done) => { + topics.getTopicDataByPid(newPost.pid, (err, data) => { assert.ifError(err); assert.equal(data.tid, newTopic.tid); done(); }); }); - describe('.getTopicWithPosts', function () { + describe('.getTopicWithPosts', () => { let tid; - before(async function () { + before(async () => { const result = await topics.post({ uid: topic.userId, title: 'page test', content: 'main post', cid: topic.categoryId }); tid = result.topicData.tid; for (let i = 0; i < 30; i++) { @@ -334,7 +334,7 @@ describe('Topic\'s', function () { } }); - it('should get a topic with posts and other data', async function () { + it('should get a topic with posts and other data', async () => { const topicData = await topics.getTopicData(tid); const data = await topics.getTopicWithPosts(topicData, `tid:${tid}:posts`, topic.userId, 0, -1, false); assert(data); @@ -345,7 +345,7 @@ describe('Topic\'s', function () { assert.equal(data.pinned, false); }); - it('should return first 3 posts including main post', async function () { + it('should return first 3 posts including main post', async () => { const topicData = await topics.getTopicData(tid); const data = await topics.getTopicWithPosts(topicData, `tid:${tid}:posts`, topic.userId, 0, 2, false); assert.strictEqual(data.posts.length, 3); @@ -357,7 +357,7 @@ describe('Topic\'s', function () { }); }); - it('should return 3 posts from 1 to 3 excluding main post', async function () { + it('should return 3 posts from 1 to 3 excluding main post', async () => { const topicData = await topics.getTopicData(tid); const start = 1; const data = await topics.getTopicWithPosts(topicData, `tid:${tid}:posts`, topic.userId, start, 3, false); @@ -370,7 +370,7 @@ describe('Topic\'s', function () { }); }); - it('should return main post and last 2 posts', async function () { + it('should return main post and last 2 posts', async () => { const topicData = await topics.getTopicData(tid); const data = await topics.getTopicWithPosts(topicData, `tid:${tid}:posts`, topic.userId, 0, 2, true); assert.strictEqual(data.posts.length, 3); @@ -382,7 +382,7 @@ describe('Topic\'s', function () { }); }); - it('should return last 3 posts and not main post', async function () { + it('should return last 3 posts and not main post', async () => { const topicData = await topics.getTopicData(tid); const start = 1; const data = await topics.getTopicWithPosts(topicData, `tid:${tid}:posts`, topic.userId, start, 3, true); @@ -395,7 +395,7 @@ describe('Topic\'s', function () { }); }); - it('should return posts 29 to 27 posts and not main post', async function () { + it('should return posts 29 to 27 posts and not main post', async () => { const topicData = await topics.getTopicData(tid); const start = 2; const data = await topics.getTopicWithPosts(topicData, `tid:${tid}:posts`, topic.userId, start, 4, true); @@ -408,7 +408,7 @@ describe('Topic\'s', function () { }); }); - it('should return 3 posts in reverse', async function () { + it('should return 3 posts in reverse', async () => { const topicData = await topics.getTopicData(tid); const start = 28; const data = await topics.getTopicWithPosts(topicData, `tid:${tid}:posts`, topic.userId, start, 30, true); @@ -421,7 +421,7 @@ describe('Topic\'s', function () { }); }); - it('should get all posts with main post at the start', async function () { + it('should get all posts with main post at the start', async () => { const topicData = await topics.getTopicData(tid); const data = await topics.getTopicWithPosts(topicData, `tid:${tid}:posts`, topic.userId, 0, -1, false); assert.strictEqual(data.posts.length, 31); @@ -433,7 +433,7 @@ describe('Topic\'s', function () { }); }); - it('should get all posts in reverse with main post at the start followed by reply 30', async function () { + it('should get all posts in reverse with main post at the start followed by reply 30', async () => { const topicData = await topics.getTopicData(tid); const data = await topics.getTopicWithPosts(topicData, `tid:${tid}:posts`, topic.userId, 0, -1, true); assert.strictEqual(data.posts.length, 31); @@ -447,13 +447,13 @@ describe('Topic\'s', function () { }); }); - describe('Title escaping', function () { - it('should properly escape topic title', function (done) { + describe('Title escaping', () => { + it('should properly escape topic title', (done) => { var title = '" new topic test'; var titleEscaped = validator.escape(title); - topics.post({ uid: topic.userId, title: title, content: topic.content, cid: topic.categoryId }, function (err, result) { + topics.post({ uid: topic.userId, title: title, content: topic.content, cid: topic.categoryId }, (err, result) => { assert.ifError(err); - topics.getTopicData(result.topicData.tid, function (err, topicData) { + topics.getTopicData(result.topicData.tid, (err, topicData) => { assert.ifError(err); assert.strictEqual(topicData.titleRaw, title); assert.strictEqual(topicData.title, titleEscaped); @@ -463,15 +463,15 @@ describe('Topic\'s', function () { }); }); - describe('tools/delete/restore/purge', function () { + describe('tools/delete/restore/purge', () => { var newTopic; var followerUid; var moveCid; - before(function (done) { + before((done) => { async.waterfall([ function (next) { - topics.post({ uid: topic.userId, title: topic.title, content: topic.content, cid: topic.categoryId }, function (err, result) { + topics.post({ uid: topic.userId, title: topic.title, content: topic.content, cid: topic.categoryId }, (err, result) => { assert.ifError(err); newTopic = result.topicData; next(); @@ -488,7 +488,7 @@ describe('Topic\'s', function () { categories.create({ name: 'Test Category', description: 'Test category created by testing script', - }, function (err, category) { + }, (err, category) => { if (err) { return next(err); } @@ -499,32 +499,32 @@ describe('Topic\'s', function () { ], done); }); - it('should load topic tools', function (done) { - socketTopics.loadTopicTools({ uid: adminUid }, { tid: newTopic.tid }, function (err, data) { + it('should load topic tools', (done) => { + socketTopics.loadTopicTools({ uid: adminUid }, { tid: newTopic.tid }, (err, data) => { assert.ifError(err); assert(data); done(); }); }); - it('should delete the topic', function (done) { - socketTopics.delete({ uid: adminUid }, { tids: [newTopic.tid], cid: categoryObj.cid }, function (err) { + it('should delete the topic', (done) => { + socketTopics.delete({ uid: adminUid }, { tids: [newTopic.tid], cid: categoryObj.cid }, (err) => { assert.ifError(err); done(); }); }); - it('should restore the topic', function (done) { - socketTopics.restore({ uid: adminUid }, { tids: [newTopic.tid], cid: categoryObj.cid }, function (err) { + it('should restore the topic', (done) => { + socketTopics.restore({ uid: adminUid }, { tids: [newTopic.tid], cid: categoryObj.cid }, (err) => { assert.ifError(err); done(); }); }); - it('should lock topic', function (done) { - socketTopics.lock({ uid: adminUid }, { tids: [newTopic.tid], cid: categoryObj.cid }, function (err) { + it('should lock topic', (done) => { + socketTopics.lock({ uid: adminUid }, { tids: [newTopic.tid], cid: categoryObj.cid }, (err) => { assert.ifError(err); - topics.isLocked(newTopic.tid, function (err, isLocked) { + topics.isLocked(newTopic.tid, (err, isLocked) => { assert.ifError(err); assert(isLocked); done(); @@ -532,10 +532,10 @@ describe('Topic\'s', function () { }); }); - it('should unlock topic', function (done) { - socketTopics.unlock({ uid: adminUid }, { tids: [newTopic.tid], cid: categoryObj.cid }, function (err) { + it('should unlock topic', (done) => { + socketTopics.unlock({ uid: adminUid }, { tids: [newTopic.tid], cid: categoryObj.cid }, (err) => { assert.ifError(err); - topics.isLocked(newTopic.tid, function (err, isLocked) { + topics.isLocked(newTopic.tid, (err, isLocked) => { assert.ifError(err); assert(!isLocked); done(); @@ -543,10 +543,10 @@ describe('Topic\'s', function () { }); }); - it('should pin topic', function (done) { - socketTopics.pin({ uid: adminUid }, { tids: [newTopic.tid], cid: categoryObj.cid }, function (err) { + it('should pin topic', (done) => { + socketTopics.pin({ uid: adminUid }, { tids: [newTopic.tid], cid: categoryObj.cid }, (err) => { assert.ifError(err); - topics.getTopicField(newTopic.tid, 'pinned', function (err, pinned) { + topics.getTopicField(newTopic.tid, 'pinned', (err, pinned) => { assert.ifError(err); assert.strictEqual(pinned, 1); done(); @@ -554,10 +554,10 @@ describe('Topic\'s', function () { }); }); - it('should unpin topic', function (done) { - socketTopics.unpin({ uid: adminUid }, { tids: [newTopic.tid], cid: categoryObj.cid }, function (err) { + it('should unpin topic', (done) => { + socketTopics.unpin({ uid: adminUid }, { tids: [newTopic.tid], cid: categoryObj.cid }, (err) => { assert.ifError(err); - topics.getTopicField(newTopic.tid, 'pinned', function (err, pinned) { + topics.getTopicField(newTopic.tid, 'pinned', (err, pinned) => { assert.ifError(err); assert.strictEqual(pinned, 0); done(); @@ -565,10 +565,10 @@ describe('Topic\'s', function () { }); }); - it('should move all topics', function (done) { - socketTopics.moveAll({ uid: adminUid }, { cid: moveCid, currentCid: categoryObj.cid }, function (err) { + it('should move all topics', (done) => { + socketTopics.moveAll({ uid: adminUid }, { cid: moveCid, currentCid: categoryObj.cid }, (err) => { assert.ifError(err); - topics.getTopicField(newTopic.tid, 'cid', function (err, cid) { + topics.getTopicField(newTopic.tid, 'cid', (err, cid) => { assert.ifError(err); assert.equal(cid, moveCid); done(); @@ -576,10 +576,10 @@ describe('Topic\'s', function () { }); }); - it('should move a topic', function (done) { - socketTopics.move({ uid: adminUid }, { cid: categoryObj.cid, tids: [newTopic.tid] }, function (err) { + it('should move a topic', (done) => { + socketTopics.move({ uid: adminUid }, { cid: categoryObj.cid, tids: [newTopic.tid] }, (err) => { assert.ifError(err); - topics.getTopicField(newTopic.tid, 'cid', function (err, cid) { + topics.getTopicField(newTopic.tid, 'cid', (err, cid) => { assert.ifError(err); assert.equal(cid, categoryObj.cid); done(); @@ -587,7 +587,7 @@ describe('Topic\'s', function () { }); }); - it('should properly update sets when post is moved', function (done) { + it('should properly update sets when post is moved', (done) => { var movedPost; var previousPost; var topic2LastReply; @@ -701,7 +701,7 @@ describe('Topic\'s', function () { ], done); }); - it('should fail to purge topic if user does not have privilege', function (done) { + it('should fail to purge topic if user does not have privilege', (done) => { var globalModUid; var tid; async.waterfall([ @@ -725,7 +725,7 @@ describe('Topic\'s', function () { privileges.categories.rescind(['groups:purge'], categoryObj.cid, 'Global Moderators', next); }, function (next) { - socketTopics.purge({ uid: globalModUid }, { tids: [tid], cid: categoryObj.cid }, function (err) { + socketTopics.purge({ uid: globalModUid }, { tids: [tid], cid: categoryObj.cid }, (err) => { assert.equal(err.message, '[[error:no-privileges]]'); privileges.categories.give(['groups:purge'], categoryObj.cid, 'Global Moderators', next); }); @@ -733,10 +733,10 @@ describe('Topic\'s', function () { ], done); }); - it('should purge the topic', function (done) { - socketTopics.purge({ uid: adminUid }, { tids: [newTopic.tid], cid: categoryObj.cid }, function (err) { + it('should purge the topic', (done) => { + socketTopics.purge({ uid: adminUid }, { tids: [newTopic.tid], cid: categoryObj.cid }, (err) => { assert.ifError(err); - db.isSortedSetMember(`uid:${followerUid}:followed_tids`, newTopic.tid, function (err, isMember) { + db.isSortedSetMember(`uid:${followerUid}:followed_tids`, newTopic.tid, (err, isMember) => { assert.ifError(err); assert.strictEqual(false, isMember); done(); @@ -744,7 +744,7 @@ describe('Topic\'s', function () { }); }); - it('should not allow user to restore their topic if it was deleted by an admin', async function () { + it('should not allow user to restore their topic if it was deleted by an admin', async () => { const result = await topics.post({ uid: fooUid, title: 'topic for restore test', @@ -760,11 +760,11 @@ describe('Topic\'s', function () { }); }); - describe('order pinned topics', function () { + describe('order pinned topics', () => { var tid1; var tid2; var tid3; - before(function (done) { + before((done) => { function createTopic(callback) { topics.post({ uid: topic.userId, @@ -783,7 +783,7 @@ describe('Topic\'s', function () { topic3: function (next) { createTopic(next); }, - }, function (err, results) { + }, (err, results) => { assert.ifError(err); tid1 = results.topic1.topicData.tid; tid2 = results.topic2.topicData.tid; @@ -794,7 +794,7 @@ describe('Topic\'s', function () { }, function (next) { // artificial timeout so pin time is different on redis sometimes scores are indentical - setTimeout(function () { + setTimeout(() => { topics.tools.pin(tid2, adminUid, next); }, 5); }, @@ -803,31 +803,31 @@ describe('Topic\'s', function () { }); var socketTopics = require('../src/socket.io/topics'); - it('should error with invalid data', function (done) { - socketTopics.orderPinnedTopics({ uid: adminUid }, null, function (err) { + it('should error with invalid data', (done) => { + socketTopics.orderPinnedTopics({ uid: adminUid }, null, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); }); - it('should error with invalid data', function (done) { - socketTopics.orderPinnedTopics({ uid: adminUid }, [null, null], function (err) { + it('should error with invalid data', (done) => { + socketTopics.orderPinnedTopics({ uid: adminUid }, [null, null], (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); }); - it('should error with unprivileged user', function (done) { - socketTopics.orderPinnedTopics({ uid: 0 }, [{ tid: tid1 }, { tid: tid2 }], function (err) { + it('should error with unprivileged user', (done) => { + socketTopics.orderPinnedTopics({ uid: 0 }, [{ tid: tid1 }, { tid: tid2 }], (err) => { assert.equal(err.message, '[[error:no-privileges]]'); done(); }); }); - it('should not do anything if topics are not pinned', function (done) { - socketTopics.orderPinnedTopics({ uid: adminUid }, [{ tid: tid3 }], function (err) { + it('should not do anything if topics are not pinned', (done) => { + socketTopics.orderPinnedTopics({ uid: adminUid }, [{ tid: tid3 }], (err) => { assert.ifError(err); - db.isSortedSetMember(`cid:${topic.categoryId}:tids:pinned`, tid3, function (err, isMember) { + db.isSortedSetMember(`cid:${topic.categoryId}:tids:pinned`, tid3, (err, isMember) => { assert.ifError(err); assert(!isMember); done(); @@ -835,14 +835,14 @@ describe('Topic\'s', function () { }); }); - it('should order pinned topics', function (done) { - db.getSortedSetRevRange(`cid:${topic.categoryId}:tids:pinned`, 0, -1, function (err, pinnedTids) { + it('should order pinned topics', (done) => { + db.getSortedSetRevRange(`cid:${topic.categoryId}:tids:pinned`, 0, -1, (err, pinnedTids) => { assert.ifError(err); assert.equal(pinnedTids[0], tid2); assert.equal(pinnedTids[1], tid1); - socketTopics.orderPinnedTopics({ uid: adminUid }, [{ tid: tid1, order: 1 }, { tid: tid2, order: 0 }], function (err) { + socketTopics.orderPinnedTopics({ uid: adminUid }, [{ tid: tid1, order: 1 }, { tid: tid2, order: 0 }], (err) => { assert.ifError(err); - db.getSortedSetRevRange(`cid:${topic.categoryId}:tids:pinned`, 0, -1, function (err, pinnedTids) { + db.getSortedSetRevRange(`cid:${topic.categoryId}:tids:pinned`, 0, -1, (err, pinnedTids) => { assert.ifError(err); assert.equal(pinnedTids[0], tid1); assert.equal(pinnedTids[1], tid2); @@ -854,15 +854,15 @@ describe('Topic\'s', function () { }); - describe('.ignore', function () { + describe('.ignore', () => { var newTid; var uid; var newTopic; - before(function (done) { + before((done) => { uid = topic.userId; async.waterfall([ function (done) { - topics.post({ uid: topic.userId, title: 'Topic to be ignored', content: 'Just ignore me, please!', cid: topic.categoryId }, function (err, result) { + topics.post({ uid: topic.userId, title: 'Topic to be ignored', content: 'Just ignore me, please!', cid: topic.categoryId }, (err, result) => { if (err) { return done(err); } @@ -878,7 +878,7 @@ describe('Topic\'s', function () { ], done); }); - it('should not appear in the unread list', function (done) { + it('should not appear in the unread list', (done) => { async.waterfall([ function (done) { topics.ignore(newTid, uid, done); @@ -888,14 +888,14 @@ describe('Topic\'s', function () { }, function (results, done) { var topics = results.topics; - var tids = topics.map(function (topic) { return topic.tid; }); + var tids = topics.map(topic => topic.tid); assert.equal(tids.indexOf(newTid), -1, 'The topic appeared in the unread list.'); done(); }, ], done); }); - it('should not appear as unread in the recent list', function (done) { + it('should not appear as unread in the recent list', (done) => { async.waterfall([ function (done) { topics.ignore(newTid, uid, done); @@ -924,7 +924,7 @@ describe('Topic\'s', function () { ], done); }); - it('should appear as unread again when marked as reading', function (done) { + it('should appear as unread again when marked as reading', (done) => { async.waterfall([ function (done) { topics.ignore(newTid, uid, done); @@ -937,14 +937,14 @@ describe('Topic\'s', function () { }, function (results, done) { var topics = results.topics; - var tids = topics.map(function (topic) { return topic.tid; }); + var tids = topics.map(topic => topic.tid); assert.notEqual(tids.indexOf(newTid), -1, 'The topic did not appear in the unread list.'); done(); }, ], done); }); - it('should appear as unread again when marked as following', function (done) { + it('should appear as unread again when marked as following', (done) => { async.waterfall([ function (done) { topics.ignore(newTid, uid, done); @@ -957,7 +957,7 @@ describe('Topic\'s', function () { }, function (results, done) { var topics = results.topics; - var tids = topics.map(function (topic) { return topic.tid; }); + var tids = topics.map(topic => topic.tid); assert.notEqual(tids.indexOf(newTid), -1, 'The topic did not appear in the unread list.'); done(); }, @@ -965,13 +965,13 @@ describe('Topic\'s', function () { }); }); - describe('.fork', function () { + describe('.fork', () => { var newTopic; var replies = []; var topicPids; var originalBookmark = 6; function postReply(next) { - topics.reply({ uid: topic.userId, content: `test post ${replies.length}`, tid: newTopic.tid }, function (err, result) { + topics.reply({ uid: topic.userId, content: `test post ${replies.length}`, tid: newTopic.tid }, (err, result) => { assert.equal(err, null, 'was created with error'); assert.ok(result); replies.push(result); @@ -979,13 +979,13 @@ describe('Topic\'s', function () { }); } - before(function (done) { + before((done) => { async.waterfall([ function (next) { groups.join('administrators', topic.userId, next); }, function (next) { - topics.post({ uid: topic.userId, title: topic.title, content: topic.content, cid: topic.categoryId }, function (err, result) { + topics.post({ uid: topic.userId, title: topic.title, content: topic.content, cid: topic.categoryId }, (err, result) => { assert.ifError(err); newTopic = result.topicData; next(); @@ -1004,39 +1004,39 @@ describe('Topic\'s', function () { function (next) { postReply(next); }, function (next) { postReply(next); }, function (next) { - topicPids = replies.map(function (reply) { return reply.pid; }); + topicPids = replies.map(reply => reply.pid); socketTopics.bookmark({ uid: topic.userId }, { tid: newTopic.tid, index: originalBookmark }, next); }, ], done); }); - it('should fail with invalid data', function (done) { - socketTopics.bookmark({ uid: topic.userId }, null, function (err) { + it('should fail with invalid data', (done) => { + socketTopics.bookmark({ uid: topic.userId }, null, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); }); - it('should have 12 replies', function (done) { + it('should have 12 replies', (done) => { assert.equal(12, replies.length); done(); }); - it('should fail with invalid data', function (done) { - socketTopics.createTopicFromPosts({ uid: 0 }, null, function (err) { + it('should fail with invalid data', (done) => { + socketTopics.createTopicFromPosts({ uid: 0 }, null, (err) => { assert.equal(err.message, '[[error:not-logged-in]]'); done(); }); }); - it('should fail with invalid data', function (done) { - socketTopics.createTopicFromPosts({ uid: adminUid }, null, function (err) { + it('should fail with invalid data', (done) => { + socketTopics.createTopicFromPosts({ uid: adminUid }, null, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); }); - it('should not update the user\'s bookmark', function (done) { + it('should not update the user\'s bookmark', (done) => { async.waterfall([ function (next) { socketTopics.createTopicFromPosts({ uid: topic.userId }, { @@ -1055,7 +1055,7 @@ describe('Topic\'s', function () { ], done); }); - it('should update the user\'s bookmark ', function (done) { + it('should update the user\'s bookmark ', (done) => { async.waterfall([ function (next) { topics.createTopicFromPosts( @@ -1093,17 +1093,17 @@ describe('Topic\'s', function () { }); }); - describe('controller', function () { + describe('controller', () => { var topicData; - before(function (done) { + before((done) => { topics.post({ uid: topic.userId, title: 'topic for controller test', content: 'topic content', cid: topic.categoryId, thumb: 'http://i.imgur.com/64iBdBD.jpg', - }, function (err, result) { + }, (err, result) => { assert.ifError(err); assert.ok(result); topicData = result.topicData; @@ -1111,8 +1111,8 @@ describe('Topic\'s', function () { }); }); - it('should load topic', function (done) { - request(`${nconf.get('url')}/topic/${topicData.slug}`, function (err, response, body) { + it('should load topic', (done) => { + request(`${nconf.get('url')}/topic/${topicData.slug}`, (err, response, body) => { assert.ifError(err); assert.equal(response.statusCode, 200); assert(body); @@ -1120,8 +1120,8 @@ describe('Topic\'s', function () { }); }); - it('should load topic api data', function (done) { - request(`${nconf.get('url')}/api/topic/${topicData.slug}`, { json: true }, function (err, response, body) { + it('should load topic api data', (done) => { + request(`${nconf.get('url')}/api/topic/${topicData.slug}`, { json: true }, (err, response, body) => { assert.ifError(err); assert.equal(response.statusCode, 200); assert.strictEqual(body._header.tags.meta.find(t => t.name === 'description').content, 'topic content'); @@ -1130,27 +1130,27 @@ describe('Topic\'s', function () { }); }); - it('should 404 if post index is invalid', function (done) { - request(`${nconf.get('url')}/topic/${topicData.slug}/derp`, function (err, response) { + it('should 404 if post index is invalid', (done) => { + request(`${nconf.get('url')}/topic/${topicData.slug}/derp`, (err, response) => { assert.ifError(err); assert.equal(response.statusCode, 404); done(); }); }); - it('should 404 if topic does not exist', function (done) { - request(`${nconf.get('url')}/topic/123123/does-not-exist`, function (err, response) { + it('should 404 if topic does not exist', (done) => { + request(`${nconf.get('url')}/topic/123123/does-not-exist`, (err, response) => { assert.ifError(err); assert.equal(response.statusCode, 404); done(); }); }); - it('should 401 if not allowed to read as guest', function (done) { + it('should 401 if not allowed to read as guest', (done) => { var privileges = require('../src/privileges'); - privileges.categories.rescind(['groups:topics:read'], topicData.cid, 'guests', function (err) { + privileges.categories.rescind(['groups:topics:read'], topicData.cid, 'guests', (err) => { assert.ifError(err); - request(`${nconf.get('url')}/api/topic/${topicData.slug}`, function (err, response, body) { + request(`${nconf.get('url')}/api/topic/${topicData.slug}`, (err, response, body) => { assert.ifError(err); assert.equal(response.statusCode, 401); assert(body); @@ -1159,8 +1159,8 @@ describe('Topic\'s', function () { }); }); - it('should redirect to correct topic if slug is missing', function (done) { - request(`${nconf.get('url')}/topic/${topicData.tid}/herpderp/1?page=2`, function (err, response, body) { + it('should redirect to correct topic if slug is missing', (done) => { + request(`${nconf.get('url')}/topic/${topicData.tid}/herpderp/1?page=2`, (err, response, body) => { assert.ifError(err); assert.equal(response.statusCode, 200); assert(body); @@ -1168,8 +1168,8 @@ describe('Topic\'s', function () { }); }); - it('should redirect if post index is out of range', function (done) { - request(`${nconf.get('url')}/api/topic/${topicData.slug}/-1`, { json: true }, function (err, res, body) { + it('should redirect if post index is out of range', (done) => { + request(`${nconf.get('url')}/api/topic/${topicData.slug}/-1`, { json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert.equal(res.headers['x-redirect'], `/topic/${topicData.tid}/topic-for-controller-test`); @@ -1178,23 +1178,23 @@ describe('Topic\'s', function () { }); }); - it('should 404 if page is out of bounds', function (done) { + it('should 404 if page is out of bounds', (done) => { var meta = require('../src/meta'); meta.config.usePagination = 1; - request(`${nconf.get('url')}/topic/${topicData.slug}?page=100`, function (err, response) { + request(`${nconf.get('url')}/topic/${topicData.slug}?page=100`, (err, response) => { assert.ifError(err); assert.equal(response.statusCode, 404); done(); }); }); - it('should mark topic read', function (done) { + it('should mark topic read', (done) => { request(`${nconf.get('url')}/topic/${topicData.slug}`, { jar: adminJar, - }, function (err, res) { + }, (err, res) => { assert.ifError(err); assert.equal(res.statusCode, 200); - topics.hasReadTopics([topicData.tid], adminUid, function (err, hasRead) { + topics.hasReadTopics([topicData.tid], adminUid, (err, hasRead) => { assert.ifError(err); assert.equal(hasRead[0], true); done(); @@ -1202,16 +1202,16 @@ describe('Topic\'s', function () { }); }); - it('should 404 if tid is not a number', function (done) { - request(`${nconf.get('url')}/api/topic/teaser/nan`, { json: true }, function (err, response) { + it('should 404 if tid is not a number', (done) => { + request(`${nconf.get('url')}/api/topic/teaser/nan`, { json: true }, (err, response) => { assert.ifError(err); assert.equal(response.statusCode, 404); done(); }); }); - it('should 403 if cant read', function (done) { - request(`${nconf.get('url')}/api/topic/teaser/${123123}`, { json: true }, function (err, response, body) { + it('should 403 if cant read', (done) => { + request(`${nconf.get('url')}/api/topic/teaser/${123123}`, { json: true }, (err, response, body) => { assert.ifError(err); assert.equal(response.statusCode, 403); assert.equal(body, '[[error:no-privileges]]'); @@ -1220,8 +1220,8 @@ describe('Topic\'s', function () { }); }); - it('should load topic teaser', function (done) { - request(`${nconf.get('url')}/api/topic/teaser/${topicData.tid}`, { json: true }, function (err, response, body) { + it('should load topic teaser', (done) => { + request(`${nconf.get('url')}/api/topic/teaser/${topicData.tid}`, { json: true }, (err, response, body) => { assert.ifError(err); assert.equal(response.statusCode, 200); assert(body); @@ -1235,24 +1235,24 @@ describe('Topic\'s', function () { }); - it('should 404 if tid is not a number', function (done) { - request(`${nconf.get('url')}/api/topic/pagination/nan`, { json: true }, function (err, response) { + it('should 404 if tid is not a number', (done) => { + request(`${nconf.get('url')}/api/topic/pagination/nan`, { json: true }, (err, response) => { assert.ifError(err); assert.equal(response.statusCode, 404); done(); }); }); - it('should 404 if tid does not exist', function (done) { - request(`${nconf.get('url')}/api/topic/pagination/1231231`, { json: true }, function (err, response) { + it('should 404 if tid does not exist', (done) => { + request(`${nconf.get('url')}/api/topic/pagination/1231231`, { json: true }, (err, response) => { assert.ifError(err); assert.equal(response.statusCode, 404); done(); }); }); - it('should load pagination', function (done) { - request(`${nconf.get('url')}/api/topic/pagination/${topicData.tid}`, { json: true }, function (err, response, body) { + it('should load pagination', (done) => { + request(`${nconf.get('url')}/api/topic/pagination/${topicData.tid}`, { json: true }, (err, response, body) => { assert.ifError(err); assert.equal(response.statusCode, 200); assert(body); @@ -1272,26 +1272,26 @@ describe('Topic\'s', function () { }); - describe('infinitescroll', function () { + describe('infinitescroll', () => { var socketTopics = require('../src/socket.io/topics'); var tid; - before(function (done) { - topics.post({ uid: topic.userId, title: topic.title, content: topic.content, cid: topic.categoryId }, function (err, result) { + before((done) => { + topics.post({ uid: topic.userId, title: topic.title, content: topic.content, cid: topic.categoryId }, (err, result) => { assert.ifError(err); tid = result.topicData.tid; done(); }); }); - it('should error with invalid data', function (done) { - socketTopics.loadMore({ uid: adminUid }, {}, function (err) { + it('should error with invalid data', (done) => { + socketTopics.loadMore({ uid: adminUid }, {}, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); }); - it('should infinite load topic posts', function (done) { - socketTopics.loadMore({ uid: adminUid }, { tid: tid, after: 0, count: 10 }, function (err, data) { + it('should infinite load topic posts', (done) => { + socketTopics.loadMore({ uid: adminUid }, { tid: tid, after: 0, count: 10 }, (err, data) => { assert.ifError(err); assert(data.mainPost); assert(data.posts); @@ -1300,17 +1300,17 @@ describe('Topic\'s', function () { }); }); - it('should error with invalid data', function (done) { - socketTopics.loadMoreSortedTopics({ uid: adminUid }, { after: 'invalid' }, function (err) { + it('should error with invalid data', (done) => { + socketTopics.loadMoreSortedTopics({ uid: adminUid }, { after: 'invalid' }, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); }); - it('should load more unread topics', function (done) { - socketTopics.markUnread({ uid: adminUid }, tid, function (err) { + it('should load more unread topics', (done) => { + socketTopics.markUnread({ uid: adminUid }, tid, (err) => { assert.ifError(err); - socketTopics.loadMoreSortedTopics({ uid: adminUid }, { cid: topic.categoryId, after: 0, count: 10, sort: 'unread' }, function (err, data) { + socketTopics.loadMoreSortedTopics({ uid: adminUid }, { cid: topic.categoryId, after: 0, count: 10, sort: 'unread' }, (err, data) => { assert.ifError(err); assert(data); assert(Array.isArray(data.topics)); @@ -1319,16 +1319,16 @@ describe('Topic\'s', function () { }); }); - it('should error with invalid data', function (done) { - socketTopics.loadMoreSortedTopics({ uid: adminUid }, { after: 'invalid' }, function (err) { + it('should error with invalid data', (done) => { + socketTopics.loadMoreSortedTopics({ uid: adminUid }, { after: 'invalid' }, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); }); - it('should load more recent topics', function (done) { - socketTopics.loadMoreSortedTopics({ uid: adminUid }, { cid: topic.categoryId, after: 0, count: 10, sort: 'recent' }, function (err, data) { + it('should load more recent topics', (done) => { + socketTopics.loadMoreSortedTopics({ uid: adminUid }, { cid: topic.categoryId, after: 0, count: 10, sort: 'recent' }, (err, data) => { assert.ifError(err); assert(data); assert(Array.isArray(data.topics)); @@ -1336,15 +1336,15 @@ describe('Topic\'s', function () { }); }); - it('should error with invalid data', function (done) { - socketTopics.loadMoreFromSet({ uid: adminUid }, { after: 'invalid' }, function (err) { + it('should error with invalid data', (done) => { + socketTopics.loadMoreFromSet({ uid: adminUid }, { after: 'invalid' }, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); }); - it('should load more from custom set', function (done) { - socketTopics.loadMoreFromSet({ uid: adminUid }, { set: `uid:${adminUid}:topics`, after: 0, count: 10 }, function (err, data) { + it('should load more from custom set', (done) => { + socketTopics.loadMoreFromSet({ uid: adminUid }, { set: `uid:${adminUid}:topics`, after: 0, count: 10 }, (err, data) => { assert.ifError(err); assert(data); assert(Array.isArray(data.topics)); @@ -1353,10 +1353,10 @@ describe('Topic\'s', function () { }); }); - describe('suggested topics', function () { + describe('suggested topics', () => { var tid1; var tid3; - before(function (done) { + before((done) => { async.series({ topic1: function (next) { topics.post({ uid: adminUid, tags: ['nodebb'], title: 'topic title 1', content: 'topic 1 content', cid: topic.categoryId }, next); @@ -1367,7 +1367,7 @@ describe('Topic\'s', function () { topic3: function (next) { topics.post({ uid: adminUid, tags: [], title: 'topic title 3', content: 'topic 3 content', cid: topic.categoryId }, next); }, - }, function (err, results) { + }, (err, results) => { assert.ifError(err); tid1 = results.topic1.topicData.tid; tid3 = results.topic3.topicData.tid; @@ -1375,16 +1375,16 @@ describe('Topic\'s', function () { }); }); - it('should return suggested topics', function (done) { - topics.getSuggestedTopics(tid1, adminUid, 0, -1, function (err, topics) { + it('should return suggested topics', (done) => { + topics.getSuggestedTopics(tid1, adminUid, 0, -1, (err, topics) => { assert.ifError(err); assert(Array.isArray(topics)); done(); }); }); - it('should return suggested topics', function (done) { - topics.getSuggestedTopics(tid3, adminUid, 0, 2, function (err, topics) { + it('should return suggested topics', (done) => { + topics.getSuggestedTopics(tid3, adminUid, 0, 2, (err, topics) => { assert.ifError(err); assert(Array.isArray(topics)); done(); @@ -1392,12 +1392,12 @@ describe('Topic\'s', function () { }); }); - describe('unread', function () { + describe('unread', () => { var socketTopics = require('../src/socket.io/topics'); var tid; var mainPid; var uid; - before(function (done) { + before((done) => { async.parallel({ topic: function (next) { topics.post({ uid: topic.userId, title: 'unread topic', content: 'unread topic content', cid: topic.categoryId }, next); @@ -1405,7 +1405,7 @@ describe('Topic\'s', function () { joeUid: function (next) { User.create({ username: 'regularJoe' }, next); }, - }, function (err, results) { + }, (err, results) => { assert.ifError(err); tid = results.topic.topicData.tid; mainPid = results.topic.postData.pid; @@ -1414,24 +1414,24 @@ describe('Topic\'s', function () { }); }); - it('should fail with invalid data', function (done) { - socketTopics.markUnread({ uid: adminUid }, null, function (err) { + it('should fail with invalid data', (done) => { + socketTopics.markUnread({ uid: adminUid }, null, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); }); - it('should fail if topic does not exist', function (done) { - socketTopics.markUnread({ uid: adminUid }, 1231082, function (err) { + it('should fail if topic does not exist', (done) => { + socketTopics.markUnread({ uid: adminUid }, 1231082, (err) => { assert.equal(err.message, '[[error:no-topic]]'); done(); }); }); - it('should mark topic unread', function (done) { - socketTopics.markUnread({ uid: adminUid }, tid, function (err) { + it('should mark topic unread', (done) => { + socketTopics.markUnread({ uid: adminUid }, tid, (err) => { assert.ifError(err); - topics.hasReadTopic(tid, adminUid, function (err, hasRead) { + topics.hasReadTopic(tid, adminUid, (err, hasRead) => { assert.ifError(err); assert.equal(hasRead, false); done(); @@ -1439,17 +1439,17 @@ describe('Topic\'s', function () { }); }); - it('should fail with invalid data', function (done) { - socketTopics.markAsRead({ uid: 0 }, null, function (err) { + it('should fail with invalid data', (done) => { + socketTopics.markAsRead({ uid: 0 }, null, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); }); - it('should mark topic read', function (done) { - socketTopics.markAsRead({ uid: adminUid }, [tid], function (err) { + it('should mark topic read', (done) => { + socketTopics.markAsRead({ uid: adminUid }, [tid], (err) => { assert.ifError(err); - topics.hasReadTopic(tid, adminUid, function (err, hasRead) { + topics.hasReadTopic(tid, adminUid, (err, hasRead) => { assert.ifError(err); assert(hasRead); done(); @@ -1457,14 +1457,14 @@ describe('Topic\'s', function () { }); }); - it('should fail with invalid data', function (done) { - socketTopics.markTopicNotificationsRead({ uid: 0 }, null, function (err) { + it('should fail with invalid data', (done) => { + socketTopics.markTopicNotificationsRead({ uid: 0 }, null, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); }); - it('should mark topic notifications read', function (done) { + it('should mark topic notifications read', (done) => { async.waterfall([ function (next) { socketTopics.follow({ uid: adminUid }, tid, next); @@ -1489,25 +1489,25 @@ describe('Topic\'s', function () { assert.equal(count, 0); next(); }, - ], function (err) { + ], (err) => { assert.ifError(err); done(); }); }); - it('should fail with invalid data', function (done) { - socketTopics.markAllRead({ uid: 0 }, null, function (err) { + it('should fail with invalid data', (done) => { + socketTopics.markAllRead({ uid: 0 }, null, (err) => { assert.equal(err.message, '[[error:invalid-uid]]'); done(); }); }); - it('should mark all read', function (done) { - socketTopics.markUnread({ uid: adminUid }, tid, function (err) { + it('should mark all read', (done) => { + socketTopics.markUnread({ uid: adminUid }, tid, (err) => { assert.ifError(err); - socketTopics.markAllRead({ uid: adminUid }, {}, function (err) { + socketTopics.markAllRead({ uid: adminUid }, {}, (err) => { assert.ifError(err); - topics.hasReadTopic(tid, adminUid, function (err, hasRead) { + topics.hasReadTopic(tid, adminUid, (err, hasRead) => { assert.ifError(err); assert(hasRead); done(); @@ -1516,12 +1516,12 @@ describe('Topic\'s', function () { }); }); - it('should mark category topics read', function (done) { - socketTopics.markUnread({ uid: adminUid }, tid, function (err) { + it('should mark category topics read', (done) => { + socketTopics.markUnread({ uid: adminUid }, tid, (err) => { assert.ifError(err); - socketTopics.markCategoryTopicsRead({ uid: adminUid }, topic.categoryId, function (err) { + socketTopics.markCategoryTopicsRead({ uid: adminUid }, topic.categoryId, (err) => { assert.ifError(err); - topics.hasReadTopic(tid, adminUid, function (err, hasRead) { + topics.hasReadTopic(tid, adminUid, (err, hasRead) => { assert.ifError(err); assert(hasRead); done(); @@ -1530,36 +1530,36 @@ describe('Topic\'s', function () { }); }); - it('should fail with invalid data', function (done) { - socketTopics.markAsUnreadForAll({ uid: adminUid }, null, function (err) { + it('should fail with invalid data', (done) => { + socketTopics.markAsUnreadForAll({ uid: adminUid }, null, (err) => { assert.equal(err.message, '[[error:invalid-tid]]'); done(); }); }); - it('should fail with invalid data', function (done) { - socketTopics.markAsUnreadForAll({ uid: 0 }, [tid], function (err) { + it('should fail with invalid data', (done) => { + socketTopics.markAsUnreadForAll({ uid: 0 }, [tid], (err) => { assert.equal(err.message, '[[error:no-privileges]]'); done(); }); }); - it('should fail if user is not admin', function (done) { - socketTopics.markAsUnreadForAll({ uid: uid }, [tid], function (err) { + it('should fail if user is not admin', (done) => { + socketTopics.markAsUnreadForAll({ uid: uid }, [tid], (err) => { assert.equal(err.message, '[[error:no-privileges]]'); done(); }); }); - it('should fail if topic does not exist', function (done) { - socketTopics.markAsUnreadForAll({ uid: uid }, [12312313], function (err) { + it('should fail if topic does not exist', (done) => { + socketTopics.markAsUnreadForAll({ uid: uid }, [12312313], (err) => { assert.equal(err.message, '[[error:no-topic]]'); done(); }); }); - it('should mark topic unread for everyone', function (done) { - socketTopics.markAsUnreadForAll({ uid: adminUid }, [tid], function (err) { + it('should mark topic unread for everyone', (done) => { + socketTopics.markAsUnreadForAll({ uid: adminUid }, [tid], (err) => { assert.ifError(err); async.parallel({ adminRead: function (next) { @@ -1568,7 +1568,7 @@ describe('Topic\'s', function () { regularRead: function (next) { topics.hasReadTopic(tid, uid, next); }, - }, function (err, results) { + }, (err, results) => { assert.ifError(err); assert.equal(results.adminRead, false); assert.equal(results.regularRead, false); @@ -1577,15 +1577,15 @@ describe('Topic\'s', function () { }); }); - it('should not do anything if tids is empty array', function (done) { - socketTopics.markAsRead({ uid: adminUid }, [], function (err, markedRead) { + it('should not do anything if tids is empty array', (done) => { + socketTopics.markAsRead({ uid: adminUid }, [], (err, markedRead) => { assert.ifError(err); assert(!markedRead); done(); }); }); - it('should not return topics in category you cant read', function (done) { + it('should not return topics in category you cant read', (done) => { var privateCid; var privateTid; async.waterfall([ @@ -1614,7 +1614,7 @@ describe('Topic\'s', function () { ], done); }); - it('should not return topics in category you ignored/not watching', function (done) { + it('should not return topics in category you ignored/not watching', (done) => { var ignoredCid; var tid; async.waterfall([ @@ -1646,7 +1646,7 @@ describe('Topic\'s', function () { ], done); }); - it('should not return topic as unread if new post is from blocked user', function (done) { + it('should not return topic as unread if new post is from blocked user', (done) => { var blockedUid; var topic; async.waterfall([ @@ -1674,7 +1674,7 @@ describe('Topic\'s', function () { ], done); }); - it('should not return topic as unread if topic is deleted', async function () { + it('should not return topic as unread if topic is deleted', async () => { const uid = await User.create({ username: 'regularJoe' }); const result = await topics.post({ uid: adminUid, title: 'deleted unread', content: 'not unread', cid: categoryObj.cid }); await topics.delete(result.topicData.tid, adminUid); @@ -1683,11 +1683,11 @@ describe('Topic\'s', function () { }); }); - describe('tags', function () { + describe('tags', () => { var socketTopics = require('../src/socket.io/topics'); var socketAdmin = require('../src/socket.io/admin'); - before(function (done) { + before((done) => { async.series([ function (next) { topics.post({ uid: adminUid, tags: ['php', 'nosql', 'psql', 'nodebb'], title: 'topic title 1', content: 'topic 1 content', cid: topic.categoryId }, next); @@ -1695,50 +1695,50 @@ describe('Topic\'s', function () { function (next) { topics.post({ uid: adminUid, tags: ['javascript', 'mysql', 'python', 'nodejs'], title: 'topic title 2', content: 'topic 2 content', cid: topic.categoryId }, next); }, - ], function (err) { + ], (err) => { assert.ifError(err); done(); }); }); - it('should return empty array if query is falsy', function (done) { - socketTopics.autocompleteTags({ uid: adminUid }, { query: '' }, function (err, data) { + it('should return empty array if query is falsy', (done) => { + socketTopics.autocompleteTags({ uid: adminUid }, { query: '' }, (err, data) => { assert.ifError(err); assert.deepEqual([], data); done(); }); }); - it('should autocomplete tags', function (done) { - socketTopics.autocompleteTags({ uid: adminUid }, { query: 'p' }, function (err, data) { + it('should autocomplete tags', (done) => { + socketTopics.autocompleteTags({ uid: adminUid }, { query: 'p' }, (err, data) => { assert.ifError(err); - ['php', 'psql', 'python'].forEach(function (tag) { + ['php', 'psql', 'python'].forEach((tag) => { assert.notEqual(data.indexOf(tag), -1); }); done(); }); }); - it('should return empty array if query is falsy', function (done) { - socketTopics.searchTags({ uid: adminUid }, { query: '' }, function (err, data) { + it('should return empty array if query is falsy', (done) => { + socketTopics.searchTags({ uid: adminUid }, { query: '' }, (err, data) => { assert.ifError(err); assert.deepEqual([], data); done(); }); }); - it('should search tags', function (done) { - socketTopics.searchTags({ uid: adminUid }, { query: 'no' }, function (err, data) { + it('should search tags', (done) => { + socketTopics.searchTags({ uid: adminUid }, { query: 'no' }, (err, data) => { assert.ifError(err); - ['nodebb', 'nodejs', 'nosql'].forEach(function (tag) { + ['nodebb', 'nodejs', 'nosql'].forEach((tag) => { assert.notEqual(data.indexOf(tag), -1); }); done(); }); }); - it('should return empty array if query is falsy', function (done) { - socketTopics.searchAndLoadTags({ uid: adminUid }, { query: '' }, function (err, data) { + it('should return empty array if query is falsy', (done) => { + socketTopics.searchAndLoadTags({ uid: adminUid }, { query: '' }, (err, data) => { assert.ifError(err); assert.equal(data.matchCount, 0); assert.equal(data.pageCount, 1); @@ -1747,8 +1747,8 @@ describe('Topic\'s', function () { }); }); - it('should search and load tags', function (done) { - socketTopics.searchAndLoadTags({ uid: adminUid }, { query: 'no' }, function (err, data) { + it('should search and load tags', (done) => { + socketTopics.searchAndLoadTags({ uid: adminUid }, { query: 'no' }, (err, data) => { assert.ifError(err); assert.equal(data.matchCount, 3); assert.equal(data.pageCount, 1); @@ -1763,15 +1763,15 @@ describe('Topic\'s', function () { }); }); - it('should return error if data is invalid', function (done) { - socketTopics.loadMoreTags({ uid: adminUid }, { after: 'asd' }, function (err) { + it('should return error if data is invalid', (done) => { + socketTopics.loadMoreTags({ uid: adminUid }, { after: 'asd' }, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); }); - it('should load more tags', function (done) { - socketTopics.loadMoreTags({ uid: adminUid }, { after: 0 }, function (err, data) { + it('should load more tags', (done) => { + socketTopics.loadMoreTags({ uid: adminUid }, { after: 0 }, (err, data) => { assert.ifError(err); assert(Array.isArray(data.tags)); assert.equal(data.nextStart, 100); @@ -1779,31 +1779,31 @@ describe('Topic\'s', function () { }); }); - it('should error if data is invalid', function (done) { - socketAdmin.tags.create({ uid: adminUid }, null, function (err) { + it('should error if data is invalid', (done) => { + socketAdmin.tags.create({ uid: adminUid }, null, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); }); - it('should error if tag is invalid', function (done) { - socketAdmin.tags.create({ uid: adminUid }, { tag: '' }, function (err) { + it('should error if tag is invalid', (done) => { + socketAdmin.tags.create({ uid: adminUid }, { tag: '' }, (err) => { assert.equal(err.message, '[[error:invalid-tag]]'); done(); }); }); - it('should error if tag is too short', function (done) { - socketAdmin.tags.create({ uid: adminUid }, { tag: 'as' }, function (err) { + it('should error if tag is too short', (done) => { + socketAdmin.tags.create({ uid: adminUid }, { tag: 'as' }, (err) => { assert.equal(err.message, '[[error:tag-too-short]]'); done(); }); }); - it('should create empty tag', function (done) { - socketAdmin.tags.create({ uid: adminUid }, { tag: 'emptytag' }, function (err) { + it('should create empty tag', (done) => { + socketAdmin.tags.create({ uid: adminUid }, { tag: 'emptytag' }, (err) => { assert.ifError(err); - db.sortedSetScore('tags:topic:count', 'emptytag', function (err, score) { + db.sortedSetScore('tags:topic:count', 'emptytag', (err, score) => { assert.ifError(err); assert.equal(score, 0); done(); @@ -1811,10 +1811,10 @@ describe('Topic\'s', function () { }); }); - it('should do nothing if tag exists', function (done) { - socketAdmin.tags.create({ uid: adminUid }, { tag: 'emptytag' }, function (err) { + it('should do nothing if tag exists', (done) => { + socketAdmin.tags.create({ uid: adminUid }, { tag: 'emptytag' }, (err) => { assert.ifError(err); - db.sortedSetScore('tags:topic:count', 'emptytag', function (err, score) { + db.sortedSetScore('tags:topic:count', 'emptytag', (err, score) => { assert.ifError(err); assert.equal(score, 0); done(); @@ -1822,31 +1822,31 @@ describe('Topic\'s', function () { }); }); - it('should error if data is invalid', function (done) { - socketAdmin.tags.update({ uid: adminUid }, null, function (err) { + it('should error if data is invalid', (done) => { + socketAdmin.tags.update({ uid: adminUid }, null, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); }); - it('should error if data is not an array', function (done) { + it('should error if data is not an array', (done) => { socketAdmin.tags.update({ uid: adminUid }, { bgColor: '#ff0000', color: '#00ff00', - }, function (err) { + }, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); }); - it('should update tag', function (done) { + it('should update tag', (done) => { socketAdmin.tags.update({ uid: adminUid }, [{ value: 'emptytag', bgColor: '#ff0000', color: '#00ff00', - }], function (err) { + }], (err) => { assert.ifError(err); - db.getObject('tag:emptytag', function (err, data) { + db.getObject('tag:emptytag', (err, data) => { assert.ifError(err); assert.equal(data.bgColor, '#ff0000'); assert.equal(data.color, '#00ff00'); @@ -1855,7 +1855,7 @@ describe('Topic\'s', function () { }); }); - it('should rename tags', function (done) { + it('should rename tags', (done) => { async.series({ topic1: function (next) { topics.post({ uid: adminUid, tags: ['plugins'], title: 'topic tagged with plugins', content: 'topic 1 content', cid: topic.categoryId }, next); @@ -1863,17 +1863,17 @@ describe('Topic\'s', function () { topic2: function (next) { topics.post({ uid: adminUid, tags: ['plugin'], title: 'topic tagged with plugin', content: 'topic 2 content', cid: topic.categoryId }, next); }, - }, function (err, result) { + }, (err, result) => { assert.ifError(err); socketAdmin.tags.rename({ uid: adminUid }, [{ value: 'plugin', newName: 'plugins', - }], function (err) { + }], (err) => { assert.ifError(err); - topics.getTagTids('plugins', 0, -1, function (err, tids) { + topics.getTagTids('plugins', 0, -1, (err, tids) => { assert.ifError(err); assert.equal(tids.length, 2); - topics.getTopicTags(result.topic2.topicData.tid, function (err, tags) { + topics.getTopicTags(result.topic2.topicData.tid, (err, tags) => { assert.ifError(err); assert.equal(tags.length, 1); assert.equal(tags[0], 'plugins'); @@ -1884,13 +1884,13 @@ describe('Topic\'s', function () { }); }); - it('should return related topics', function (done) { + it('should return related topics', (done) => { var meta = require('../src/meta'); meta.config.maximumRelatedTopics = 2; var topicData = { tags: [{ value: 'javascript' }], }; - topics.getRelatedTopics(topicData, 0, function (err, data) { + topics.getRelatedTopics(topicData, 0, (err, data) => { assert.ifError(err); assert(Array.isArray(data)); assert.equal(data[0].title, 'topic title 2'); @@ -1899,26 +1899,26 @@ describe('Topic\'s', function () { }); }); - it('should return error with invalid data', function (done) { - socketAdmin.tags.deleteTags({ uid: adminUid }, null, function (err) { + it('should return error with invalid data', (done) => { + socketAdmin.tags.deleteTags({ uid: adminUid }, null, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); }); - it('should do nothing if arrays is empty', function (done) { - socketAdmin.tags.deleteTags({ uid: adminUid }, { tags: [] }, function (err) { + it('should do nothing if arrays is empty', (done) => { + socketAdmin.tags.deleteTags({ uid: adminUid }, { tags: [] }, (err) => { assert.ifError(err); done(); }); }); - it('should delete tags', function (done) { - socketAdmin.tags.create({ uid: adminUid }, { tag: 'emptytag2' }, function (err) { + it('should delete tags', (done) => { + socketAdmin.tags.create({ uid: adminUid }, { tag: 'emptytag2' }, (err) => { assert.ifError(err); - socketAdmin.tags.deleteTags({ uid: adminUid }, { tags: ['emptytag', 'emptytag2', 'nodebb', 'nodejs'] }, function (err) { + socketAdmin.tags.deleteTags({ uid: adminUid }, { tags: ['emptytag', 'emptytag2', 'nodebb', 'nodejs'] }, (err) => { assert.ifError(err); - db.getObjects(['tag:emptytag', 'tag:emptytag2'], function (err, data) { + db.getObjects(['tag:emptytag', 'tag:emptytag2'], (err, data) => { assert.ifError(err); assert(!data[0]); assert(!data[1]); @@ -1928,10 +1928,10 @@ describe('Topic\'s', function () { }); }); - it('should delete tag', function (done) { - topics.deleteTag('javascript', function (err) { + it('should delete tag', (done) => { + topics.deleteTag('javascript', (err) => { assert.ifError(err); - db.getObject('tag:javascript', function (err, data) { + db.getObject('tag:javascript', (err, data) => { assert.ifError(err); assert(!data); done(); @@ -1939,7 +1939,7 @@ describe('Topic\'s', function () { }); }); - it('should delete category tag as well', async function () { + it('should delete category tag as well', async () => { const category = await categories.create({ name: 'delete category' }); const cid = category.cid; await topics.post({ uid: adminUid, tags: ['willbedeleted', 'notthis'], title: 'tag topic', content: 'topic 1 content', cid: cid }); @@ -2052,7 +2052,7 @@ describe('Topic\'s', function () { ]); }); - it('should update counts correctly if topic is moved between categories', async function () { + it('should update counts correctly if topic is moved between categories', async () => { const category1 = await categories.create({ name: 'tag category 2' }); const category2 = await categories.create({ name: 'tag category 2' }); const cid1 = category1.cid; @@ -2089,17 +2089,17 @@ describe('Topic\'s', function () { }); }); - describe('follow/unfollow', function () { + describe('follow/unfollow', () => { var socketTopics = require('../src/socket.io/topics'); var tid; var followerUid; - before(function (done) { - User.create({ username: 'follower' }, function (err, uid) { + before((done) => { + User.create({ username: 'follower' }, (err, uid) => { if (err) { return done(err); } followerUid = uid; - topics.post({ uid: adminUid, title: 'topic title', content: 'some content', cid: topic.categoryId }, function (err, result) { + topics.post({ uid: adminUid, title: 'topic title', content: 'some content', cid: topic.categoryId }, (err, result) => { if (err) { return done(err); } @@ -2109,17 +2109,17 @@ describe('Topic\'s', function () { }); }); - it('should error if not logged in', function (done) { - socketTopics.changeWatching({ uid: 0 }, { tid: tid, type: 'ignore' }, function (err) { + it('should error if not logged in', (done) => { + socketTopics.changeWatching({ uid: 0 }, { tid: tid, type: 'ignore' }, (err) => { assert.equal(err.message, '[[error:not-logged-in]]'); done(); }); }); - it('should filter ignoring uids', function (done) { - socketTopics.changeWatching({ uid: followerUid }, { tid: tid, type: 'ignore' }, function (err) { + it('should filter ignoring uids', (done) => { + socketTopics.changeWatching({ uid: followerUid }, { tid: tid, type: 'ignore' }, (err) => { assert.ifError(err); - topics.filterIgnoringUids(tid, [adminUid, followerUid], function (err, uids) { + topics.filterIgnoringUids(tid, [adminUid, followerUid], (err, uids) => { assert.ifError(err); assert.equal(uids.length, 1); assert.equal(uids[0], adminUid); @@ -2128,25 +2128,25 @@ describe('Topic\'s', function () { }); }); - it('should error with invalid data', function (done) { - socketTopics.changeWatching({ uid: followerUid }, {}, function (err) { + it('should error with invalid data', (done) => { + socketTopics.changeWatching({ uid: followerUid }, {}, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); }); - it('should error with invalid type', function (done) { - socketTopics.changeWatching({ uid: followerUid }, { tid: tid, type: 'derp' }, function (err) { + it('should error with invalid type', (done) => { + socketTopics.changeWatching({ uid: followerUid }, { tid: tid, type: 'derp' }, (err) => { assert.equal(err.message, '[[error:invalid-command]]'); done(); }); }); - it('should follow topic', function (done) { - topics.toggleFollow(tid, followerUid, function (err, isFollowing) { + it('should follow topic', (done) => { + topics.toggleFollow(tid, followerUid, (err, isFollowing) => { assert.ifError(err); assert(isFollowing); - socketTopics.isFollowed({ uid: followerUid }, tid, function (err, isFollowing) { + socketTopics.isFollowed({ uid: followerUid }, tid, (err, isFollowing) => { assert.ifError(err); assert(isFollowing); done(); @@ -2155,15 +2155,15 @@ describe('Topic\'s', function () { }); }); - describe('topics search', function () { - it('should error with invalid data', function (done) { - socketTopics.search({ uid: adminUid }, null, function (err) { + describe('topics search', () => { + it('should error with invalid data', (done) => { + socketTopics.search({ uid: adminUid }, null, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); }); - it('should return results', function (done) { + it('should return results', (done) => { var plugins = require('../src/plugins'); plugins.hooks.register('myTestPlugin', { hook: 'filter:topic.search', @@ -2171,7 +2171,7 @@ describe('Topic\'s', function () { callback(null, [1, 2, 3]); }, }); - socketTopics.search({ uid: adminUid }, { tid: topic.tid, term: 'test' }, function (err, results) { + socketTopics.search({ uid: adminUid }, { tid: topic.tid, term: 'test' }, (err, results) => { assert.ifError(err); assert.deepEqual(results, [1, 2, 3]); done(); @@ -2179,18 +2179,18 @@ describe('Topic\'s', function () { }); }); - it('should check if user is moderator', function (done) { - socketTopics.isModerator({ uid: adminUid }, topic.tid, function (err, isModerator) { + it('should check if user is moderator', (done) => { + socketTopics.isModerator({ uid: adminUid }, topic.tid, (err, isModerator) => { assert.ifError(err); assert(!isModerator); done(); }); }); - describe('teasers', function () { + describe('teasers', () => { var topic1; var topic2; - before(function (done) { + before((done) => { async.series([ function (next) { topics.post({ uid: adminUid, title: 'topic 1', content: 'content 1', cid: categoryObj.cid }, next); @@ -2198,7 +2198,7 @@ describe('Topic\'s', function () { function (next) { topics.post({ uid: adminUid, title: 'topic 2', content: 'content 2', cid: categoryObj.cid }, next); }, - ], function (err, results) { + ], (err, results) => { assert.ifError(err); topic1 = results[0]; topic2 = results[1]; @@ -2206,31 +2206,31 @@ describe('Topic\'s', function () { }); }); - after(function (done) { + after((done) => { meta.config.teaserPost = ''; done(); }); - it('should return empty array if first param is empty', function (done) { - topics.getTeasers([], 1, function (err, teasers) { + it('should return empty array if first param is empty', (done) => { + topics.getTeasers([], 1, (err, teasers) => { assert.ifError(err); assert.equal(0, teasers.length); done(); }); }); - it('should get teasers with 2 params', function (done) { - topics.getTeasers([topic1.topicData, topic2.topicData], 1, function (err, teasers) { + it('should get teasers with 2 params', (done) => { + topics.getTeasers([topic1.topicData, topic2.topicData], 1, (err, teasers) => { assert.ifError(err); assert.deepEqual([undefined, undefined], teasers); done(); }); }); - it('should get teasers with first posts', function (done) { + it('should get teasers with first posts', (done) => { meta.config.teaserPost = 'first'; - topics.getTeasers([topic1.topicData, topic2.topicData], 1, function (err, teasers) { + topics.getTeasers([topic1.topicData, topic2.topicData], 1, (err, teasers) => { assert.ifError(err); assert.equal(2, teasers.length); assert(teasers[0]); @@ -2242,8 +2242,8 @@ describe('Topic\'s', function () { }); }); - it('should get teasers even if one topic is falsy', function (done) { - topics.getTeasers([null, topic2.topicData], 1, function (err, teasers) { + it('should get teasers even if one topic is falsy', (done) => { + topics.getTeasers([null, topic2.topicData], 1, (err, teasers) => { assert.ifError(err); assert.equal(2, teasers.length); assert.equal(undefined, teasers[0]); @@ -2255,12 +2255,12 @@ describe('Topic\'s', function () { }); }); - it('should get teasers with last posts', function (done) { + it('should get teasers with last posts', (done) => { meta.config.teaserPost = 'last-post'; - topics.reply({ uid: adminUid, content: 'reply 1 content', tid: topic1.topicData.tid }, function (err, result) { + topics.reply({ uid: adminUid, content: 'reply 1 content', tid: topic1.topicData.tid }, (err, result) => { assert.ifError(err); topic1.topicData.teaserPid = result.pid; - topics.getTeasers([topic1.topicData, topic2.topicData], 1, function (err, teasers) { + topics.getTeasers([topic1.topicData, topic2.topicData], 1, (err, teasers) => { assert.ifError(err); assert(teasers[0]); assert(teasers[1]); @@ -2271,8 +2271,8 @@ describe('Topic\'s', function () { }); }); - it('should get teasers by tids', function (done) { - topics.getTeasersByTids([topic2.topicData.tid, topic1.topicData.tid], 1, function (err, teasers) { + it('should get teasers by tids', (done) => { + topics.getTeasersByTids([topic2.topicData.tid, topic1.topicData.tid], 1, (err, teasers) => { assert.ifError(err); assert(2, teasers.length); assert.equal(teasers[1].content, 'reply 1 content'); @@ -2280,16 +2280,16 @@ describe('Topic\'s', function () { }); }); - it('should return empty array ', function (done) { - topics.getTeasersByTids([], 1, function (err, teasers) { + it('should return empty array ', (done) => { + topics.getTeasersByTids([], 1, (err, teasers) => { assert.ifError(err); assert.equal(0, teasers.length); done(); }); }); - it('should get teaser by tid', function (done) { - topics.getTeaser(topic2.topicData.tid, 1, function (err, teaser) { + it('should get teaser by tid', (done) => { + topics.getTeaser(topic2.topicData.tid, 1, (err, teaser) => { assert.ifError(err); assert(teaser); assert.equal(teaser.content, 'content 2'); @@ -2297,7 +2297,7 @@ describe('Topic\'s', function () { }); }); - it('should not return teaser if user is blocked', function (done) { + it('should not return teaser if user is blocked', (done) => { var blockedUid; async.waterfall([ function (next) { @@ -2321,10 +2321,10 @@ describe('Topic\'s', function () { }); }); - describe('tag privilege', function () { + describe('tag privilege', () => { var uid; var cid; - before(function (done) { + before((done) => { async.waterfall([ function (next) { User.create({ username: 'tag_poster' }, next); @@ -2340,37 +2340,35 @@ describe('Topic\'s', function () { ], done); }); - it('should fail to post if user does not have tag privilege', function (done) { - privileges.categories.rescind(['groups:topics:tag'], cid, 'registered-users', function (err) { + it('should fail to post if user does not have tag privilege', (done) => { + privileges.categories.rescind(['groups:topics:tag'], cid, 'registered-users', (err) => { assert.ifError(err); - topics.post({ uid: uid, cid: cid, tags: ['tag1'], title: 'topic with tags', content: 'some content here' }, function (err) { + topics.post({ uid: uid, cid: cid, tags: ['tag1'], title: 'topic with tags', content: 'some content here' }, (err) => { assert.equal(err.message, '[[error:no-privileges]]'); done(); }); }); }); - it('should fail to edit if user does not have tag privilege', function (done) { - topics.post({ uid: uid, cid: cid, title: 'topic with tags', content: 'some content here' }, function (err, result) { + it('should fail to edit if user does not have tag privilege', (done) => { + topics.post({ uid: uid, cid: cid, title: 'topic with tags', content: 'some content here' }, (err, result) => { assert.ifError(err); var pid = result.postData.pid; - posts.edit({ pid: pid, uid: uid, content: 'edited content', tags: ['tag2'] }, function (err) { + posts.edit({ pid: pid, uid: uid, content: 'edited content', tags: ['tag2'] }, (err) => { assert.equal(err.message, '[[error:no-privileges]]'); done(); }); }); }); - it('should be able to edit topic and add tags if allowed', function (done) { - privileges.categories.give(['groups:topics:tag'], cid, 'registered-users', function (err) { + it('should be able to edit topic and add tags if allowed', (done) => { + privileges.categories.give(['groups:topics:tag'], cid, 'registered-users', (err) => { assert.ifError(err); - topics.post({ uid: uid, cid: cid, tags: ['tag1'], title: 'topic with tags', content: 'some content here' }, function (err, result) { + topics.post({ uid: uid, cid: cid, tags: ['tag1'], title: 'topic with tags', content: 'some content here' }, (err, result) => { assert.ifError(err); - posts.edit({ pid: result.postData.pid, uid: uid, content: 'edited content', tags: ['tag1', 'tag2'] }, function (err, result) { + posts.edit({ pid: result.postData.pid, uid: uid, content: 'edited content', tags: ['tag1', 'tag2'] }, (err, result) => { assert.ifError(err); - var tags = result.topic.tags.map(function (tag) { - return tag.value; - }); + var tags = result.topic.tags.map(tag => tag.value); assert(tags.includes('tag1')); assert(tags.includes('tag2')); done(); @@ -2380,7 +2378,7 @@ describe('Topic\'s', function () { }); }); - describe('topic merge', function () { + describe('topic merge', () => { var uid; var topic1Data; var topic2Data; @@ -2390,7 +2388,7 @@ describe('Topic\'s', function () { return await topics.getTopicWithPosts(topicData, `tid:${topicData.tid}:posts`, adminUid, 0, 19, false); } - before(function (done) { + before((done) => { async.waterfall([ function (next) { User.create({ username: 'mergevictim' }, next); @@ -2413,21 +2411,21 @@ describe('Topic\'s', function () { ], done); }); - it('should error if data is not an array', function (done) { - socketTopics.merge({ uid: 0 }, null, function (err) { + it('should error if data is not an array', (done) => { + socketTopics.merge({ uid: 0 }, null, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); }); - it('should error if user does not have privileges', function (done) { - socketTopics.merge({ uid: 0 }, { tids: [topic2Data.tid, topic1Data.tid] }, function (err) { + it('should error if user does not have privileges', (done) => { + socketTopics.merge({ uid: 0 }, { tids: [topic2Data.tid, topic1Data.tid] }, (err) => { assert.equal(err.message, '[[error:no-privileges]]'); done(); }); }); - it('should merge 2 topics', async function () { + it('should merge 2 topics', async () => { await socketTopics.merge({ uid: adminUid }, { tids: [topic2Data.tid, topic1Data.tid], }); @@ -2448,8 +2446,8 @@ describe('Topic\'s', function () { assert.equal(topic1.title, 'topic 1'); }); - it('should return properly for merged topic', function (done) { - request(`${nconf.get('url')}/api/topic/${topic2Data.slug}`, { jar: adminJar, json: true }, function (err, response, body) { + it('should return properly for merged topic', (done) => { + request(`${nconf.get('url')}/api/topic/${topic2Data.slug}`, { jar: adminJar, json: true }, (err, response, body) => { assert.ifError(err); assert.equal(response.statusCode, 200); assert(body); @@ -2458,7 +2456,7 @@ describe('Topic\'s', function () { }); }); - it('should merge 2 topics with options mainTid', async function () { + it('should merge 2 topics with options mainTid', async () => { const topic1Result = await topics.post({ uid: uid, cid: categoryObj.cid, title: 'topic 1', content: 'topic 1 OP' }); const topic2Result = await topics.post({ uid: uid, cid: categoryObj.cid, title: 'topic 2', content: 'topic 2 OP' }); await topics.reply({ uid: uid, content: 'topic 1 reply', tid: topic1Result.topicData.tid }); @@ -2486,7 +2484,7 @@ describe('Topic\'s', function () { assert.equal(topic2.title, 'topic 2'); }); - it('should merge 2 topics with options newTopicTitle', async function () { + it('should merge 2 topics with options newTopicTitle', async () => { const topic1Result = await topics.post({ uid: uid, cid: categoryObj.cid, title: 'topic 1', content: 'topic 1 OP' }); const topic2Result = await topics.post({ uid: uid, cid: categoryObj.cid, title: 'topic 2', content: 'topic 2 OP' }); await topics.reply({ uid: uid, content: 'topic 1 reply', tid: topic1Result.topicData.tid }); @@ -2518,10 +2516,10 @@ describe('Topic\'s', function () { }); }); - describe('sorted topics', function () { - it('should get sorted topics in category', function (done) { + describe('sorted topics', () => { + it('should get sorted topics in category', (done) => { var filters = ['', 'watched', 'unreplied', 'new']; - async.map(filters, function (filter, next) { + async.map(filters, (filter, next) => { topics.getSortedTopics({ cids: [topic.categoryId], uid: topic.userId, @@ -2530,10 +2528,10 @@ describe('Topic\'s', function () { filter: filter, sort: 'votes', }, next); - }, function (err, data) { + }, (err, data) => { assert.ifError(err); assert(data); - data.forEach(function (filterTopics) { + data.forEach((filterTopics) => { assert(Array.isArray(filterTopics.topics)); }); done(); diff --git a/test/translator.js b/test/translator.js index c5eafdf08a..d33b326e15 100644 --- a/test/translator.js +++ b/test/translator.js @@ -7,231 +7,231 @@ var shim = require('../public/src/modules/translator.js'); var Translator = shim.Translator; var db = require('./mocks/databasemock'); -describe('Translator shim', function () { - describe('.translate()', function () { - it('should translate correctly', function (done) { - shim.translate('[[global:pagination.out_of, (foobar), [[global:home]]]]', function (translated) { +describe('Translator shim', () => { + describe('.translate()', () => { + it('should translate correctly', (done) => { + shim.translate('[[global:pagination.out_of, (foobar), [[global:home]]]]', (translated) => { assert.strictEqual(translated, '(foobar) out of Home'); done(); }); }); - it('should accept a language parameter and adjust accordingly', function (done) { - shim.translate('[[global:home]]', 'de', function (translated) { + it('should accept a language parameter and adjust accordingly', (done) => { + shim.translate('[[global:home]]', 'de', (translated) => { assert.strictEqual(translated, 'Übersicht'); done(); }); }); - it('should translate empty string properly', function (done) { - shim.translate('', 'en-GB', function (translated) { + it('should translate empty string properly', (done) => { + shim.translate('', 'en-GB', (translated) => { assert.strictEqual(translated, ''); done(); }); }); - it('should translate empty string properly', async function () { + it('should translate empty string properly', async () => { const translated = await shim.translate('', 'en-GB'); assert.strictEqual(translated, ''); }); }); }); -describe('new Translator(language)', function () { - it('should throw if not passed a language', function (done) { - assert.throws(function () { +describe('new Translator(language)', () => { + it('should throw if not passed a language', (done) => { + assert.throws(() => { new Translator(); }, /language string/); done(); }); - describe('.translate()', function () { - it('should handle basic translations', function () { + describe('.translate()', () => { + it('should handle basic translations', () => { var translator = Translator.create('en-GB'); - return translator.translate('[[global:home]]').then(function (translated) { + return translator.translate('[[global:home]]').then((translated) => { assert.strictEqual(translated, 'Home'); }); }); - it('should handle language keys in regular text', function () { + it('should handle language keys in regular text', () => { var translator = Translator.create('en-GB'); - return translator.translate('Let\'s go [[global:home]]').then(function (translated) { + return translator.translate('Let\'s go [[global:home]]').then((translated) => { assert.strictEqual(translated, 'Let\'s go Home'); }); }); - it('should handle language keys in regular text with another language specified', function () { + it('should handle language keys in regular text with another language specified', () => { var translator = Translator.create('de'); - return translator.translate('[[global:home]] test').then(function (translated) { + return translator.translate('[[global:home]] test').then((translated) => { assert.strictEqual(translated, 'Übersicht test'); }); }); - it('should handle language keys with parameters', function () { + it('should handle language keys with parameters', () => { var translator = Translator.create('en-GB'); - return translator.translate('[[global:pagination.out_of, 1, 5]]').then(function (translated) { + return translator.translate('[[global:pagination.out_of, 1, 5]]').then((translated) => { assert.strictEqual(translated, '1 out of 5'); }); }); - it('should handle language keys inside language keys', function () { + it('should handle language keys inside language keys', () => { var translator = Translator.create('en-GB'); - return translator.translate('[[notifications:outgoing_link_message, [[global:guest]]]]').then(function (translated) { + return translator.translate('[[notifications:outgoing_link_message, [[global:guest]]]]').then((translated) => { assert.strictEqual(translated, 'You are now leaving Guest'); }); }); - it('should handle language keys inside language keys with multiple parameters', function () { + it('should handle language keys inside language keys with multiple parameters', () => { var translator = Translator.create('en-GB'); - return translator.translate('[[notifications:user_posted_to, [[global:guest]], My Topic]]').then(function (translated) { + return translator.translate('[[notifications:user_posted_to, [[global:guest]], My Topic]]').then((translated) => { assert.strictEqual(translated, 'Guest has posted a reply to: My Topic'); }); }); - it('should handle language keys inside language keys with all parameters as language keys', function () { + it('should handle language keys inside language keys with all parameters as language keys', () => { var translator = Translator.create('en-GB'); - return translator.translate('[[notifications:user_posted_to, [[global:guest]], [[global:guest]]]]').then(function (translated) { + return translator.translate('[[notifications:user_posted_to, [[global:guest]], [[global:guest]]]]').then((translated) => { assert.strictEqual(translated, 'Guest has posted a reply to: Guest'); }); }); - it('should properly handle parameters that contain square brackets', function () { + it('should properly handle parameters that contain square brackets', () => { var translator = Translator.create('en-GB'); - return translator.translate('[[global:pagination.out_of, [guest], [[global:home]]]]').then(function (translated) { + return translator.translate('[[global:pagination.out_of, [guest], [[global:home]]]]').then((translated) => { assert.strictEqual(translated, '[guest] out of Home'); }); }); - it('should properly handle parameters that contain parentheses', function () { + it('should properly handle parameters that contain parentheses', () => { var translator = Translator.create('en-GB'); - return translator.translate('[[global:pagination.out_of, (foobar), [[global:home]]]]').then(function (translated) { + return translator.translate('[[global:pagination.out_of, (foobar), [[global:home]]]]').then((translated) => { assert.strictEqual(translated, '(foobar) out of Home'); }); }); - it('should escape language key parameters with HTML in them', function () { + it('should escape language key parameters with HTML in them', () => { var translator = Translator.create('en-GB'); var key = '[[global:403.login, test]]'; - return translator.translate(key).then(function (translated) { + return translator.translate(key).then((translated) => { assert.strictEqual(translated, 'Perhaps you should try logging in?'); }); }); - it('should not unescape html in parameters', function () { + it('should not unescape html in parameters', () => { var translator = Translator.create('en-GB'); var key = '[[pages:tag, some&tag]]'; - return translator.translate(key).then(function (translated) { + return translator.translate(key).then((translated) => { assert.strictEqual(translated, 'Topics tagged under "some&tag"'); }); }); - it('should translate escaped translation arguments properly', function () { + it('should translate escaped translation arguments properly', () => { // https://github.com/NodeBB/NodeBB/issues/9206 var translator = Translator.create('en-GB'); var key = '[[notifications:upvoted_your_post_in, test1, error: Error: [[error:group-name-too-long]] on NodeBB Upgrade]]'; - return translator.translate(key).then(function (translated) { + return translator.translate(key).then((translated) => { assert.strictEqual(translated, 'test1 has upvoted your post in error: Error: [[error:group-name-too-long]] on NodeBB Upgrade.'); }); }); - it('should properly escape and ignore % and \\, in arguments', function () { + it('should properly escape and ignore % and \\, in arguments', () => { var translator = Translator.create('en-GB'); var title = 'Test 1\\, 2\\, 3 %2 salmon'; var key = `[[topic:composer.replying_to, ${title}]]`; - return translator.translate(key).then(function (translated) { + return translator.translate(key).then((translated) => { assert.strictEqual(translated, 'Replying to Test 1, 2, 3 %2 salmon'); }); }); - it('should not escape regular %', function () { + it('should not escape regular %', () => { var translator = Translator.create('en-GB'); var title = '3 % salmon'; var key = `[[topic:composer.replying_to, ${title}]]`; - return translator.translate(key).then(function (translated) { + return translator.translate(key).then((translated) => { assert.strictEqual(translated, 'Replying to 3 % salmon'); }); }); - it('should not translate [[derp] some text', function () { + it('should not translate [[derp] some text', () => { var translator = Translator.create('en-GB'); - return translator.translate('[[derp] some text').then(function (translated) { + return translator.translate('[[derp] some text').then((translated) => { assert.strictEqual('[[derp] some text', translated); }); }); - it('should not translate [[derp]] some text', function () { + it('should not translate [[derp]] some text', () => { var translator = Translator.create('en-GB'); - return translator.translate('[[derp]] some text').then(function (translated) { + return translator.translate('[[derp]] some text').then((translated) => { assert.strictEqual('[[derp]] some text', translated); }); }); - it('should not translate [[derp:xyz] some text', function () { + it('should not translate [[derp:xyz] some text', () => { var translator = Translator.create('en-GB'); - return translator.translate('[[derp:xyz] some text').then(function (translated) { + return translator.translate('[[derp:xyz] some text').then((translated) => { assert.strictEqual('[[derp:xyz] some text', translated); }); }); - it('should translate keys with slashes properly', function () { + it('should translate keys with slashes properly', () => { var translator = Translator.create('en-GB'); - return translator.translate('[[pages:users/latest]]').then(function (translated) { + return translator.translate('[[pages:users/latest]]').then((translated) => { assert.strictEqual(translated, 'Latest Users'); }); }); - it('should use key for unknown keys without arguments', function () { + it('should use key for unknown keys without arguments', () => { var translator = Translator.create('en-GB'); - return translator.translate('[[unknown:key.without.args]]').then(function (translated) { + return translator.translate('[[unknown:key.without.args]]').then((translated) => { assert.strictEqual(translated, 'key.without.args'); }); }); - it('should use backup for unknown keys with arguments', function () { + it('should use backup for unknown keys with arguments', () => { var translator = Translator.create('en-GB'); - return translator.translate('[[unknown:key.with.args, arguments are here, derpity, derp]]').then(function (translated) { + return translator.translate('[[unknown:key.with.args, arguments are here, derpity, derp]]').then((translated) => { assert.strictEqual(translated, 'unknown:key.with.args, arguments are here, derpity, derp'); }); }); - it('should ignore unclosed tokens', function () { + it('should ignore unclosed tokens', () => { var translator = Translator.create('en-GB'); - return translator.translate('here is some stuff and other things [[abc:xyz, other random stuff should be fine here [[global:home]] and more things [[pages:users/latest]]').then(function (translated) { + return translator.translate('here is some stuff and other things [[abc:xyz, other random stuff should be fine here [[global:home]] and more things [[pages:users/latest]]').then((translated) => { assert.strictEqual(translated, 'here is some stuff and other things abc:xyz, other random stuff should be fine here Home and more things Latest Users'); }); }); }); }); -describe('Translator.create()', function () { - it('should return an instance of Translator', function (done) { +describe('Translator.create()', () => { + it('should return an instance of Translator', (done) => { var translator = Translator.create('en-GB'); assert(translator instanceof Translator); done(); }); - it('should return the same object for the same language', function (done) { + it('should return the same object for the same language', (done) => { var one = Translator.create('de'); var two = Translator.create('de'); assert.strictEqual(one, two); done(); }); - it('should default to defaultLang', function (done) { + it('should default to defaultLang', (done) => { var translator = Translator.create(); assert.strictEqual(translator.lang, 'en-GB'); @@ -239,41 +239,39 @@ describe('Translator.create()', function () { }); }); -describe('Translator modules', function () { - it('should work before registered', function () { +describe('Translator modules', () => { + it('should work before registered', () => { var translator = Translator.create(); - Translator.registerModule('test-custom-integer-format', function (lang) { - return function (key, args) { - var num = parseInt(args[0], 10) || 0; - if (key === 'binary') { - return num.toString(2); - } - if (key === 'hex') { - return num.toString(16); - } - if (key === 'octal') { - return num.toString(8); - } - return num.toString(); - }; - }); - - return translator.translate('[[test-custom-integer-format:octal, 24]]').then(function (translation) { + Translator.registerModule('test-custom-integer-format', lang => function (key, args) { + var num = parseInt(args[0], 10) || 0; + if (key === 'binary') { + return num.toString(2); + } + if (key === 'hex') { + return num.toString(16); + } + if (key === 'octal') { + return num.toString(8); + } + return num.toString(); + }); + + return translator.translate('[[test-custom-integer-format:octal, 24]]').then((translation) => { assert.strictEqual(translation, '30'); }); }); - it('should work after registered', function () { + it('should work after registered', () => { var translator = Translator.create('de'); - return translator.translate('[[test-custom-integer-format:octal, 23]]').then(function (translation) { + return translator.translate('[[test-custom-integer-format:octal, 23]]').then((translation) => { assert.strictEqual(translation, '27'); }); }); - it('registerModule be passed the language', function (done) { - Translator.registerModule('something', function (lang) { + it('registerModule be passed the language', (done) => { + Translator.registerModule('something', (lang) => { assert.ok(lang); }); @@ -282,9 +280,9 @@ describe('Translator modules', function () { }); }); -describe('Translator static methods', function () { - describe('.removePatterns', function () { - it('should remove translator patterns from text', function (done) { +describe('Translator static methods', () => { + describe('.removePatterns', () => { + it('should remove translator patterns from text', (done) => { assert.strictEqual( Translator.removePatterns('Lorem ipsum dolor [[sit:amet]], consectetur adipiscing elit. [[sed:vitae, [[semper:dolor]]]] lorem'), 'Lorem ipsum dolor , consectetur adipiscing elit. lorem' @@ -292,8 +290,8 @@ describe('Translator static methods', function () { done(); }); }); - describe('.escape', function () { - it('should escape translation patterns within text', function (done) { + describe('.escape', () => { + it('should escape translation patterns within text', (done) => { assert.strictEqual( Translator.escape('some nice text [[global:home]] here'), 'some nice text [[global:home]] here' @@ -302,8 +300,8 @@ describe('Translator static methods', function () { }); }); - describe('.unescape', function () { - it('should unescape escaped translation patterns within text', function (done) { + describe('.unescape', () => { + it('should unescape escaped translation patterns within text', (done) => { assert.strictEqual( Translator.unescape('some nice text \\[\\[global:home\\]\\] here'), 'some nice text [[global:home]] here' @@ -316,8 +314,8 @@ describe('Translator static methods', function () { }); }); - describe('.compile', function () { - it('should create a translator pattern from a key and list of arguments', function (done) { + describe('.compile', () => { + it('should create a translator pattern from a key and list of arguments', (done) => { assert.strictEqual( Translator.compile('amazing:cool', 'awesome', 'great'), '[[amazing:cool, awesome, great]]' @@ -325,7 +323,7 @@ describe('Translator static methods', function () { done(); }); - it('should escape `%` and `,` in arguments', function (done) { + it('should escape `%` and `,` in arguments', (done) => { assert.strictEqual( Translator.compile('amazing:cool', '100% awesome!', 'one, two, and three'), '[[amazing:cool, 100% awesome!, one, two, and three]]' @@ -334,16 +332,16 @@ describe('Translator static methods', function () { }); }); - describe('add translation', function () { - it('should add custom translations', async function () { + describe('add translation', () => { + it('should add custom translations', async () => { shim.addTranslation('en-GB', 'my-namespace', { foo: 'a custom translation' }); const t = await shim.translate('this is best [[my-namespace:foo]]'); assert.strictEqual(t, 'this is best a custom translation'); }); }); - describe('translate nested keys', function () { - it('should handle nested translations', async function () { + describe('translate nested keys', () => { + it('should handle nested translations', async () => { shim.addTranslation('en-GB', 'my-namespace', { key: { key1: 'key1 translated', @@ -357,7 +355,7 @@ describe('Translator static methods', function () { assert.strictEqual(t1, 'this is best key1 translated'); assert.strictEqual(t2, 'this is best key3 translated'); }); - it("should try the defaults if it didn't reach a string in a nested translation", async function () { + it("should try the defaults if it didn't reach a string in a nested translation", async () => { shim.addTranslation('en-GB', 'my-namespace', { default1: { default1: 'default1 translated', diff --git a/test/upgrade.js b/test/upgrade.js index 93557cbf3f..9d934cc404 100644 --- a/test/upgrade.js +++ b/test/upgrade.js @@ -5,13 +5,13 @@ const assert = require('assert'); const db = require('./mocks/databasemock'); const upgrade = require('../src/upgrade'); -describe('Upgrade', function () { - it('should get all upgrade scripts', async function () { +describe('Upgrade', () => { + it('should get all upgrade scripts', async () => { const files = await upgrade.getAll(); assert(Array.isArray(files) && files.length > 0); }); - it('should throw error', async function () { + it('should throw error', async () => { let err; try { await upgrade.check(); @@ -21,7 +21,7 @@ describe('Upgrade', function () { assert.equal(err.message, 'schema-out-of-date'); }); - it('should run all upgrades', async function () { + it('should run all upgrades', async () => { // for upgrade scripts to run await db.set('schemaDate', 1); await upgrade.run(); diff --git a/test/uploads.js b/test/uploads.js index 2ef454e482..fd85900a59 100644 --- a/test/uploads.js +++ b/test/uploads.js @@ -18,14 +18,14 @@ var helpers = require('./helpers'); var file = require('../src/file'); var image = require('../src/image'); -describe('Upload Controllers', function () { +describe('Upload Controllers', () => { var tid; var cid; var pid; var adminUid; var regularUid; - before(function (done) { + before((done) => { async.series({ category: function (next) { categories.create({ @@ -39,7 +39,7 @@ describe('Upload Controllers', function () { regularUid: function (next) { user.create({ username: 'regular', password: 'zugzug' }, next); }, - }, function (err, results) { + }, (err, results) => { if (err) { return done(err); } @@ -47,7 +47,7 @@ describe('Upload Controllers', function () { regularUid = results.regularUid; cid = results.category.cid; - topics.post({ uid: adminUid, title: 'test topic title', content: 'test topic content', cid: results.category.cid }, function (err, result) { + topics.post({ uid: adminUid, title: 'test topic title', content: 'test topic content', cid: results.category.cid }, (err, result) => { if (err) { return done(err); } @@ -58,12 +58,12 @@ describe('Upload Controllers', function () { }); }); - describe('regular user uploads', function () { + describe('regular user uploads', () => { var jar; var csrf_token; - before(function (done) { - helpers.loginUser('regular', 'zugzug', function (err, _jar, _csrf_token) { + before((done) => { + helpers.loginUser('regular', 'zugzug', (err, _jar, _csrf_token) => { assert.ifError(err); jar = _jar; csrf_token = _csrf_token; @@ -71,8 +71,8 @@ describe('Upload Controllers', function () { }); }); - it('should upload an image to a post', function (done) { - helpers.uploadFile(`${nconf.get('url')}/api/post/upload`, path.join(__dirname, '../test/files/test.png'), {}, jar, csrf_token, function (err, res, body) { + it('should upload an image to a post', (done) => { + helpers.uploadFile(`${nconf.get('url')}/api/post/upload`, path.join(__dirname, '../test/files/test.png'), {}, jar, csrf_token, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body && body.status && body.response && body.response.images); @@ -82,17 +82,17 @@ describe('Upload Controllers', function () { }); }); - it('should upload an image to a post and then delete the upload', function (done) { - helpers.uploadFile(`${nconf.get('url')}/api/post/upload`, path.join(__dirname, '../test/files/test.png'), {}, jar, csrf_token, function (err, res, body) { + it('should upload an image to a post and then delete the upload', (done) => { + helpers.uploadFile(`${nconf.get('url')}/api/post/upload`, path.join(__dirname, '../test/files/test.png'), {}, jar, csrf_token, (err, res, body) => { assert.ifError(err); assert.strictEqual(res.statusCode, 200); assert(body && body.status && body.response && body.response.images); assert(Array.isArray(body.response.images)); assert(body.response.images[0].url); var name = body.response.images[0].url.replace(nconf.get('relative_path') + nconf.get('upload_url'), ''); - socketUser.deleteUpload({ uid: regularUid }, { uid: regularUid, name: name }, function (err) { + socketUser.deleteUpload({ uid: regularUid }, { uid: regularUid, name: name }, (err) => { assert.ifError(err); - db.getSortedSetRange(`uid:${regularUid}:uploads`, 0, -1, function (err, uploads) { + db.getSortedSetRange(`uid:${regularUid}:uploads`, 0, -1, (err, uploads) => { assert.ifError(err); assert.equal(uploads.includes(name), false); done(); @@ -101,25 +101,25 @@ describe('Upload Controllers', function () { }); }); - it('should not allow deleting if path is not correct', function (done) { - socketUser.deleteUpload({ uid: adminUid }, { uid: regularUid, name: '../../bkconfig.json' }, function (err) { + it('should not allow deleting if path is not correct', (done) => { + socketUser.deleteUpload({ uid: adminUid }, { uid: regularUid, name: '../../bkconfig.json' }, (err) => { assert.equal(err.message, '[[error:invalid-path]]'); done(); }); }); - it('should not allow deleting if path is not correct', function (done) { - socketUser.deleteUpload({ uid: adminUid }, { uid: regularUid, name: '/files/../../bkconfig.json' }, function (err) { + it('should not allow deleting if path is not correct', (done) => { + socketUser.deleteUpload({ uid: adminUid }, { uid: regularUid, name: '/files/../../bkconfig.json' }, (err) => { assert.equal(err.message, '[[error:invalid-path]]'); done(); }); }); - it('should resize and upload an image to a post', function (done) { + it('should resize and upload an image to a post', (done) => { var oldValue = meta.config.resizeImageWidth; meta.config.resizeImageWidth = 10; meta.config.resizeImageWidthThreshold = 10; - helpers.uploadFile(`${nconf.get('url')}/api/post/upload`, path.join(__dirname, '../test/files/test.png'), {}, jar, csrf_token, function (err, res, body) { + helpers.uploadFile(`${nconf.get('url')}/api/post/upload`, path.join(__dirname, '../test/files/test.png'), {}, jar, csrf_token, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body && body.status && body.response && body.response.images); @@ -133,10 +133,10 @@ describe('Upload Controllers', function () { }); - it('should upload a file to a post', function (done) { + it('should upload a file to a post', (done) => { var oldValue = meta.config.allowedFileExtensions; meta.config.allowedFileExtensions = 'png,jpg,bmp,html'; - helpers.uploadFile(`${nconf.get('url')}/api/post/upload`, path.join(__dirname, '../test/files/503.html'), {}, jar, csrf_token, function (err, res, body) { + helpers.uploadFile(`${nconf.get('url')}/api/post/upload`, path.join(__dirname, '../test/files/503.html'), {}, jar, csrf_token, (err, res, body) => { meta.config.allowedFileExtensions = oldValue; assert.ifError(err); assert.strictEqual(res.statusCode, 200); @@ -147,8 +147,8 @@ describe('Upload Controllers', function () { }); }); - it('should fail to upload image to post if image dimensions are too big', function (done) { - helpers.uploadFile(`${nconf.get('url')}/api/post/upload`, path.join(__dirname, '../test/files/toobig.jpg'), {}, jar, csrf_token, function (err, res, body) { + it('should fail to upload image to post if image dimensions are too big', (done) => { + helpers.uploadFile(`${nconf.get('url')}/api/post/upload`, path.join(__dirname, '../test/files/toobig.jpg'), {}, jar, csrf_token, (err, res, body) => { assert.ifError(err); assert.strictEqual(res.statusCode, 500); assert(body && body.status && body.status.message); @@ -157,8 +157,8 @@ describe('Upload Controllers', function () { }); }); - it('should fail to upload image to post if image is broken', function (done) { - helpers.uploadFile(`${nconf.get('url')}/api/post/upload`, path.join(__dirname, '../test/files/brokenimage.png'), {}, jar, csrf_token, function (err, res, body) { + it('should fail to upload image to post if image is broken', (done) => { + helpers.uploadFile(`${nconf.get('url')}/api/post/upload`, path.join(__dirname, '../test/files/brokenimage.png'), {}, jar, csrf_token, (err, res, body) => { assert.ifError(err); assert.strictEqual(res.statusCode, 500); assert(body && body.status && body.status.message); @@ -167,29 +167,29 @@ describe('Upload Controllers', function () { }); }); - it('should fail if file is not an image', function (done) { - image.isFileTypeAllowed(path.join(__dirname, '../test/files/notanimage.png'), function (err) { + it('should fail if file is not an image', (done) => { + image.isFileTypeAllowed(path.join(__dirname, '../test/files/notanimage.png'), (err) => { assert.strictEqual(err.message, 'Input file contains unsupported image format'); done(); }); }); - it('should fail if file is not an image', function (done) { - image.isFileTypeAllowed(path.join(__dirname, '../test/files/notanimage.png'), function (err) { + it('should fail if file is not an image', (done) => { + image.isFileTypeAllowed(path.join(__dirname, '../test/files/notanimage.png'), (err) => { assert.strictEqual(err.message, 'Input file contains unsupported image format'); done(); }); }); - it('should fail if file is not an image', function (done) { - image.size(path.join(__dirname, '../test/files/notanimage.png'), function (err) { + it('should fail if file is not an image', (done) => { + image.size(path.join(__dirname, '../test/files/notanimage.png'), (err) => { assert.strictEqual(err.message, 'Input file contains unsupported image format'); done(); }); }); - it('should fail if file is missing', function (done) { - image.size(path.join(__dirname, '../test/files/doesnotexist.png'), function (err) { + it('should fail if file is missing', (done) => { + image.size(path.join(__dirname, '../test/files/doesnotexist.png'), (err) => { assert.strictEqual(err.message, 'Input file is missing'); done(); }); @@ -228,49 +228,49 @@ describe('Upload Controllers', function () { // }); // }); - it('should not allow non image uploads', function (done) { - socketUser.updateCover({ uid: 1 }, { uid: 1, file: { path: '../../text.txt' } }, function (err) { + it('should not allow non image uploads', (done) => { + socketUser.updateCover({ uid: 1 }, { uid: 1, file: { path: '../../text.txt' } }, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); }); - it('should not allow non image uploads', function (done) { - socketUser.updateCover({ uid: 1 }, { uid: 1, imageData: 'data:text/html;base64,PHN2Zy9vbmxvYWQ9YWxlcnQoMik+' }, function (err) { + it('should not allow non image uploads', (done) => { + socketUser.updateCover({ uid: 1 }, { uid: 1, imageData: 'data:text/html;base64,PHN2Zy9vbmxvYWQ9YWxlcnQoMik+' }, (err) => { assert.equal(err.message, '[[error:invalid-image]]'); done(); }); }); - it('should not allow svg uploads', function (done) { - socketUser.updateCover({ uid: 1 }, { uid: 1, imageData: 'data:image/svg;base64,PHN2Zy9vbmxvYWQ9YWxlcnQoMik+' }, function (err) { + it('should not allow svg uploads', (done) => { + socketUser.updateCover({ uid: 1 }, { uid: 1, imageData: 'data:image/svg;base64,PHN2Zy9vbmxvYWQ9YWxlcnQoMik+' }, (err) => { assert.equal(err.message, '[[error:invalid-image]]'); done(); }); }); - it('should not allow non image uploads', function (done) { - socketUser.uploadCroppedPicture({ uid: 1 }, { uid: 1, file: { path: '../../text.txt' } }, function (err) { + it('should not allow non image uploads', (done) => { + socketUser.uploadCroppedPicture({ uid: 1 }, { uid: 1, file: { path: '../../text.txt' } }, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); }); - it('should not allow non image uploads', function (done) { - socketUser.uploadCroppedPicture({ uid: 1 }, { uid: 1, imageData: 'data:text/html;base64,PHN2Zy9vbmxvYWQ9YWxlcnQoMik+' }, function (err) { + it('should not allow non image uploads', (done) => { + socketUser.uploadCroppedPicture({ uid: 1 }, { uid: 1, imageData: 'data:text/html;base64,PHN2Zy9vbmxvYWQ9YWxlcnQoMik+' }, (err) => { assert.equal(err.message, '[[error:invalid-image]]'); done(); }); }); - it('should not allow svg uploads', function (done) { - socketUser.uploadCroppedPicture({ uid: 1 }, { uid: 1, imageData: 'data:image/svg;base64,PHN2Zy9vbmxvYWQ9YWxlcnQoMik+' }, function (err) { + it('should not allow svg uploads', (done) => { + socketUser.uploadCroppedPicture({ uid: 1 }, { uid: 1, imageData: 'data:image/svg;base64,PHN2Zy9vbmxvYWQ9YWxlcnQoMik+' }, (err) => { assert.equal(err.message, '[[error:invalid-image]]'); done(); }); }); - it('should delete users uploads if account is deleted', function (done) { + it('should delete users uploads if account is deleted', (done) => { var jar; var uid; var url; @@ -307,12 +307,12 @@ describe('Upload Controllers', function () { }); }); - describe('admin uploads', function () { + describe('admin uploads', () => { var jar; var csrf_token; - before(function (done) { - helpers.loginUser('admin', 'barbar', function (err, _jar, _csrf_token) { + before((done) => { + helpers.loginUser('admin', 'barbar', (err, _jar, _csrf_token) => { assert.ifError(err); jar = _jar; csrf_token = _csrf_token; @@ -320,8 +320,8 @@ describe('Upload Controllers', function () { }); }); - it('should upload site logo', function (done) { - helpers.uploadFile(`${nconf.get('url')}/api/admin/uploadlogo`, path.join(__dirname, '../test/files/test.png'), {}, jar, csrf_token, function (err, res, body) { + it('should upload site logo', (done) => { + helpers.uploadFile(`${nconf.get('url')}/api/admin/uploadlogo`, path.join(__dirname, '../test/files/test.png'), {}, jar, csrf_token, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(Array.isArray(body)); @@ -330,24 +330,24 @@ describe('Upload Controllers', function () { }); }); - it('should fail to upload invalid file type', function (done) { - helpers.uploadFile(`${nconf.get('url')}/api/admin/category/uploadpicture`, path.join(__dirname, '../test/files/503.html'), { params: JSON.stringify({ cid: cid }) }, jar, csrf_token, function (err, res, body) { + it('should fail to upload invalid file type', (done) => { + helpers.uploadFile(`${nconf.get('url')}/api/admin/category/uploadpicture`, path.join(__dirname, '../test/files/503.html'), { params: JSON.stringify({ cid: cid }) }, jar, csrf_token, (err, res, body) => { assert.ifError(err); assert.equal(body.error, '[[error:invalid-image-type, image/png, image/jpeg, image/pjpeg, image/jpg, image/gif, image/svg+xml]]'); done(); }); }); - it('should fail to upload category image with invalid json params', function (done) { - helpers.uploadFile(`${nconf.get('url')}/api/admin/category/uploadpicture`, path.join(__dirname, '../test/files/test.png'), { params: 'invalid json' }, jar, csrf_token, function (err, res, body) { + it('should fail to upload category image with invalid json params', (done) => { + helpers.uploadFile(`${nconf.get('url')}/api/admin/category/uploadpicture`, path.join(__dirname, '../test/files/test.png'), { params: 'invalid json' }, jar, csrf_token, (err, res, body) => { assert.ifError(err); assert.equal(body.error, '[[error:invalid-json]]'); done(); }); }); - it('should upload category image', function (done) { - helpers.uploadFile(`${nconf.get('url')}/api/admin/category/uploadpicture`, path.join(__dirname, '../test/files/test.png'), { params: JSON.stringify({ cid: cid }) }, jar, csrf_token, function (err, res, body) { + it('should upload category image', (done) => { + helpers.uploadFile(`${nconf.get('url')}/api/admin/category/uploadpicture`, path.join(__dirname, '../test/files/test.png'), { params: JSON.stringify({ cid: cid }) }, jar, csrf_token, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(Array.isArray(body)); @@ -356,8 +356,8 @@ describe('Upload Controllers', function () { }); }); - it('should upload default avatar', function (done) { - helpers.uploadFile(`${nconf.get('url')}/api/admin/uploadDefaultAvatar`, path.join(__dirname, '../test/files/test.png'), { }, jar, csrf_token, function (err, res, body) { + it('should upload default avatar', (done) => { + helpers.uploadFile(`${nconf.get('url')}/api/admin/uploadDefaultAvatar`, path.join(__dirname, '../test/files/test.png'), { }, jar, csrf_token, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert.equal(body[0].url, `${nconf.get('relative_path')}/assets/uploads/system/avatar-default.png`); @@ -365,8 +365,8 @@ describe('Upload Controllers', function () { }); }); - it('should upload og image', function (done) { - helpers.uploadFile(`${nconf.get('url')}/api/admin/uploadOgImage`, path.join(__dirname, '../test/files/test.png'), { }, jar, csrf_token, function (err, res, body) { + it('should upload og image', (done) => { + helpers.uploadFile(`${nconf.get('url')}/api/admin/uploadOgImage`, path.join(__dirname, '../test/files/test.png'), { }, jar, csrf_token, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert.equal(body[0].url, `${nconf.get('relative_path')}/assets/uploads/system/og-image.png`); @@ -374,8 +374,8 @@ describe('Upload Controllers', function () { }); }); - it('should upload favicon', function (done) { - helpers.uploadFile(`${nconf.get('url')}/api/admin/uploadfavicon`, path.join(__dirname, '../test/files/favicon.ico'), {}, jar, csrf_token, function (err, res, body) { + it('should upload favicon', (done) => { + helpers.uploadFile(`${nconf.get('url')}/api/admin/uploadfavicon`, path.join(__dirname, '../test/files/favicon.ico'), {}, jar, csrf_token, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(Array.isArray(body)); @@ -384,15 +384,15 @@ describe('Upload Controllers', function () { }); }); - it('should upload touch icon', function (done) { + it('should upload touch icon', (done) => { var touchiconAssetPath = '/assets/uploads/system/touchicon-orig.png'; - helpers.uploadFile(`${nconf.get('url')}/api/admin/uploadTouchIcon`, path.join(__dirname, '../test/files/test.png'), {}, jar, csrf_token, function (err, res, body) { + helpers.uploadFile(`${nconf.get('url')}/api/admin/uploadTouchIcon`, path.join(__dirname, '../test/files/test.png'), {}, jar, csrf_token, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(Array.isArray(body)); assert.equal(body[0].url, touchiconAssetPath); meta.config['brand:touchIcon'] = touchiconAssetPath; - request(`${nconf.get('url')}/apple-touch-icon`, function (err, res, body) { + request(`${nconf.get('url')}/apple-touch-icon`, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -401,12 +401,12 @@ describe('Upload Controllers', function () { }); }); - it('should upload regular file', function (done) { + it('should upload regular file', (done) => { helpers.uploadFile(`${nconf.get('url')}/api/admin/upload/file`, path.join(__dirname, '../test/files/test.png'), { params: JSON.stringify({ folder: 'system', }), - }, jar, csrf_token, function (err, res, body) { + }, jar, csrf_token, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(Array.isArray(body)); @@ -416,12 +416,12 @@ describe('Upload Controllers', function () { }); }); - it('should fail to upload regular file in wrong directory', function (done) { + it('should fail to upload regular file in wrong directory', (done) => { helpers.uploadFile(`${nconf.get('url')}/api/admin/upload/file`, path.join(__dirname, '../test/files/test.png'), { params: JSON.stringify({ folder: '../../system', }), - }, jar, csrf_token, function (err, res, body) { + }, jar, csrf_token, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 500); assert.strictEqual(body.error, '[[error:invalid-path]]'); diff --git a/test/user.js b/test/user.js index 41c2ba2b09..bae85e74d7 100644 --- a/test/user.js +++ b/test/user.js @@ -20,7 +20,7 @@ var meta = require('../src/meta'); var plugins = require('../src/plugins'); var socketUser = require('../src/socket.io/user'); -describe('User', function () { +describe('User', () => { var userData; var testUid; var testCid; @@ -30,7 +30,7 @@ describe('User', function () { async function dummyEmailerHook(data) { // pretend to handle sending emails } - before(function (done) { + before((done) => { // Attach an emailer hook so related requests do not error plugins.hooks.register('emailer-test', { hook: 'filter:email.send', @@ -41,7 +41,7 @@ describe('User', function () { name: 'Test Category', description: 'A test', order: 1, - }, function (err, categoryObj) { + }, (err, categoryObj) => { if (err) { return done(err); } @@ -50,11 +50,11 @@ describe('User', function () { done(); }); }); - after(function () { + after(() => { plugins.hooks.unregister('emailer-test', 'filter:email.send'); }); - beforeEach(function () { + beforeEach(() => { userData = { username: 'John Smith', fullname: 'John Smith McNamara', @@ -65,13 +65,13 @@ describe('User', function () { }); - describe('.create(), when created', function () { - it('should be created properly', async function () { + describe('.create(), when created', () => { + it('should be created properly', async () => { testUid = await User.create({ username: userData.username, password: userData.password, email: userData.email }); assert.ok(testUid); }); - it('should be created properly', async function () { + it('should be created properly', async () => { const uid = await User.create({ username: 'weirdemail', email: 'test@gmail.com' }); const data = await User.getUserData(uid); assert.equal(data.email, '<h1>test</h1>@gmail.com'); @@ -83,40 +83,40 @@ describe('User', function () { assert.strictEqual(data.banned, false); }); - it('should have a valid email, if using an email', function (done) { - User.create({ username: userData.username, password: userData.password, email: 'fakeMail' }, function (err) { + it('should have a valid email, if using an email', (done) => { + User.create({ username: userData.username, password: userData.password, email: 'fakeMail' }, (err) => { assert(err); assert.equal(err.message, '[[error:invalid-email]]'); done(); }); }); - it('should error with invalid password', function (done) { - User.create({ username: 'test', password: '1' }, function (err) { + it('should error with invalid password', (done) => { + User.create({ username: 'test', password: '1' }, (err) => { assert.equal(err.message, '[[reset_password:password_too_short]]'); done(); }); }); - it('should error with invalid password', function (done) { - User.create({ username: 'test', password: {} }, function (err) { + it('should error with invalid password', (done) => { + User.create({ username: 'test', password: {} }, (err) => { assert.equal(err.message, '[[error:invalid-password]]'); done(); }); }); - it('should error with a too long password', function (done) { + it('should error with a too long password', (done) => { var toolong = ''; for (var i = 0; i < 5000; i++) { toolong += 'a'; } - User.create({ username: 'test', password: toolong }, function (err) { + User.create({ username: 'test', password: toolong }, (err) => { assert.equal(err.message, '[[error:password-too-long]]'); done(); }); }); - it('should error if username is already taken or rename user', async function () { + it('should error if username is already taken or rename user', async () => { let err; async function tryCreate(data) { try { @@ -141,7 +141,7 @@ describe('User', function () { } }); - it('should error if email is already taken', async function () { + it('should error if email is already taken', async () => { let err; async function tryCreate(data) { try { @@ -159,8 +159,8 @@ describe('User', function () { }); }); - describe('.uniqueUsername()', function () { - it('should deal with collisions', function (done) { + describe('.uniqueUsername()', () => { + it('should deal with collisions', (done) => { var users = []; for (var i = 0; i < 10; i += 1) { users.push({ @@ -171,7 +171,7 @@ describe('User', function () { async.series([ function (next) { - async.eachSeries(users, function (user, next) { + async.eachSeries(users, (user, next) => { User.create(user, next); }, next); }, @@ -179,7 +179,7 @@ describe('User', function () { User.uniqueUsername({ username: 'Jane Doe', userslug: 'jane-doe', - }, function (err, username) { + }, (err, username) => { assert.ifError(err); assert.strictEqual(username, 'Jane Doe 9'); @@ -190,17 +190,17 @@ describe('User', function () { }); }); - describe('.isModerator()', function () { - it('should return false', function (done) { - User.isModerator(testUid, testCid, function (err, isModerator) { + describe('.isModerator()', () => { + it('should return false', (done) => { + User.isModerator(testUid, testCid, (err, isModerator) => { assert.equal(err, null); assert.equal(isModerator, false); done(); }); }); - it('should return two false results', function (done) { - User.isModerator([testUid, testUid], testCid, function (err, isModerator) { + it('should return two false results', (done) => { + User.isModerator([testUid, testUid], testCid, (err, isModerator) => { assert.equal(err, null); assert.equal(isModerator[0], false); assert.equal(isModerator[1], false); @@ -208,8 +208,8 @@ describe('User', function () { }); }); - it('should return two false results', function (done) { - User.isModerator(testUid, [testCid, testCid], function (err, isModerator) { + it('should return two false results', (done) => { + User.isModerator(testUid, [testCid, testCid], (err, isModerator) => { assert.equal(err, null); assert.equal(isModerator[0], false); assert.equal(isModerator[1], false); @@ -218,13 +218,13 @@ describe('User', function () { }); }); - describe('.getModeratorUids()', function () { - before(function (done) { + describe('.getModeratorUids()', () => { + before((done) => { groups.join('cid:1:privileges:moderate', 1, done); }); - it('should retrieve all users with moderator bit in category privilege', function (done) { - User.getModeratorUids(function (err, uids) { + it('should retrieve all users with moderator bit in category privilege', (done) => { + User.getModeratorUids((err, uids) => { assert.ifError(err); assert.strictEqual(1, uids.length); assert.strictEqual(1, parseInt(uids[0], 10)); @@ -232,13 +232,13 @@ describe('User', function () { }); }); - after(function (done) { + after((done) => { groups.leave('cid:1:privileges:moderate', 1, done); }); }); - describe('.getModeratorUids()', function () { - before(function (done) { + describe('.getModeratorUids()', () => { + before((done) => { async.series([ async.apply(groups.create, { name: 'testGroup' }), async.apply(groups.join, 'cid:1:privileges:groups:moderate', 'testGroup'), @@ -246,8 +246,8 @@ describe('User', function () { ], done); }); - it('should retrieve all users with moderator bit in category privilege', function (done) { - User.getModeratorUids(function (err, uids) { + it('should retrieve all users with moderator bit in category privilege', (done) => { + User.getModeratorUids((err, uids) => { assert.ifError(err); assert.strictEqual(1, uids.length); assert.strictEqual(1, parseInt(uids[0], 10)); @@ -255,7 +255,7 @@ describe('User', function () { }); }); - after(function (done) { + after((done) => { async.series([ async.apply(groups.leave, 'cid:1:privileges:groups:moderate', 'testGroup'), async.apply(groups.destroy, 'testGroup'), @@ -263,8 +263,8 @@ describe('User', function () { }); }); - describe('.isReadyToPost()', function () { - it('should error when a user makes two posts in quick succession', function (done) { + describe('.isReadyToPost()', () => { + it('should error when a user makes two posts in quick succession', (done) => { meta.config = meta.config || {}; meta.config.postDelay = '10'; @@ -281,54 +281,54 @@ describe('User', function () { content: 'lorem ipsum', cid: testCid, }), - ], function (err) { + ], (err) => { assert(err); done(); }); }); - it('should allow a post if the last post time is > 10 seconds', function (done) { - User.setUserField(testUid, 'lastposttime', +new Date() - (11 * 1000), function () { + it('should allow a post if the last post time is > 10 seconds', (done) => { + User.setUserField(testUid, 'lastposttime', +new Date() - (11 * 1000), () => { Topics.post({ uid: testUid, title: 'Topic 3', content: 'lorem ipsum', cid: testCid, - }, function (err) { + }, (err) => { assert.ifError(err); done(); }); }); }); - it('should error when a new user posts if the last post time is 10 < 30 seconds', function (done) { + it('should error when a new user posts if the last post time is 10 < 30 seconds', (done) => { meta.config.newbiePostDelay = 30; meta.config.newbiePostDelayThreshold = 3; - User.setUserField(testUid, 'lastposttime', +new Date() - (20 * 1000), function () { + User.setUserField(testUid, 'lastposttime', +new Date() - (20 * 1000), () => { Topics.post({ uid: testUid, title: 'Topic 4', content: 'lorem ipsum', cid: testCid, - }, function (err) { + }, (err) => { assert(err); done(); }); }); }); - it('should not error if a non-newbie user posts if the last post time is 10 < 30 seconds', function (done) { + it('should not error if a non-newbie user posts if the last post time is 10 < 30 seconds', (done) => { User.setUserFields(testUid, { lastposttime: +new Date() - (20 * 1000), reputation: 10, - }, function () { + }, () => { Topics.post({ uid: testUid, title: 'Topic 5', content: 'lorem ipsum', cid: testCid, - }, function (err) { + }, (err) => { assert.ifError(err); done(); }); @@ -336,7 +336,7 @@ describe('User', function () { }); }); - describe('.search()', function () { + describe('.search()', () => { let adminUid; let uid; before(async () => { @@ -344,8 +344,8 @@ describe('User', function () { await groups.join('administrators', adminUid); }); - it('should return an object containing an array of matching users', function (done) { - User.search({ query: 'john' }, function (err, searchData) { + it('should return an object containing an array of matching users', (done) => { + User.search({ query: 'john' }, (err, searchData) => { assert.ifError(err); uid = searchData.users[0].uid; assert.equal(Array.isArray(searchData.users) && searchData.users.length > 0, true); @@ -354,50 +354,50 @@ describe('User', function () { }); }); - it('should search user', function (done) { - socketUser.search({ uid: testUid }, { query: 'john' }, function (err, searchData) { + it('should search user', (done) => { + socketUser.search({ uid: testUid }, { query: 'john' }, (err, searchData) => { assert.ifError(err); assert.equal(searchData.users[0].username, 'John Smith'); done(); }); }); - it('should error for guest', function (done) { - socketUser.search({ uid: 0 }, { query: 'john' }, function (err) { + it('should error for guest', (done) => { + socketUser.search({ uid: 0 }, { query: 'john' }, (err) => { assert.equal(err.message, '[[error:no-privileges]]'); done(); }); }); - it('should error with invalid data', function (done) { - socketUser.search({ uid: testUid }, null, function (err) { + it('should error with invalid data', (done) => { + socketUser.search({ uid: testUid }, null, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); }); - it('should error for unprivileged user', function (done) { - socketUser.search({ uid: testUid }, { searchBy: 'ip', query: '123' }, function (err) { + it('should error for unprivileged user', (done) => { + socketUser.search({ uid: testUid }, { searchBy: 'ip', query: '123' }, (err) => { assert.equal(err.message, '[[error:no-privileges]]'); done(); }); }); - it('should error for unprivileged user', function (done) { - socketUser.search({ uid: testUid }, { filters: ['banned'], query: '123' }, function (err) { + it('should error for unprivileged user', (done) => { + socketUser.search({ uid: testUid }, { filters: ['banned'], query: '123' }, (err) => { assert.equal(err.message, '[[error:no-privileges]]'); done(); }); }); - it('should error for unprivileged user', function (done) { - socketUser.search({ uid: testUid }, { filters: ['flagged'], query: '123' }, function (err) { + it('should error for unprivileged user', (done) => { + socketUser.search({ uid: testUid }, { filters: ['flagged'], query: '123' }, (err) => { assert.equal(err.message, '[[error:no-privileges]]'); done(); }); }); - it('should search users by ip', async function () { + it('should search users by ip', async () => { const uid = await User.create({ username: 'ipsearch' }); await db.sortedSetAdd('ip:1.1.1.1:uid', [1, 1], [testUid, uid]); const data = await socketUser.search({ uid: adminUid }, { query: '1.1.1.1', searchBy: 'ip' }); @@ -405,8 +405,8 @@ describe('User', function () { assert.equal(data.users.length, 2); }); - it('should search users by uid', function (done) { - socketUser.search({ uid: testUid }, { query: uid, searchBy: 'uid' }, function (err, data) { + it('should search users by uid', (done) => { + socketUser.search({ uid: testUid }, { query: uid, searchBy: 'uid' }, (err, data) => { assert.ifError(err); assert(Array.isArray(data.users)); assert.equal(data.users[0].uid, uid); @@ -414,7 +414,7 @@ describe('User', function () { }); }); - it('should search users by fullname', async function () { + it('should search users by fullname', async () => { const uid = await User.create({ username: 'fullnamesearch1', fullname: 'Mr. Fullname' }); const data = await socketUser.search({ uid: adminUid }, { query: 'mr', searchBy: 'fullname' }); assert(Array.isArray(data.users)); @@ -422,7 +422,7 @@ describe('User', function () { assert.equal(uid, data.users[0].uid); }); - it('should search users by fullname', async function () { + it('should search users by fullname', async () => { const uid = await User.create({ username: 'fullnamesearch2', fullname: 'Baris:Usakli' }); const data = await socketUser.search({ uid: adminUid }, { query: 'baris:', searchBy: 'fullname' }); assert(Array.isArray(data.users)); @@ -430,25 +430,25 @@ describe('User', function () { assert.equal(uid, data.users[0].uid); }); - it('should return empty array if query is empty', function (done) { - socketUser.search({ uid: testUid }, { query: '' }, function (err, data) { + it('should return empty array if query is empty', (done) => { + socketUser.search({ uid: testUid }, { query: '' }, (err, data) => { assert.ifError(err); assert.equal(data.users.length, 0); done(); }); }); - it('should filter users', function (done) { - User.create({ username: 'ipsearch_filter' }, function (err, uid) { + it('should filter users', (done) => { + User.create({ username: 'ipsearch_filter' }, (err, uid) => { assert.ifError(err); - User.bans.ban(uid, 0, '', function (err) { + User.bans.ban(uid, 0, '', (err) => { assert.ifError(err); - User.setUserFields(uid, { flags: 10 }, function (err) { + User.setUserFields(uid, { flags: 10 }, (err) => { assert.ifError(err); socketUser.search({ uid: adminUid }, { query: 'ipsearch', filters: ['online', 'banned', 'flagged'], - }, function (err, data) { + }, (err, data) => { assert.ifError(err); assert.equal(data.users[0].username, 'ipsearch_filter'); done(); @@ -458,7 +458,7 @@ describe('User', function () { }); }); - it('should sort results by username', function (done) { + it('should sort results by username', (done) => { async.waterfall([ function (next) { User.create({ username: 'brian' }, next); @@ -477,7 +477,7 @@ describe('User', function () { paginate: false, }, next); }, - ], function (err, data) { + ], (err, data) => { assert.ifError(err); assert.equal(data.users[0].username, 'baris'); assert.equal(data.users[1].username, 'brian'); @@ -487,20 +487,20 @@ describe('User', function () { }); }); - describe('.delete()', function () { + describe('.delete()', () => { var uid; - before(function (done) { - User.create({ username: 'usertodelete', password: '123456', email: 'delete@me.com' }, function (err, newUid) { + before((done) => { + User.create({ username: 'usertodelete', password: '123456', email: 'delete@me.com' }, (err, newUid) => { assert.ifError(err); uid = newUid; done(); }); }); - it('should delete a user account', function (done) { - User.delete(1, uid, function (err) { + it('should delete a user account', (done) => { + User.delete(1, uid, (err) => { assert.ifError(err); - User.existsBySlug('usertodelete', function (err, exists) { + User.existsBySlug('usertodelete', (err, exists) => { assert.ifError(err); assert.equal(exists, false); done(); @@ -508,7 +508,7 @@ describe('User', function () { }); }); - it('should not re-add user to users:postcount if post is deleted after user deletion', async function () { + it('should not re-add user to users:postcount if post is deleted after user deletion', async () => { const uid = await User.create({ username: 'olduserwithposts' }); assert(await db.isSortedSetMember('users:postcount', uid)); @@ -525,7 +525,7 @@ describe('User', function () { assert(!await db.isSortedSetMember('users:postcount', uid)); }); - it('should not re-add user to users:reputation if post is upvoted after user deletion', async function () { + it('should not re-add user to users:reputation if post is upvoted after user deletion', async () => { const uid = await User.create({ username: 'olduserwithpostsupvote' }); assert(await db.isSortedSetMember('users:reputation', uid)); @@ -543,19 +543,19 @@ describe('User', function () { }); }); - describe('passwordReset', function () { + describe('passwordReset', () => { var uid; var code; - before(function (done) { - User.create({ username: 'resetuser', password: '123456', email: 'reset@me.com' }, function (err, newUid) { + before((done) => { + User.create({ username: 'resetuser', password: '123456', email: 'reset@me.com' }, (err, newUid) => { assert.ifError(err); uid = newUid; done(); }); }); - it('.generate() should generate a new reset code', function (done) { - User.reset.generate(uid, function (err, _code) { + it('.generate() should generate a new reset code', (done) => { + User.reset.generate(uid, (err, _code) => { assert.ifError(err); assert(_code); @@ -564,24 +564,24 @@ describe('User', function () { }); }); - it('.validate() should ensure that this new code is valid', function (done) { - User.reset.validate(code, function (err, valid) { + it('.validate() should ensure that this new code is valid', (done) => { + User.reset.validate(code, (err, valid) => { assert.ifError(err); assert.strictEqual(valid, true); done(); }); }); - it('.validate() should correctly identify an invalid code', function (done) { - User.reset.validate(`${code}abcdef`, function (err, valid) { + it('.validate() should correctly identify an invalid code', (done) => { + User.reset.validate(`${code}abcdef`, (err, valid) => { assert.ifError(err); assert.strictEqual(valid, false); done(); }); }); - it('.send() should create a new reset code and reset password', function (done) { - User.reset.send('reset@me.com', function (err) { + it('.send() should create a new reset code and reset password', (done) => { + User.reset.send('reset@me.com', (err) => { if (err) { console.log(err); } @@ -589,8 +589,8 @@ describe('User', function () { }); }); - it('.commit() should update the user\'s password and confirm their email', function (done) { - User.reset.commit(code, 'newpassword', function (err) { + it('.commit() should update the user\'s password and confirm their email', (done) => { + User.reset.commit(code, 'newpassword', (err) => { assert.ifError(err); async.parallel({ @@ -600,9 +600,9 @@ describe('User', function () { password: function (next) { db.getObjectField(`user:${uid}`, 'password', next); }, - }, function (err, results) { + }, (err, results) => { assert.ifError(err); - Password.compare('newpassword', results.password, true, function (err, match) { + Password.compare('newpassword', results.password, true, (err, match) => { assert.ifError(err); assert(match); assert.strictEqual(results.userData['email:confirmed'], 1); @@ -612,7 +612,7 @@ describe('User', function () { }); }); - it('.commit() should invalidate old codes', function (done) { + it('.commit() should invalidate old codes', (done) => { var code1; var code2; var uid; @@ -646,7 +646,7 @@ describe('User', function () { ], done); }); - it('.should error if same password is used for reset', async function () { + it('.should error if same password is used for reset', async () => { const uid = await User.create({ username: 'badmemory', email: 'bad@memory.com', password: '123456' }); const code = await User.reset.generate(uid); let err; @@ -658,7 +658,7 @@ describe('User', function () { assert.strictEqual(err.message, '[[error:reset-same-password]]'); }); - it('should not validate email if password reset is due to expiry', async function () { + it('should not validate email if password reset is due to expiry', async () => { const uid = await User.create({ username: 'resetexpiry', email: 'reset@expiry.com', password: '123456' }); let confirmed = await User.getUserField(uid, 'email:confirmed'); let [verified, unverified] = await groups.isMemberOfGroups(uid, ['verified-users', 'unverified-users']); @@ -676,33 +676,33 @@ describe('User', function () { }); }); - describe('hash methods', function () { - it('should return uid from email', function (done) { - User.getUidByEmail('john@example.com', function (err, uid) { + describe('hash methods', () => { + it('should return uid from email', (done) => { + User.getUidByEmail('john@example.com', (err, uid) => { assert.ifError(err); assert.equal(parseInt(uid, 10), parseInt(testUid, 10)); done(); }); }); - it('should return uid from username', function (done) { - User.getUidByUsername('John Smith', function (err, uid) { + it('should return uid from username', (done) => { + User.getUidByUsername('John Smith', (err, uid) => { assert.ifError(err); assert.equal(parseInt(uid, 10), parseInt(testUid, 10)); done(); }); }); - it('should return uid from userslug', function (done) { - User.getUidByUserslug('john-smith', function (err, uid) { + it('should return uid from userslug', (done) => { + User.getUidByUserslug('john-smith', (err, uid) => { assert.ifError(err); assert.equal(parseInt(uid, 10), parseInt(testUid, 10)); done(); }); }); - it('should get user data even if one uid is NaN', function (done) { - User.getUsersData([NaN, testUid], function (err, data) { + it('should get user data even if one uid is NaN', (done) => { + User.getUsersData([NaN, testUid], (err, data) => { assert.ifError(err); assert(data[0]); assert.equal(data[0].username, '[[global:guest]]'); @@ -712,14 +712,14 @@ describe('User', function () { }); }); - it('should not return private user data', function (done) { + it('should not return private user data', (done) => { User.setUserFields(testUid, { fb_token: '123123123', another_secret: 'abcde', postcount: '123', - }, function (err) { + }, (err) => { assert.ifError(err); - User.getUserData(testUid, function (err, userData) { + User.getUserData(testUid, (err, userData) => { assert.ifError(err); assert(!userData.hasOwnProperty('fb_token')); assert(!userData.hasOwnProperty('another_secret')); @@ -732,22 +732,22 @@ describe('User', function () { }); }); - it('should not return password even if explicitly requested', function (done) { - User.getUserFields(testUid, ['password'], function (err, payload) { + it('should not return password even if explicitly requested', (done) => { + User.getUserFields(testUid, ['password'], (err, payload) => { assert.ifError(err); assert(!payload.hasOwnProperty('password')); done(); }); }); - it('should return private data if field is whitelisted', function (done) { + it('should return private data if field is whitelisted', (done) => { function filterMethod(data, callback) { data.whitelist.push('another_secret'); callback(null, data); } plugins.hooks.register('test-plugin', { hook: 'filter:user.whitelistFields', method: filterMethod }); - User.getUserData(testUid, function (err, userData) { + User.getUserData(testUid, (err, userData) => { assert.ifError(err); assert(!userData.hasOwnProperty('fb_token')); assert.equal(userData.another_secret, 'abcde'); @@ -756,32 +756,32 @@ describe('User', function () { }); }); - it('should return 0 as uid if username is falsy', function (done) { - User.getUidByUsername('', function (err, uid) { + it('should return 0 as uid if username is falsy', (done) => { + User.getUidByUsername('', (err, uid) => { assert.ifError(err); assert.strictEqual(uid, 0); done(); }); }); - it('should get username by userslug', function (done) { - User.getUsernameByUserslug('john-smith', function (err, username) { + it('should get username by userslug', (done) => { + User.getUsernameByUserslug('john-smith', (err, username) => { assert.ifError(err); assert.strictEqual('John Smith', username); done(); }); }); - it('should get uids by emails', function (done) { - User.getUidsByEmails(['john@example.com'], function (err, uids) { + it('should get uids by emails', (done) => { + User.getUidsByEmails(['john@example.com'], (err, uids) => { assert.ifError(err); assert.equal(uids[0], testUid); done(); }); }); - it('should not get groupTitle for guests', function (done) { - User.getUserData(0, function (err, userData) { + it('should not get groupTitle for guests', (done) => { + User.getUserData(0, (err, userData) => { assert.ifError(err); assert.strictEqual(userData.groupTitle, ''); assert.deepStrictEqual(userData.groupTitleArray, []); @@ -789,8 +789,8 @@ describe('User', function () { }); }); - it('should load guest data', function (done) { - User.getUsersData([1, 0], function (err, data) { + it('should load guest data', (done) => { + User.getUsersData([1, 0], (err, data) => { assert.ifError(err); assert.strictEqual(data[1].username, '[[global:guest]]'); assert.strictEqual(data[1].userslug, ''); @@ -800,24 +800,24 @@ describe('User', function () { }); }); - describe('not logged in', function () { - it('should return error if not logged in', function (done) { - socketUser.updateProfile({ uid: 0 }, { uid: 1 }, function (err) { + describe('not logged in', () => { + it('should return error if not logged in', (done) => { + socketUser.updateProfile({ uid: 0 }, { uid: 1 }, (err) => { assert.equal(err.message, '[[error:invalid-uid]]'); done(); }); }); }); - describe('profile methods', function () { + describe('profile methods', () => { var uid; var jar; - before(function (done) { - User.create({ username: 'updateprofile', email: 'update@me.com', password: '123456' }, function (err, newUid) { + before((done) => { + User.create({ username: 'updateprofile', email: 'update@me.com', password: '123456' }, (err, newUid) => { assert.ifError(err); uid = newUid; - helpers.loginUser('updateprofile', '123456', function (err, _jar) { + helpers.loginUser('updateprofile', '123456', (err, _jar) => { assert.ifError(err); jar = _jar; done(); @@ -825,22 +825,22 @@ describe('User', function () { }); }); - it('should return error if data is invalid', function (done) { - socketUser.updateProfile({ uid: uid }, null, function (err) { + it('should return error if data is invalid', (done) => { + socketUser.updateProfile({ uid: uid }, null, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); }); - it('should return error if data is missing uid', function (done) { - socketUser.updateProfile({ uid: uid }, { username: 'bip', email: 'bop' }, function (err) { + it('should return error if data is missing uid', (done) => { + socketUser.updateProfile({ uid: uid }, { username: 'bip', email: 'bop' }, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); }); - it('should update a user\'s profile', function (done) { - User.create({ username: 'justforupdate', email: 'just@for.updated', password: '123456' }, function (err, uid) { + it('should update a user\'s profile', (done) => { + User.create({ username: 'justforupdate', email: 'just@for.updated', password: '123456' }, (err, uid) => { assert.ifError(err); var data = { uid: uid, @@ -854,16 +854,16 @@ describe('User', function () { signature: 'nodebb is good', password: '123456', }; - socketUser.updateProfile({ uid: uid }, { ...data, password: '123456' }, function (err, result) { + socketUser.updateProfile({ uid: uid }, { ...data, password: '123456' }, (err, result) => { assert.ifError(err); assert.equal(result.username, 'updatedUserName'); assert.equal(result.userslug, 'updatedusername'); assert.equal(result.email, 'updatedEmail@me.com'); - db.getObject(`user:${uid}`, function (err, userData) { + db.getObject(`user:${uid}`, (err, userData) => { assert.ifError(err); - Object.keys(data).forEach(function (key) { + Object.keys(data).forEach((key) => { if (key !== 'password') { assert.equal(data[key], userData[key]); } else { @@ -876,12 +876,12 @@ describe('User', function () { }); }); - it('should change a user\'s password', function (done) { - User.create({ username: 'changepassword', password: '123456' }, function (err, uid) { + it('should change a user\'s password', (done) => { + User.create({ username: 'changepassword', password: '123456' }, (err, uid) => { assert.ifError(err); - socketUser.changePassword({ uid: uid }, { uid: uid, newPassword: '654321', currentPassword: '123456' }, function (err) { + socketUser.changePassword({ uid: uid }, { uid: uid, newPassword: '654321', currentPassword: '123456' }, (err) => { assert.ifError(err); - User.isPasswordCorrect(uid, '654321', '127.0.0.1', function (err, correct) { + User.isPasswordCorrect(uid, '654321', '127.0.0.1', (err, correct) => { assert.ifError(err); assert(correct); done(); @@ -890,7 +890,7 @@ describe('User', function () { }); }); - it('should not let user change another user\'s password', async function () { + it('should not let user change another user\'s password', async () => { const regularUserUid = await User.create({ username: 'regularuserpwdchange', password: 'regularuser1234' }); const uid = await User.create({ username: 'changeadminpwd1', password: '123456' }); let err; @@ -902,7 +902,7 @@ describe('User', function () { assert.equal(err.message, '[[user:change_password_error_privileges]]'); }); - it('should not let user change admin\'s password', async function () { + it('should not let user change admin\'s password', async () => { const adminUid = await User.create({ username: 'adminpwdchange', password: 'admin1234' }); await groups.join('administrators', adminUid); const uid = await User.create({ username: 'changeadminpwd2', password: '123456' }); @@ -916,7 +916,7 @@ describe('User', function () { assert.equal(err.message, '[[user:change_password_error_privileges]]'); }); - it('should let admin change another users password', async function () { + it('should let admin change another users password', async () => { const adminUid = await User.create({ username: 'adminpwdchange2', password: 'admin1234' }); await groups.join('administrators', adminUid); const uid = await User.create({ username: 'forgotmypassword', password: '123456' }); @@ -926,7 +926,7 @@ describe('User', function () { assert(correct); }); - it('should not let admin change their password if current password is incorrect', async function () { + it('should not let admin change their password if current password is incorrect', async () => { const adminUid = await User.create({ username: 'adminforgotpwd', password: 'admin1234' }); await groups.join('administrators', adminUid); @@ -939,10 +939,10 @@ describe('User', function () { assert.equal(err.message, '[[user:change_password_error_wrong_current]]'); }); - it('should change username', function (done) { - socketUser.changeUsernameEmail({ uid: uid }, { uid: uid, username: 'updatedAgain', password: '123456' }, function (err) { + it('should change username', (done) => { + socketUser.changeUsernameEmail({ uid: uid }, { uid: uid, username: 'updatedAgain', password: '123456' }, (err) => { assert.ifError(err); - db.getObjectField(`user:${uid}`, 'username', function (err, username) { + db.getObjectField(`user:${uid}`, 'username', (err, username) => { assert.ifError(err); assert.equal(username, 'updatedAgain'); done(); @@ -950,13 +950,13 @@ describe('User', function () { }); }); - it('should not let setting an empty username', async function () { + it('should not let setting an empty username', async () => { await socketUser.changeUsernameEmail({ uid: uid }, { uid: uid, username: '', password: '123456' }); const username = await db.getObjectField(`user:${uid}`, 'username'); assert.strictEqual(username, 'updatedAgain'); }); - it('should let updating profile if current username is above max length and it is not being changed', async function () { + it('should let updating profile if current username is above max length and it is not being changed', async () => { const maxLength = meta.config.maximumUsernameLength + 1; const longName = new Array(maxLength).fill('a').join(''); const uid = await User.create({ username: longName }); @@ -966,10 +966,10 @@ describe('User', function () { assert.strictEqual(userData.email, 'verylong@name.com'); }); - it('should not update a user\'s username if it did not change', function (done) { - socketUser.changeUsernameEmail({ uid: uid }, { uid: uid, username: 'updatedAgain', password: '123456' }, function (err) { + it('should not update a user\'s username if it did not change', (done) => { + socketUser.changeUsernameEmail({ uid: uid }, { uid: uid, username: 'updatedAgain', password: '123456' }, (err) => { assert.ifError(err); - db.getSortedSetRevRange(`user:${uid}:usernames`, 0, -1, function (err, data) { + db.getSortedSetRevRange(`user:${uid}:usernames`, 0, -1, (err, data) => { assert.ifError(err); assert.equal(data.length, 2); assert(data[0].startsWith('updatedAgain')); @@ -990,12 +990,12 @@ describe('User', function () { assert.strictEqual(_err.message, '[[error:invalid-password]]'); }); - it('should change email', function (done) { - User.create({ username: 'pooremailupdate', email: 'poor@update.me', password: '123456' }, function (err, uid) { + it('should change email', (done) => { + User.create({ username: 'pooremailupdate', email: 'poor@update.me', password: '123456' }, (err, uid) => { assert.ifError(err); - socketUser.changeUsernameEmail({ uid: uid }, { uid: uid, email: 'updatedAgain@me.com', password: '123456' }, function (err) { + socketUser.changeUsernameEmail({ uid: uid }, { uid: uid, email: 'updatedAgain@me.com', password: '123456' }, (err) => { assert.ifError(err); - db.getObjectField(`user:${uid}`, 'email', function (err, email) { + db.getObjectField(`user:${uid}`, 'email', (err, email) => { assert.ifError(err); assert.equal(email, 'updatedAgain@me.com'); done(); @@ -1004,7 +1004,7 @@ describe('User', function () { }); }); - it('should error if email is identical', async function () { + it('should error if email is identical', async () => { await User.create({ username: 'trimtest1', email: 'trim1@trim.com', @@ -1025,13 +1025,13 @@ describe('User', function () { assert.strictEqual(err.message, '[[error:email-taken]]'); }); - it('should update cover image', function (done) { + it('should update cover image', (done) => { var imageData = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABwAAAAgCAYAAAABtRhCAAAACXBIWXMAAC4jAAAuIwF4pT92AAAKT2lDQ1BQaG90b3Nob3AgSUNDIHByb2ZpbGUAAHjanVNnVFPpFj333vRCS4iAlEtvUhUIIFJCi4AUkSYqIQkQSoghodkVUcERRUUEG8igiAOOjoCMFVEsDIoK2AfkIaKOg6OIisr74Xuja9a89+bN/rXXPues852zzwfACAyWSDNRNYAMqUIeEeCDx8TG4eQuQIEKJHAAEAizZCFz/SMBAPh+PDwrIsAHvgABeNMLCADATZvAMByH/w/qQplcAYCEAcB0kThLCIAUAEB6jkKmAEBGAYCdmCZTAKAEAGDLY2LjAFAtAGAnf+bTAICd+Jl7AQBblCEVAaCRACATZYhEAGg7AKzPVopFAFgwABRmS8Q5ANgtADBJV2ZIALC3AMDOEAuyAAgMADBRiIUpAAR7AGDIIyN4AISZABRG8lc88SuuEOcqAAB4mbI8uSQ5RYFbCC1xB1dXLh4ozkkXKxQ2YQJhmkAuwnmZGTKBNA/g88wAAKCRFRHgg/P9eM4Ors7ONo62Dl8t6r8G/yJiYuP+5c+rcEAAAOF0ftH+LC+zGoA7BoBt/qIl7gRoXgugdfeLZrIPQLUAoOnaV/Nw+H48PEWhkLnZ2eXk5NhKxEJbYcpXff5nwl/AV/1s+X48/Pf14L7iJIEyXYFHBPjgwsz0TKUcz5IJhGLc5o9H/LcL//wd0yLESWK5WCoU41EScY5EmozzMqUiiUKSKcUl0v9k4t8s+wM+3zUAsGo+AXuRLahdYwP2SycQWHTA4vcAAPK7b8HUKAgDgGiD4c93/+8//UegJQCAZkmScQAAXkQkLlTKsz/HCAAARKCBKrBBG/TBGCzABhzBBdzBC/xgNoRCJMTCQhBCCmSAHHJgKayCQiiGzbAdKmAv1EAdNMBRaIaTcA4uwlW4Dj1wD/phCJ7BKLyBCQRByAgTYSHaiAFiilgjjggXmYX4IcFIBBKLJCDJiBRRIkuRNUgxUopUIFVIHfI9cgI5h1xGupE7yAAygvyGvEcxlIGyUT3UDLVDuag3GoRGogvQZHQxmo8WoJvQcrQaPYw2oefQq2gP2o8+Q8cwwOgYBzPEbDAuxsNCsTgsCZNjy7EirAyrxhqwVqwDu4n1Y8+xdwQSgUXACTYEd0IgYR5BSFhMWE7YSKggHCQ0EdoJNwkDhFHCJyKTqEu0JroR+cQYYjIxh1hILCPWEo8TLxB7iEPENyQSiUMyJ7mQAkmxpFTSEtJG0m5SI+ksqZs0SBojk8naZGuyBzmULCAryIXkneTD5DPkG+Qh8lsKnWJAcaT4U+IoUspqShnlEOU05QZlmDJBVaOaUt2ooVQRNY9aQq2htlKvUYeoEzR1mjnNgxZJS6WtopXTGmgXaPdpr+h0uhHdlR5Ol9BX0svpR+iX6AP0dwwNhhWDx4hnKBmbGAcYZxl3GK+YTKYZ04sZx1QwNzHrmOeZD5lvVVgqtip8FZHKCpVKlSaVGyovVKmqpqreqgtV81XLVI+pXlN9rkZVM1PjqQnUlqtVqp1Q61MbU2epO6iHqmeob1Q/pH5Z/YkGWcNMw09DpFGgsV/jvMYgC2MZs3gsIWsNq4Z1gTXEJrHN2Xx2KruY/R27iz2qqaE5QzNKM1ezUvOUZj8H45hx+Jx0TgnnKKeX836K3hTvKeIpG6Y0TLkxZVxrqpaXllirSKtRq0frvTau7aedpr1Fu1n7gQ5Bx0onXCdHZ4/OBZ3nU9lT3acKpxZNPTr1ri6qa6UbobtEd79up+6Ynr5egJ5Mb6feeb3n+hx9L/1U/W36p/VHDFgGswwkBtsMzhg8xTVxbzwdL8fb8VFDXcNAQ6VhlWGX4YSRudE8o9VGjUYPjGnGXOMk423GbcajJgYmISZLTepN7ppSTbmmKaY7TDtMx83MzaLN1pk1mz0x1zLnm+eb15vft2BaeFostqi2uGVJsuRaplnutrxuhVo5WaVYVVpds0atna0l1rutu6cRp7lOk06rntZnw7Dxtsm2qbcZsOXYBtuutm22fWFnYhdnt8Wuw+6TvZN9un2N/T0HDYfZDqsdWh1+c7RyFDpWOt6azpzuP33F9JbpL2dYzxDP2DPjthPLKcRpnVOb00dnF2e5c4PziIuJS4LLLpc+Lpsbxt3IveRKdPVxXeF60vWdm7Obwu2o26/uNu5p7ofcn8w0nymeWTNz0MPIQ+BR5dE/C5+VMGvfrH5PQ0+BZ7XnIy9jL5FXrdewt6V3qvdh7xc+9j5yn+M+4zw33jLeWV/MN8C3yLfLT8Nvnl+F30N/I/9k/3r/0QCngCUBZwOJgUGBWwL7+Hp8Ib+OPzrbZfay2e1BjKC5QRVBj4KtguXBrSFoyOyQrSH355jOkc5pDoVQfujW0Adh5mGLw34MJ4WHhVeGP45wiFga0TGXNXfR3ENz30T6RJZE3ptnMU85ry1KNSo+qi5qPNo3ujS6P8YuZlnM1VidWElsSxw5LiquNm5svt/87fOH4p3iC+N7F5gvyF1weaHOwvSFpxapLhIsOpZATIhOOJTwQRAqqBaMJfITdyWOCnnCHcJnIi/RNtGI2ENcKh5O8kgqTXqS7JG8NXkkxTOlLOW5hCepkLxMDUzdmzqeFpp2IG0yPTq9MYOSkZBxQqohTZO2Z+pn5mZ2y6xlhbL+xW6Lty8elQfJa7OQrAVZLQq2QqboVFoo1yoHsmdlV2a/zYnKOZarnivN7cyzytuQN5zvn//tEsIS4ZK2pYZLVy0dWOa9rGo5sjxxedsK4xUFK4ZWBqw8uIq2Km3VT6vtV5eufr0mek1rgV7ByoLBtQFr6wtVCuWFfevc1+1dT1gvWd+1YfqGnRs+FYmKrhTbF5cVf9go3HjlG4dvyr+Z3JS0qavEuWTPZtJm6ebeLZ5bDpaql+aXDm4N2dq0Dd9WtO319kXbL5fNKNu7g7ZDuaO/PLi8ZafJzs07P1SkVPRU+lQ27tLdtWHX+G7R7ht7vPY07NXbW7z3/T7JvttVAVVN1WbVZftJ+7P3P66Jqun4lvttXa1ObXHtxwPSA/0HIw6217nU1R3SPVRSj9Yr60cOxx++/p3vdy0NNg1VjZzG4iNwRHnk6fcJ3/ceDTradox7rOEH0x92HWcdL2pCmvKaRptTmvtbYlu6T8w+0dbq3nr8R9sfD5w0PFl5SvNUyWna6YLTk2fyz4ydlZ19fi753GDborZ752PO32oPb++6EHTh0kX/i+c7vDvOXPK4dPKy2+UTV7hXmq86X23qdOo8/pPTT8e7nLuarrlca7nuer21e2b36RueN87d9L158Rb/1tWeOT3dvfN6b/fF9/XfFt1+cif9zsu72Xcn7q28T7xf9EDtQdlD3YfVP1v+3Njv3H9qwHeg89HcR/cGhYPP/pH1jw9DBY+Zj8uGDYbrnjg+OTniP3L96fynQ89kzyaeF/6i/suuFxYvfvjV69fO0ZjRoZfyl5O/bXyl/erA6xmv28bCxh6+yXgzMV70VvvtwXfcdx3vo98PT+R8IH8o/2j5sfVT0Kf7kxmTk/8EA5jz/GMzLdsAAAAgY0hSTQAAeiUAAICDAAD5/wAAgOkAAHUwAADqYAAAOpgAABdvkl/FRgAACcJJREFUeNqMl9tvnNV6xn/f+s5z8DCeg88Zj+NYdhJH4KShFoJAIkzVphLVJnsDaiV6gUKaC2qQUFVATbnoValAakuQYKMqBKUUJCgI9XBBSmOROMqGoCStHbA9sWM7nrFn/I3n9B17kcwoabfarj9gvet53+d9nmdJAwMDAAgh8DyPtbU1XNfFMAwkScK2bTzPw/M8dF1/SAhxKAiCxxVF2aeqqqTr+q+Af+7o6Ch0d3f/69TU1KwkSRiGwbFjx3jmmWd47rnn+OGHH1BVFYX/5QRBkPQ87xeSJP22YRi/oapqStM0PM/D931kWSYIgnHf98cXFxepVqtomjZt2/Zf2bb990EQ4Pv+PXfeU1CSpGYhfN9/TgjxQTQaJQgCwuEwQRBQKpUwDAPTNPF9n0ajAYDv+8zPzzM+Pr6/Wq2eqdVqfxOJRA6Zpnn57hrivyEC0IQQZ4Mg+MAwDCKRCJIkUa/XEUIQi8XQNI1QKIQkSQghUBQFIQSmaTI7OwtAuVxOTE9Pfzc9Pf27lUqlBUgulUoUi0VKpRKqqg4EQfAfiqLsDIfDAC0E4XCYaDSKEALXdalUKvfM1/d9hBBYlkUul2N4eJi3335bcl33mW+++aaUz+cvSJKE8uKLL6JpGo7j8Omnn/7d+vp6sr+/HyEEjuMgyzKu6yJJEsViEVVV8TyPjY2NVisV5fZkTNMkkUhw8+ZN6vU6Kysr7Nmzh9OnT7/12GOPDS8sLByT7rQR4A9XV1d/+cILLzA9PU0kEmF4eBhFUTh//jyWZaHrOkII0uk0jUaDWq1GJpOhWCyysrLC1tYWnuehqir79+9H13W6urp48803+f7773n++ef/4G7S/H4ikUCSJNbX11trcuvWLcrlMrIs4zgODzzwABMTE/i+T7lcpq2tjUqlwubmJrZts7y8jBCCkZERGo0G2WyWkydPkkql6Onp+eMmwihwc3JyMvrWW2+RTCYBcF0XWZbRdZ3l5WX27NnD008/TSwWQ1VVyuVy63GhUIhEIkEqlcJxHCzLIhaLMTQ0xJkzZ7Btm3379lmS53kIIczZ2dnFsbGxRK1Wo729HQDP8zAMg5WVFXp7e5mcnKSzs5N8Po/rutTrdVzXbQmHrutEo1FM00RVVXp7e0kkEgRBwMWLF9F1vaxUq1UikUjtlVdeuV6pVBJ9fX3Ytn2bwrLMysoKXV1dTE5OkslksCwLTdMwDANVVdnY2CAIApLJJJFIBMdxiMfj7Nq1C1VViUajLQCvvvrqkhKJRJiZmfmdb7/99jeTySSyLLfWodFoEAqFOH78OLt37yaXy2GaJoqisLy8zNTUFFevXiUIAtrb29m5cyePPPJIa+cymQz1eh2A0dFRCoXCsgIwNTW1J5/P093dTbFYRJZlJEmiWq1y4MABxsbGqNVqhEIh6vU6QRBQLpcxDIPh4WE8z2NxcZFTp05x7tw5Xn755ZY6dXZ2tliZzWa/EwD1ev3RsbExxsfHSafTVCoVGo0Gqqqya9cuIpEIQgh832dtbY3FxUUA+vr62LZtG2NjYxw5coTDhw+ztLTEyZMnuXr1KoVC4R4d3bt375R84sQJEY/H/2Jubq7N9326urqwbZt6vY5pmhw5coS+vr4W9YvFIrdu3WJqagohBFeuXOHcuXOtue7evRtN01rtfO+991haWmJkZGQrkUi8JIC9iqL0BkFAIpFACMETTzxBV1cXiUSC7u5uHMfB8zyCIMA0TeLxONlsFlmW8X2fwcFBHMdhfn6eer1Oe3s7Dz30EBMTE1y6dImjR49y6tSppR07dqwrjuM8+OWXXzI0NMTly5e5du0aQ0NDTExMkMvlCIKAIAhaIh2LxQiHw0QiEfL5POl0mlqtRq1Wo6OjA8uykGWZdDrN0tISvb29vPPOOzz++OPk83lELpf7rXfffRfDMOjo6MBxHEqlEocOHWLHjh00Gg0kSULTNIS4bS6qqhKPxxkaGmJ4eJjR0VH279/PwMAA27dvJ5vN4vs+X331FR9//DGzs7OEQiE++eQTlPb29keuX7/OtWvXOH78ONVqlZs3b9LW1kYmk8F13dZeCiGQJAnXdRFCYBgGsiwjhMC2bQqFAkEQoOs6P/74Iw8++CCDg4Pous6xY8f47LPPkIIguDo2Nrbzxo0bfPjhh9i2zczMTHNvcF2XpsZalkWj0cB1Xe4o1O3YoCisra3x008/EY/H6erqAuDAgQNEIhGCIODQoUP/ubCwMCKAjx599FHW19f56KOP6OjooFgsks/niUajKIqCbds4joMQAiFESxxs226xd2Zmhng8Tl9fH67r0mg0sG2bbDZLpVIhl8vd5gHwtysrKy8Dcdd1mZubo6enh1gsRrVabZlrk6VND/R9n3q9TqVSQdd1QqEQi4uLnD9/nlKpxODgIHv37gXAcRyCICiFQiHEzp07i1988cUfKYpCIpHANE22b9/eUhNFUVotDIKghc7zPCzLolKpsLW1RVtbG0EQ4DgOmqbR09NDM1qUSiWAPwdQ7ujjmf7+/kQymfxrSZJQVZWtra2WG+i63iKH53m4rku1WqVcLmNZFu3t7S2x7+/vJ51O89prr7VYfenSpcPAP1UqFeSHH36YeDxOKpW6eP/9988Bv9d09nw+T7VapVKptJjZnE2tVmNtbY1cLke5XGZra4vNzU16enp49tlnGRgYaD7iTxqNxgexWIzDhw+jNEPQHV87NT8/f+PChQtnR0ZGqFarrUVuOsDds2u2b2FhgVQqRSQSYWFhgStXrtDf308ymcwBf3nw4EEOHjx4O5c2lURVVRzHYXp6+t8uX7785IULFz7LZDLous59991HOBy+h31N9xgdHSWTyVCtVhkaGmLfvn1MT08zPz/PzMzM6c8//9xr+uE9QViWZer1OhsbGxiG8fns7OzPc7ncx729vXR3d1OpVNi2bRuhUAhZljEMA9/3sW0bVVVZWlri4sWLjI+P8/rrr/P111/z5JNPXrIs69cn76ZeGoaBpmm0tbX9Q6FQeHhubu7fC4UCkUiE1dVVstks8Xgc0zSRZZlGo9ESAdM02djYoNFo8MYbb2BZ1mYoFOKuZPjr/xZBEHCHred83x/b3Nz8l/X19aRlWWxsbNDZ2cnw8DDhcBjf96lWq/T09HD06FGeeuopXnrpJc6ePUs6nb4hhPi/C959ZFn+TtO0lG3bJ0ql0p85jsPW1haFQoG2tjYkSWpF/Uwmw9raGu+//z7A977vX2+GrP93wSZiTdNOGIbxy3K5/DPHcfYXCoVe27Yzpmm2m6bppVKp/Orqqnv69OmoZVn/mEwm/9TzvP9x138NAMpJ4VFTBr6SAAAAAElFTkSuQmCC'; var position = '50.0301% 19.2464%'; - socketUser.updateCover({ uid: uid }, { uid: uid, imageData: imageData, position: position }, function (err, result) { + socketUser.updateCover({ uid: uid }, { uid: uid, imageData: imageData, position: position }, (err, result) => { assert.ifError(err); assert(result.url); - db.getObjectFields(`user:${uid}`, ['cover:url', 'cover:position'], function (err, data) { + db.getObjectFields(`user:${uid}`, ['cover:url', 'cover:position'], (err, data) => { assert.ifError(err); assert.equal(data['cover:url'], result.url); assert.equal(data['cover:position'], position); @@ -1040,12 +1040,12 @@ describe('User', function () { }); }); - it('should upload cropped profile picture', function (done) { + it('should upload cropped profile picture', (done) => { var imageData = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABwAAAAgCAYAAAABtRhCAAAACXBIWXMAAC4jAAAuIwF4pT92AAAKT2lDQ1BQaG90b3Nob3AgSUNDIHByb2ZpbGUAAHjanVNnVFPpFj333vRCS4iAlEtvUhUIIFJCi4AUkSYqIQkQSoghodkVUcERRUUEG8igiAOOjoCMFVEsDIoK2AfkIaKOg6OIisr74Xuja9a89+bN/rXXPues852zzwfACAyWSDNRNYAMqUIeEeCDx8TG4eQuQIEKJHAAEAizZCFz/SMBAPh+PDwrIsAHvgABeNMLCADATZvAMByH/w/qQplcAYCEAcB0kThLCIAUAEB6jkKmAEBGAYCdmCZTAKAEAGDLY2LjAFAtAGAnf+bTAICd+Jl7AQBblCEVAaCRACATZYhEAGg7AKzPVopFAFgwABRmS8Q5ANgtADBJV2ZIALC3AMDOEAuyAAgMADBRiIUpAAR7AGDIIyN4AISZABRG8lc88SuuEOcqAAB4mbI8uSQ5RYFbCC1xB1dXLh4ozkkXKxQ2YQJhmkAuwnmZGTKBNA/g88wAAKCRFRHgg/P9eM4Ors7ONo62Dl8t6r8G/yJiYuP+5c+rcEAAAOF0ftH+LC+zGoA7BoBt/qIl7gRoXgugdfeLZrIPQLUAoOnaV/Nw+H48PEWhkLnZ2eXk5NhKxEJbYcpXff5nwl/AV/1s+X48/Pf14L7iJIEyXYFHBPjgwsz0TKUcz5IJhGLc5o9H/LcL//wd0yLESWK5WCoU41EScY5EmozzMqUiiUKSKcUl0v9k4t8s+wM+3zUAsGo+AXuRLahdYwP2SycQWHTA4vcAAPK7b8HUKAgDgGiD4c93/+8//UegJQCAZkmScQAAXkQkLlTKsz/HCAAARKCBKrBBG/TBGCzABhzBBdzBC/xgNoRCJMTCQhBCCmSAHHJgKayCQiiGzbAdKmAv1EAdNMBRaIaTcA4uwlW4Dj1wD/phCJ7BKLyBCQRByAgTYSHaiAFiilgjjggXmYX4IcFIBBKLJCDJiBRRIkuRNUgxUopUIFVIHfI9cgI5h1xGupE7yAAygvyGvEcxlIGyUT3UDLVDuag3GoRGogvQZHQxmo8WoJvQcrQaPYw2oefQq2gP2o8+Q8cwwOgYBzPEbDAuxsNCsTgsCZNjy7EirAyrxhqwVqwDu4n1Y8+xdwQSgUXACTYEd0IgYR5BSFhMWE7YSKggHCQ0EdoJNwkDhFHCJyKTqEu0JroR+cQYYjIxh1hILCPWEo8TLxB7iEPENyQSiUMyJ7mQAkmxpFTSEtJG0m5SI+ksqZs0SBojk8naZGuyBzmULCAryIXkneTD5DPkG+Qh8lsKnWJAcaT4U+IoUspqShnlEOU05QZlmDJBVaOaUt2ooVQRNY9aQq2htlKvUYeoEzR1mjnNgxZJS6WtopXTGmgXaPdpr+h0uhHdlR5Ol9BX0svpR+iX6AP0dwwNhhWDx4hnKBmbGAcYZxl3GK+YTKYZ04sZx1QwNzHrmOeZD5lvVVgqtip8FZHKCpVKlSaVGyovVKmqpqreqgtV81XLVI+pXlN9rkZVM1PjqQnUlqtVqp1Q61MbU2epO6iHqmeob1Q/pH5Z/YkGWcNMw09DpFGgsV/jvMYgC2MZs3gsIWsNq4Z1gTXEJrHN2Xx2KruY/R27iz2qqaE5QzNKM1ezUvOUZj8H45hx+Jx0TgnnKKeX836K3hTvKeIpG6Y0TLkxZVxrqpaXllirSKtRq0frvTau7aedpr1Fu1n7gQ5Bx0onXCdHZ4/OBZ3nU9lT3acKpxZNPTr1ri6qa6UbobtEd79up+6Ynr5egJ5Mb6feeb3n+hx9L/1U/W36p/VHDFgGswwkBtsMzhg8xTVxbzwdL8fb8VFDXcNAQ6VhlWGX4YSRudE8o9VGjUYPjGnGXOMk423GbcajJgYmISZLTepN7ppSTbmmKaY7TDtMx83MzaLN1pk1mz0x1zLnm+eb15vft2BaeFostqi2uGVJsuRaplnutrxuhVo5WaVYVVpds0atna0l1rutu6cRp7lOk06rntZnw7Dxtsm2qbcZsOXYBtuutm22fWFnYhdnt8Wuw+6TvZN9un2N/T0HDYfZDqsdWh1+c7RyFDpWOt6azpzuP33F9JbpL2dYzxDP2DPjthPLKcRpnVOb00dnF2e5c4PziIuJS4LLLpc+Lpsbxt3IveRKdPVxXeF60vWdm7Obwu2o26/uNu5p7ofcn8w0nymeWTNz0MPIQ+BR5dE/C5+VMGvfrH5PQ0+BZ7XnIy9jL5FXrdewt6V3qvdh7xc+9j5yn+M+4zw33jLeWV/MN8C3yLfLT8Nvnl+F30N/I/9k/3r/0QCngCUBZwOJgUGBWwL7+Hp8Ib+OPzrbZfay2e1BjKC5QRVBj4KtguXBrSFoyOyQrSH355jOkc5pDoVQfujW0Adh5mGLw34MJ4WHhVeGP45wiFga0TGXNXfR3ENz30T6RJZE3ptnMU85ry1KNSo+qi5qPNo3ujS6P8YuZlnM1VidWElsSxw5LiquNm5svt/87fOH4p3iC+N7F5gvyF1weaHOwvSFpxapLhIsOpZATIhOOJTwQRAqqBaMJfITdyWOCnnCHcJnIi/RNtGI2ENcKh5O8kgqTXqS7JG8NXkkxTOlLOW5hCepkLxMDUzdmzqeFpp2IG0yPTq9MYOSkZBxQqohTZO2Z+pn5mZ2y6xlhbL+xW6Lty8elQfJa7OQrAVZLQq2QqboVFoo1yoHsmdlV2a/zYnKOZarnivN7cyzytuQN5zvn//tEsIS4ZK2pYZLVy0dWOa9rGo5sjxxedsK4xUFK4ZWBqw8uIq2Km3VT6vtV5eufr0mek1rgV7ByoLBtQFr6wtVCuWFfevc1+1dT1gvWd+1YfqGnRs+FYmKrhTbF5cVf9go3HjlG4dvyr+Z3JS0qavEuWTPZtJm6ebeLZ5bDpaql+aXDm4N2dq0Dd9WtO319kXbL5fNKNu7g7ZDuaO/PLi8ZafJzs07P1SkVPRU+lQ27tLdtWHX+G7R7ht7vPY07NXbW7z3/T7JvttVAVVN1WbVZftJ+7P3P66Jqun4lvttXa1ObXHtxwPSA/0HIw6217nU1R3SPVRSj9Yr60cOxx++/p3vdy0NNg1VjZzG4iNwRHnk6fcJ3/ceDTradox7rOEH0x92HWcdL2pCmvKaRptTmvtbYlu6T8w+0dbq3nr8R9sfD5w0PFl5SvNUyWna6YLTk2fyz4ydlZ19fi753GDborZ752PO32oPb++6EHTh0kX/i+c7vDvOXPK4dPKy2+UTV7hXmq86X23qdOo8/pPTT8e7nLuarrlca7nuer21e2b36RueN87d9L158Rb/1tWeOT3dvfN6b/fF9/XfFt1+cif9zsu72Xcn7q28T7xf9EDtQdlD3YfVP1v+3Njv3H9qwHeg89HcR/cGhYPP/pH1jw9DBY+Zj8uGDYbrnjg+OTniP3L96fynQ89kzyaeF/6i/suuFxYvfvjV69fO0ZjRoZfyl5O/bXyl/erA6xmv28bCxh6+yXgzMV70VvvtwXfcdx3vo98PT+R8IH8o/2j5sfVT0Kf7kxmTk/8EA5jz/GMzLdsAAAAgY0hSTQAAeiUAAICDAAD5/wAAgOkAAHUwAADqYAAAOpgAABdvkl/FRgAACcJJREFUeNqMl9tvnNV6xn/f+s5z8DCeg88Zj+NYdhJH4KShFoJAIkzVphLVJnsDaiV6gUKaC2qQUFVATbnoValAakuQYKMqBKUUJCgI9XBBSmOROMqGoCStHbA9sWM7nrFn/I3n9B17kcwoabfarj9gvet53+d9nmdJAwMDAAgh8DyPtbU1XNfFMAwkScK2bTzPw/M8dF1/SAhxKAiCxxVF2aeqqqTr+q+Af+7o6Ch0d3f/69TU1KwkSRiGwbFjx3jmmWd47rnn+OGHH1BVFYX/5QRBkPQ87xeSJP22YRi/oapqStM0PM/D931kWSYIgnHf98cXFxepVqtomjZt2/Zf2bb990EQ4Pv+PXfeU1CSpGYhfN9/TgjxQTQaJQgCwuEwQRBQKpUwDAPTNPF9n0ajAYDv+8zPzzM+Pr6/Wq2eqdVqfxOJRA6Zpnn57hrivyEC0IQQZ4Mg+MAwDCKRCJIkUa/XEUIQi8XQNI1QKIQkSQghUBQFIQSmaTI7OwtAuVxOTE9Pfzc9Pf27lUqlBUgulUoUi0VKpRKqqg4EQfAfiqLsDIfDAC0E4XCYaDSKEALXdalUKvfM1/d9hBBYlkUul2N4eJi3335bcl33mW+++aaUz+cvSJKE8uKLL6JpGo7j8Omnn/7d+vp6sr+/HyEEjuMgyzKu6yJJEsViEVVV8TyPjY2NVisV5fZkTNMkkUhw8+ZN6vU6Kysr7Nmzh9OnT7/12GOPDS8sLByT7rQR4A9XV1d/+cILLzA9PU0kEmF4eBhFUTh//jyWZaHrOkII0uk0jUaDWq1GJpOhWCyysrLC1tYWnuehqir79+9H13W6urp48803+f7773n++ef/4G7S/H4ikUCSJNbX11trcuvWLcrlMrIs4zgODzzwABMTE/i+T7lcpq2tjUqlwubmJrZts7y8jBCCkZERGo0G2WyWkydPkkql6Onp+eMmwihwc3JyMvrWW2+RTCYBcF0XWZbRdZ3l5WX27NnD008/TSwWQ1VVyuVy63GhUIhEIkEqlcJxHCzLIhaLMTQ0xJkzZ7Btm3379lmS53kIIczZ2dnFsbGxRK1Wo729HQDP8zAMg5WVFXp7e5mcnKSzs5N8Po/rutTrdVzXbQmHrutEo1FM00RVVXp7e0kkEgRBwMWLF9F1vaxUq1UikUjtlVdeuV6pVBJ9fX3Ytn2bwrLMysoKXV1dTE5OkslksCwLTdMwDANVVdnY2CAIApLJJJFIBMdxiMfj7Nq1C1VViUajLQCvvvrqkhKJRJiZmfmdb7/99jeTySSyLLfWodFoEAqFOH78OLt37yaXy2GaJoqisLy8zNTUFFevXiUIAtrb29m5cyePPPJIa+cymQz1eh2A0dFRCoXCsgIwNTW1J5/P093dTbFYRJZlJEmiWq1y4MABxsbGqNVqhEIh6vU6QRBQLpcxDIPh4WE8z2NxcZFTp05x7tw5Xn755ZY6dXZ2tliZzWa/EwD1ev3RsbExxsfHSafTVCoVGo0Gqqqya9cuIpEIQgh832dtbY3FxUUA+vr62LZtG2NjYxw5coTDhw+ztLTEyZMnuXr1KoVC4R4d3bt375R84sQJEY/H/2Jubq7N9326urqwbZt6vY5pmhw5coS+vr4W9YvFIrdu3WJqagohBFeuXOHcuXOtue7evRtN01rtfO+991haWmJkZGQrkUi8JIC9iqL0BkFAIpFACMETTzxBV1cXiUSC7u5uHMfB8zyCIMA0TeLxONlsFlmW8X2fwcFBHMdhfn6eer1Oe3s7Dz30EBMTE1y6dImjR49y6tSppR07dqwrjuM8+OWXXzI0NMTly5e5du0aQ0NDTExMkMvlCIKAIAhaIh2LxQiHw0QiEfL5POl0mlqtRq1Wo6OjA8uykGWZdDrN0tISvb29vPPOOzz++OPk83lELpf7rXfffRfDMOjo6MBxHEqlEocOHWLHjh00Gg0kSULTNIS4bS6qqhKPxxkaGmJ4eJjR0VH279/PwMAA27dvJ5vN4vs+X331FR9//DGzs7OEQiE++eQTlPb29keuX7/OtWvXOH78ONVqlZs3b9LW1kYmk8F13dZeCiGQJAnXdRFCYBgGsiwjhMC2bQqFAkEQoOs6P/74Iw8++CCDg4Pous6xY8f47LPPkIIguDo2Nrbzxo0bfPjhh9i2zczMTHNvcF2XpsZalkWj0cB1Xe4o1O3YoCisra3x008/EY/H6erqAuDAgQNEIhGCIODQoUP/ubCwMCKAjx599FHW19f56KOP6OjooFgsks/niUajKIqCbds4joMQAiFESxxs226xd2Zmhng8Tl9fH67r0mg0sG2bbDZLpVIhl8vd5gHwtysrKy8Dcdd1mZubo6enh1gsRrVabZlrk6VND/R9n3q9TqVSQdd1QqEQi4uLnD9/nlKpxODgIHv37gXAcRyCICiFQiHEzp07i1988cUfKYpCIpHANE22b9/eUhNFUVotDIKghc7zPCzLolKpsLW1RVtbG0EQ4DgOmqbR09NDM1qUSiWAPwdQ7ujjmf7+/kQymfxrSZJQVZWtra2WG+i63iKH53m4rku1WqVcLmNZFu3t7S2x7+/vJ51O89prr7VYfenSpcPAP1UqFeSHH36YeDxOKpW6eP/9988Bv9d09nw+T7VapVKptJjZnE2tVmNtbY1cLke5XGZra4vNzU16enp49tlnGRgYaD7iTxqNxgexWIzDhw+jNEPQHV87NT8/f+PChQtnR0ZGqFarrUVuOsDds2u2b2FhgVQqRSQSYWFhgStXrtDf308ymcwBf3nw4EEOHjx4O5c2lURVVRzHYXp6+t8uX7785IULFz7LZDLous59991HOBy+h31N9xgdHSWTyVCtVhkaGmLfvn1MT08zPz/PzMzM6c8//9xr+uE9QViWZer1OhsbGxiG8fns7OzPc7ncx729vXR3d1OpVNi2bRuhUAhZljEMA9/3sW0bVVVZWlri4sWLjI+P8/rrr/P111/z5JNPXrIs69cn76ZeGoaBpmm0tbX9Q6FQeHhubu7fC4UCkUiE1dVVstks8Xgc0zSRZZlGo9ESAdM02djYoNFo8MYbb2BZ1mYoFOKuZPjr/xZBEHCHred83x/b3Nz8l/X19aRlWWxsbNDZ2cnw8DDhcBjf96lWq/T09HD06FGeeuopXnrpJc6ePUs6nb4hhPi/C959ZFn+TtO0lG3bJ0ql0p85jsPW1haFQoG2tjYkSWpF/Uwmw9raGu+//z7A977vX2+GrP93wSZiTdNOGIbxy3K5/DPHcfYXCoVe27Yzpmm2m6bppVKp/Orqqnv69OmoZVn/mEwm/9TzvP9x138NAMpJ4VFTBr6SAAAAAElFTkSuQmCC'; - socketUser.uploadCroppedPicture({ uid: uid }, { uid: uid, imageData: imageData }, function (err, result) { + socketUser.uploadCroppedPicture({ uid: uid }, { uid: uid, imageData: imageData }, (err, result) => { assert.ifError(err); assert(result.url); - db.getObjectFields(`user:${uid}`, ['uploadedpicture', 'picture'], function (err, data) { + db.getObjectFields(`user:${uid}`, ['uploadedpicture', 'picture'], (err, data) => { assert.ifError(err); assert.equal(result.url, data.uploadedpicture); assert.equal(result.url, data.picture); @@ -1054,10 +1054,10 @@ describe('User', function () { }); }); - it('should remove cover image', function (done) { - socketUser.removeCover({ uid: uid }, { uid: uid }, function (err) { + it('should remove cover image', (done) => { + socketUser.removeCover({ uid: uid }, { uid: uid }, (err) => { assert.ifError(err); - db.getObjectField(`user:${uid}`, 'cover:url', function (err, url) { + db.getObjectField(`user:${uid}`, 'cover:url', (err, url) => { assert.ifError(err); assert.equal(url, null); done(); @@ -1065,8 +1065,8 @@ describe('User', function () { }); }); - it('should set user status', function (done) { - socketUser.setStatus({ uid: uid }, 'away', function (err, data) { + it('should set user status', (done) => { + socketUser.setStatus({ uid: uid }, 'away', (err, data) => { assert.ifError(err); assert.equal(data.uid, uid); assert.equal(data.status, 'away'); @@ -1074,25 +1074,25 @@ describe('User', function () { }); }); - it('should fail for invalid status', function (done) { - socketUser.setStatus({ uid: uid }, '12345', function (err) { + it('should fail for invalid status', (done) => { + socketUser.setStatus({ uid: uid }, '12345', (err) => { assert.equal(err.message, '[[error:invalid-user-status]]'); done(); }); }); - it('should get user status', function (done) { - socketUser.checkStatus({ uid: uid }, uid, function (err, status) { + it('should get user status', (done) => { + socketUser.checkStatus({ uid: uid }, uid, (err, status) => { assert.ifError(err); assert.equal(status, 'away'); done(); }); }); - it('should change user picture', function (done) { - socketUser.changePicture({ uid: uid }, { type: 'default', uid: uid }, function (err) { + it('should change user picture', (done) => { + socketUser.changePicture({ uid: uid }, { type: 'default', uid: uid }, (err) => { assert.ifError(err); - User.getUserField(uid, 'picture', function (err, picture) { + User.getUserField(uid, 'picture', (err, picture) => { assert.ifError(err); assert.equal(picture, ''); done(); @@ -1100,26 +1100,26 @@ describe('User', function () { }); }); - it('should fail to change user picture with invalid data', function (done) { - socketUser.changePicture({ uid: uid }, null, function (err) { + it('should fail to change user picture with invalid data', (done) => { + socketUser.changePicture({ uid: uid }, null, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); }); - it('should fail to change user picture with invalid uid', function (done) { - socketUser.changePicture({ uid: 0 }, null, function (err) { + it('should fail to change user picture with invalid uid', (done) => { + socketUser.changePicture({ uid: 0 }, null, (err) => { assert.equal(err.message, '[[error:invalid-uid]]'); done(); }); }); - it('should set user picture to uploaded', function (done) { - User.setUserField(uid, 'uploadedpicture', '/test', function (err) { + it('should set user picture to uploaded', (done) => { + User.setUserField(uid, 'uploadedpicture', '/test', (err) => { assert.ifError(err); - socketUser.changePicture({ uid: uid }, { type: 'uploaded', uid: uid }, function (err) { + socketUser.changePicture({ uid: uid }, { type: 'uploaded', uid: uid }, (err) => { assert.ifError(err); - User.getUserField(uid, 'picture', function (err, picture) { + User.getUserField(uid, 'picture', (err, picture) => { assert.ifError(err); assert.equal(picture, `${nconf.get('relative_path')}/test`); done(); @@ -1128,7 +1128,7 @@ describe('User', function () { }); }); - it('should return error if profile image uploads disabled', function (done) { + it('should return error if profile image uploads disabled', (done) => { meta.config.allowProfileImageUploads = 0; var picture = { path: path.join(nconf.get('base_dir'), 'test/files/test_copy.png'), @@ -1139,40 +1139,40 @@ describe('User', function () { User.uploadCroppedPicture({ uid: uid, file: picture, - }, function (err) { + }, (err) => { assert.equal(err.message, '[[error:profile-image-uploads-disabled]]'); meta.config.allowProfileImageUploads = 1; done(); }); }); - it('should return error if profile image has no mime type', function (done) { + it('should return error if profile image has no mime type', (done) => { User.uploadCroppedPicture({ uid: uid, imageData: 'data:image/invalid;base64,R0lGODlhPQBEAPeoAJosM/', - }, function (err) { + }, (err) => { assert.equal(err.message, '[[error:invalid-image]]'); done(); }); }); - describe('user.uploadCroppedPicture', function () { + describe('user.uploadCroppedPicture', () => { var goodImage = 'data:image/gif;base64,R0lGODlhPQBEAPeoAJosM//AwO/AwHVYZ/z595kzAP/s7P+goOXMv8+fhw/v739/f+8PD98fH/8mJl+fn/9ZWb8/PzWlwv///6wWGbImAPgTEMImIN9gUFCEm/gDALULDN8PAD6atYdCTX9gUNKlj8wZAKUsAOzZz+UMAOsJAP/Z2ccMDA8PD/95eX5NWvsJCOVNQPtfX/8zM8+QePLl38MGBr8JCP+zs9myn/8GBqwpAP/GxgwJCPny78lzYLgjAJ8vAP9fX/+MjMUcAN8zM/9wcM8ZGcATEL+QePdZWf/29uc/P9cmJu9MTDImIN+/r7+/vz8/P8VNQGNugV8AAF9fX8swMNgTAFlDOICAgPNSUnNWSMQ5MBAQEJE3QPIGAM9AQMqGcG9vb6MhJsEdGM8vLx8fH98AANIWAMuQeL8fABkTEPPQ0OM5OSYdGFl5jo+Pj/+pqcsTE78wMFNGQLYmID4dGPvd3UBAQJmTkP+8vH9QUK+vr8ZWSHpzcJMmILdwcLOGcHRQUHxwcK9PT9DQ0O/v70w5MLypoG8wKOuwsP/g4P/Q0IcwKEswKMl8aJ9fX2xjdOtGRs/Pz+Dg4GImIP8gIH0sKEAwKKmTiKZ8aB/f39Wsl+LFt8dgUE9PT5x5aHBwcP+AgP+WltdgYMyZfyywz78AAAAAAAD///8AAP9mZv///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAKgALAAAAAA9AEQAAAj/AFEJHEiwoMGDCBMqXMiwocAbBww4nEhxoYkUpzJGrMixogkfGUNqlNixJEIDB0SqHGmyJSojM1bKZOmyop0gM3Oe2liTISKMOoPy7GnwY9CjIYcSRYm0aVKSLmE6nfq05QycVLPuhDrxBlCtYJUqNAq2bNWEBj6ZXRuyxZyDRtqwnXvkhACDV+euTeJm1Ki7A73qNWtFiF+/gA95Gly2CJLDhwEHMOUAAuOpLYDEgBxZ4GRTlC1fDnpkM+fOqD6DDj1aZpITp0dtGCDhr+fVuCu3zlg49ijaokTZTo27uG7Gjn2P+hI8+PDPERoUB318bWbfAJ5sUNFcuGRTYUqV/3ogfXp1rWlMc6awJjiAAd2fm4ogXjz56aypOoIde4OE5u/F9x199dlXnnGiHZWEYbGpsAEA3QXYnHwEFliKAgswgJ8LPeiUXGwedCAKABACCN+EA1pYIIYaFlcDhytd51sGAJbo3onOpajiihlO92KHGaUXGwWjUBChjSPiWJuOO/LYIm4v1tXfE6J4gCSJEZ7YgRYUNrkji9P55sF/ogxw5ZkSqIDaZBV6aSGYq/lGZplndkckZ98xoICbTcIJGQAZcNmdmUc210hs35nCyJ58fgmIKX5RQGOZowxaZwYA+JaoKQwswGijBV4C6SiTUmpphMspJx9unX4KaimjDv9aaXOEBteBqmuuxgEHoLX6Kqx+yXqqBANsgCtit4FWQAEkrNbpq7HSOmtwag5w57GrmlJBASEU18ADjUYb3ADTinIttsgSB1oJFfA63bduimuqKB1keqwUhoCSK374wbujvOSu4QG6UvxBRydcpKsav++Ca6G8A6Pr1x2kVMyHwsVxUALDq/krnrhPSOzXG1lUTIoffqGR7Goi2MAxbv6O2kEG56I7CSlRsEFKFVyovDJoIRTg7sugNRDGqCJzJgcKE0ywc0ELm6KBCCJo8DIPFeCWNGcyqNFE06ToAfV0HBRgxsvLThHn1oddQMrXj5DyAQgjEHSAJMWZwS3HPxT/QMbabI/iBCliMLEJKX2EEkomBAUCxRi42VDADxyTYDVogV+wSChqmKxEKCDAYFDFj4OmwbY7bDGdBhtrnTQYOigeChUmc1K3QTnAUfEgGFgAWt88hKA6aCRIXhxnQ1yg3BCayK44EWdkUQcBByEQChFXfCB776aQsG0BIlQgQgE8qO26X1h8cEUep8ngRBnOy74E9QgRgEAC8SvOfQkh7FDBDmS43PmGoIiKUUEGkMEC/PJHgxw0xH74yx/3XnaYRJgMB8obxQW6kL9QYEJ0FIFgByfIL7/IQAlvQwEpnAC7DtLNJCKUoO/w45c44GwCXiAFB/OXAATQryUxdN4LfFiwgjCNYg+kYMIEFkCKDs6PKAIJouyGWMS1FSKJOMRB/BoIxYJIUXFUxNwoIkEKPAgCBZSQHQ1A2EWDfDEUVLyADj5AChSIQW6gu10bE/JG2VnCZGfo4R4d0sdQoBAHhPjhIB94v/wRoRKQWGRHgrhGSQJxCS+0pCZbEhAAOw=='; var badImage = 'data:audio/mp3;base64,R0lGODlhPQBEAPeoAJosM//AwO/AwHVYZ/z595kzAP/s7P+goOXMv8+fhw/v739/f+8PD98fH/8mJl+fn/9ZWb8/PzWlwv///6wWGbImAPgTEMImIN9gUFCEm/gDALULDN8PAD6atYdCTX9gUNKlj8wZAKUsAOzZz+UMAOsJAP/Z2ccMDA8PD/95eX5NWvsJCOVNQPtfX/8zM8+QePLl38MGBr8JCP+zs9myn/8GBqwpAP/GxgwJCPny78lzYLgjAJ8vAP9fX/+MjMUcAN8zM/9wcM8ZGcATEL+QePdZWf/29uc/P9cmJu9MTDImIN+/r7+/vz8/P8VNQGNugV8AAF9fX8swMNgTAFlDOICAgPNSUnNWSMQ5MBAQEJE3QPIGAM9AQMqGcG9vb6MhJsEdGM8vLx8fH98AANIWAMuQeL8fABkTEPPQ0OM5OSYdGFl5jo+Pj/+pqcsTE78wMFNGQLYmID4dGPvd3UBAQJmTkP+8vH9QUK+vr8ZWSHpzcJMmILdwcLOGcHRQUHxwcK9PT9DQ0O/v70w5MLypoG8wKOuwsP/g4P/Q0IcwKEswKMl8aJ9fX2xjdOtGRs/Pz+Dg4GImIP8gIH0sKEAwKKmTiKZ8aB/f39Wsl+LFt8dgUE9PT5x5aHBwcP+AgP+WltdgYMyZfyywz78AAAAAAAD///8AAP9mZv///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAKgALAAAAAA9AEQAAAj/AFEJHEiwoMGDCBMqXMiwocAbBww4nEhxoYkUpzJGrMixogkfGUNqlNixJEIDB0SqHGmyJSojM1bKZOmyop0gM3Oe2liTISKMOoPy7GnwY9CjIYcSRYm0aVKSLmE6nfq05QycVLPuhDrxBlCtYJUqNAq2bNWEBj6ZXRuyxZyDRtqwnXvkhACDV+euTeJm1Ki7A73qNWtFiF+/gA95Gly2CJLDhwEHMOUAAuOpLYDEgBxZ4GRTlC1fDnpkM+fOqD6DDj1aZpITp0dtGCDhr+fVuCu3zlg49ijaokTZTo27uG7Gjn2P+hI8+PDPERoUB318bWbfAJ5sUNFcuGRTYUqV/3ogfXp1rWlMc6awJjiAAd2fm4ogXjz56aypOoIde4OE5u/F9x199dlXnnGiHZWEYbGpsAEA3QXYnHwEFliKAgswgJ8LPeiUXGwedCAKABACCN+EA1pYIIYaFlcDhytd51sGAJbo3onOpajiihlO92KHGaUXGwWjUBChjSPiWJuOO/LYIm4v1tXfE6J4gCSJEZ7YgRYUNrkji9P55sF/ogxw5ZkSqIDaZBV6aSGYq/lGZplndkckZ98xoICbTcIJGQAZcNmdmUc210hs35nCyJ58fgmIKX5RQGOZowxaZwYA+JaoKQwswGijBV4C6SiTUmpphMspJx9unX4KaimjDv9aaXOEBteBqmuuxgEHoLX6Kqx+yXqqBANsgCtit4FWQAEkrNbpq7HSOmtwag5w57GrmlJBASEU18ADjUYb3ADTinIttsgSB1oJFfA63bduimuqKB1keqwUhoCSK374wbujvOSu4QG6UvxBRydcpKsav++Ca6G8A6Pr1x2kVMyHwsVxUALDq/krnrhPSOzXG1lUTIoffqGR7Goi2MAxbv6O2kEG56I7CSlRsEFKFVyovDJoIRTg7sugNRDGqCJzJgcKE0ywc0ELm6KBCCJo8DIPFeCWNGcyqNFE06ToAfV0HBRgxsvLThHn1oddQMrXj5DyAQgjEHSAJMWZwS3HPxT/QMbabI/iBCliMLEJKX2EEkomBAUCxRi42VDADxyTYDVogV+wSChqmKxEKCDAYFDFj4OmwbY7bDGdBhtrnTQYOigeChUmc1K3QTnAUfEgGFgAWt88hKA6aCRIXhxnQ1yg3BCayK44EWdkUQcBByEQChFXfCB776aQsG0BIlQgQgE8qO26X1h8cEUep8ngRBnOy74E9QgRgEAC8SvOfQkh7FDBDmS43PmGoIiKUUEGkMEC/PJHgxw0xH74yx/3XnaYRJgMB8obxQW6kL9QYEJ0FIFgByfIL7/IQAlvQwEpnAC7DtLNJCKUoO/w45c44GwCXiAFB/OXAATQryUxdN4LfFiwgjCNYg+kYMIEFkCKDs6PKAIJouyGWMS1FSKJOMRB/BoIxYJIUXFUxNwoIkEKPAgCBZSQHQ1A2EWDfDEUVLyADj5AChSIQW6gu10bE/JG2VnCZGfo4R4d0sdQoBAHhPjhIB94v/wRoRKQWGRHgrhGSQJxCS+0pCZbEhAAOw=='; - it('should error if both file and imageData are missing', function (done) { - User.uploadCroppedPicture({}, function (err) { + it('should error if both file and imageData are missing', (done) => { + User.uploadCroppedPicture({}, (err) => { assert.equal('[[error:invalid-data]]', err.message); done(); }); }); - it('should error if file size is too big', function (done) { + it('should error if file size is too big', (done) => { var temp = meta.config.maximumProfileImageSize; meta.config.maximumProfileImageSize = 1; User.uploadCroppedPicture({ uid: 1, imageData: goodImage, - }, function (err) { + }, (err) => { assert.equal('[[error:file-too-big, 1]]', err.message); // Restore old value @@ -1181,19 +1181,19 @@ describe('User', function () { }); }); - it('should not allow image data with bad MIME type to be passed in', function (done) { + it('should not allow image data with bad MIME type to be passed in', (done) => { User.uploadCroppedPicture({ uid: 1, imageData: badImage, - }, function (err) { + }, (err) => { assert.equal('[[error:invalid-image]]', err.message); done(); }); }); }); - it('should get profile pictures', function (done) { - socketUser.getProfilePictures({ uid: uid }, { uid: uid }, function (err, data) { + it('should get profile pictures', (done) => { + socketUser.getProfilePictures({ uid: uid }, { uid: uid }, (err, data) => { assert.ifError(err); assert(data); assert(Array.isArray(data)); @@ -1203,7 +1203,7 @@ describe('User', function () { }); }); - it('should get default profile avatar', function (done) { + it('should get default profile avatar', (done) => { assert.strictEqual(User.getDefaultAvatar(), ''); meta.config.defaultAvatar = 'https://path/to/default/avatar'; assert.strictEqual(User.getDefaultAvatar(), meta.config.defaultAvatar); @@ -1213,20 +1213,20 @@ describe('User', function () { done(); }); - it('should fail to get profile pictures with invalid data', function (done) { - socketUser.getProfilePictures({ uid: uid }, null, function (err) { + it('should fail to get profile pictures with invalid data', (done) => { + socketUser.getProfilePictures({ uid: uid }, null, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); - socketUser.getProfilePictures({ uid: uid }, { uid: null }, function (err) { + socketUser.getProfilePictures({ uid: uid }, { uid: null }, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); }); }); - it('should remove uploaded picture', function (done) { - socketUser.removeUploadedPicture({ uid: uid }, { uid: uid }, function (err) { + it('should remove uploaded picture', (done) => { + socketUser.removeUploadedPicture({ uid: uid }, { uid: uid }, (err) => { assert.ifError(err); - User.getUserField(uid, 'uploadedpicture', function (err, uploadedpicture) { + User.getUserField(uid, 'uploadedpicture', (err, uploadedpicture) => { assert.ifError(err); assert.equal(uploadedpicture, ''); done(); @@ -1234,12 +1234,12 @@ describe('User', function () { }); }); - it('should fail to remove uploaded picture with invalid-data', function (done) { - socketUser.removeUploadedPicture({ uid: uid }, null, function (err) { + it('should fail to remove uploaded picture with invalid-data', (done) => { + socketUser.removeUploadedPicture({ uid: uid }, null, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); - socketUser.removeUploadedPicture({ uid: uid }, { }, function (err) { + socketUser.removeUploadedPicture({ uid: uid }, { }, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); - socketUser.removeUploadedPicture({ uid: null }, { }, function (err) { + socketUser.removeUploadedPicture({ uid: null }, { }, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); @@ -1247,8 +1247,8 @@ describe('User', function () { }); }); - it('should load profile page', function (done) { - request(`${nconf.get('url')}/api/user/updatedagain`, { jar: jar, json: true }, function (err, res, body) { + it('should load profile page', (done) => { + request(`${nconf.get('url')}/api/user/updatedagain`, { jar: jar, json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -1256,8 +1256,8 @@ describe('User', function () { }); }); - it('should load settings page', function (done) { - request(`${nconf.get('url')}/api/user/updatedagain/settings`, { jar: jar, json: true }, function (err, res, body) { + it('should load settings page', (done) => { + request(`${nconf.get('url')}/api/user/updatedagain/settings`, { jar: jar, json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body.settings); @@ -1267,8 +1267,8 @@ describe('User', function () { }); }); - it('should load edit page', function (done) { - request(`${nconf.get('url')}/api/user/updatedagain/edit`, { jar: jar, json: true }, function (err, res, body) { + it('should load edit page', (done) => { + request(`${nconf.get('url')}/api/user/updatedagain/edit`, { jar: jar, json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -1276,8 +1276,8 @@ describe('User', function () { }); }); - it('should load edit/email page', function (done) { - request(`${nconf.get('url')}/api/user/updatedagain/edit/email`, { jar: jar, json: true }, function (err, res, body) { + it('should load edit/email page', (done) => { + request(`${nconf.get('url')}/api/user/updatedagain/edit/email`, { jar: jar, json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(body); @@ -1285,15 +1285,15 @@ describe('User', function () { }); }); - it('should load user\'s groups page', function (done) { + it('should load user\'s groups page', (done) => { groups.create({ name: 'Test', description: 'Foobar!', - }, function (err) { + }, (err) => { assert.ifError(err); - groups.join('Test', uid, function (err) { + groups.join('Test', uid, (err) => { assert.ifError(err); - request(`${nconf.get('url')}/api/user/updatedagain/groups`, { jar: jar, json: true }, function (err, res, body) { + request(`${nconf.get('url')}/api/user/updatedagain/groups`, { jar: jar, json: true }, (err, res, body) => { assert.ifError(err); assert.equal(res.statusCode, 200); assert(Array.isArray(body.groups)); @@ -1305,25 +1305,25 @@ describe('User', function () { }); }); - describe('user info', function () { + describe('user info', () => { let testUserUid; let verifiedTestUserUid; - before(async function () { + before(async () => { // Might be the first user thus a verified one if this test part is ran alone verifiedTestUserUid = await User.create({ username: 'bannedUser', password: '123456', email: 'banneduser@example.com' }); await User.setUserField(verifiedTestUserUid, 'email:confirmed', 1); testUserUid = await User.create({ username: 'bannedUser2', password: '123456', email: 'banneduser2@example.com' }); }); - it('should return error if there is no ban reason', function (done) { - User.getLatestBanInfo(123, function (err) { + it('should return error if there is no ban reason', (done) => { + User.getLatestBanInfo(123, (err) => { assert.equal(err.message, 'no-ban-info'); done(); }); }); - it('should get history from set', async function () { + it('should get history from set', async () => { const now = Date.now(); await db.sortedSetAdd(`user:${testUserUid}:usernames`, now, `derp:${now}`); const data = await User.getHistory(`user:${testUserUid}:usernames`); @@ -1331,16 +1331,16 @@ describe('User', function () { assert.equal(data[0].timestamp, now); }); - it('should return the correct ban reason', function (done) { + it('should return the correct ban reason', (done) => { async.series([ function (next) { - User.bans.ban(testUserUid, 0, '', function (err) { + User.bans.ban(testUserUid, 0, '', (err) => { assert.ifError(err); next(err); }); }, function (next) { - User.getModerationHistory(testUserUid, function (err, data) { + User.getModerationHistory(testUserUid, (err, data) => { assert.ifError(err); assert.equal(data.bans.length, 1, 'one ban'); assert.equal(data.bans[0].reason, '[[user:info.banned-no-reason]]', 'no ban reason'); @@ -1348,19 +1348,19 @@ describe('User', function () { next(err); }); }, - ], function (err) { + ], (err) => { assert.ifError(err); - User.bans.unban(testUserUid, function (err) { + User.bans.unban(testUserUid, (err) => { assert.ifError(err); done(); }); }); }); - it('should ban user permanently', function (done) { - User.bans.ban(testUserUid, function (err) { + it('should ban user permanently', (done) => { + User.bans.ban(testUserUid, (err) => { assert.ifError(err); - User.bans.isBanned(testUserUid, function (err, isBanned) { + User.bans.isBanned(testUserUid, (err, isBanned) => { assert.ifError(err); assert.equal(isBanned, true); User.bans.unban(testUserUid, done); @@ -1368,15 +1368,15 @@ describe('User', function () { }); }); - it('should ban user temporarily', function (done) { - User.bans.ban(testUserUid, Date.now() + 2000, function (err) { + it('should ban user temporarily', (done) => { + User.bans.ban(testUserUid, Date.now() + 2000, (err) => { assert.ifError(err); - User.bans.isBanned(testUserUid, function (err, isBanned) { + User.bans.isBanned(testUserUid, (err, isBanned) => { assert.ifError(err); assert.equal(isBanned, true); - setTimeout(function () { - User.bans.isBanned(testUserUid, function (err, isBanned) { + setTimeout(() => { + User.bans.isBanned(testUserUid, (err, isBanned) => { assert.ifError(err); assert.equal(isBanned, false); User.bans.unban(testUserUid, done); @@ -1386,14 +1386,14 @@ describe('User', function () { }); }); - it('should error if until is NaN', function (done) { - User.bans.ban(testUserUid, 'asd', function (err) { + it('should error if until is NaN', (done) => { + User.bans.ban(testUserUid, 'asd', (err) => { assert.equal(err.message, '[[error:ban-expiry-missing]]'); done(); }); }); - it('should be member of "banned-users" system group only after a ban', async function () { + it('should be member of "banned-users" system group only after a ban', async () => { await User.bans.ban(testUserUid); const systemGroups = groups.systemGroups.filter(group => group !== groups.BANNED_USERS); @@ -1404,7 +1404,7 @@ describe('User', function () { assert.strictEqual(isMemberOfAny, false); }); - it('should restore system group memberships after an unban (for an unverified user)', async function () { + it('should restore system group memberships after an unban (for an unverified user)', async () => { await User.bans.unban(testUserUid); const isMemberOfGroups = await groups.isMemberOfGroups(testUserUid, groups.systemGroups); @@ -1420,7 +1420,7 @@ describe('User', function () { assert.strictEqual(membership.get('Global Moderators'), false); }); - it('should restore system group memberships after an unban (for a verified user)', async function () { + it('should restore system group memberships after an unban (for a verified user)', async () => { await User.bans.ban(verifiedTestUserUid); await User.bans.unban(verifiedTestUserUid); @@ -1432,12 +1432,12 @@ describe('User', function () { }); }); - describe('Digest.getSubscribers', function (done) { + describe('Digest.getSubscribers', (done) => { var uidIndex = {}; - before(function (done) { + before((done) => { var testUsers = ['daysub', 'offsub', 'nullsub', 'weeksub']; - async.each(testUsers, function (username, next) { + async.each(testUsers, (username, next) => { async.waterfall([ async.apply(User.create, { username: username, email: `${username}@example.com` }), function (uid, next) { @@ -1457,8 +1457,8 @@ describe('User', function () { }, done); }); - it('should accurately build digest list given ACP default "null" (not set)', function (done) { - User.digest.getSubscribers('day', function (err, subs) { + it('should accurately build digest list given ACP default "null" (not set)', (done) => { + User.digest.getSubscribers('day', (err, subs) => { assert.ifError(err); assert.strictEqual(subs.length, 1); @@ -1466,11 +1466,11 @@ describe('User', function () { }); }); - it('should accurately build digest list given ACP default "day"', function (done) { + it('should accurately build digest list given ACP default "day"', (done) => { async.series([ async.apply(meta.configs.set, 'dailyDigestFreq', 'day'), function (next) { - User.digest.getSubscribers('day', function (err, subs) { + User.digest.getSubscribers('day', (err, subs) => { assert.ifError(err); assert.strictEqual(subs.includes(uidIndex.daysub.toString()), true); // daysub does get emailed assert.strictEqual(subs.includes(uidIndex.weeksub.toString()), false); // weeksub does not get emailed @@ -1482,11 +1482,11 @@ describe('User', function () { ], done); }); - it('should accurately build digest list given ACP default "week"', function (done) { + it('should accurately build digest list given ACP default "week"', (done) => { async.series([ async.apply(meta.configs.set, 'dailyDigestFreq', 'week'), function (next) { - User.digest.getSubscribers('week', function (err, subs) { + User.digest.getSubscribers('week', (err, subs) => { assert.ifError(err); assert.strictEqual(subs.includes(uidIndex.weeksub.toString()), true); // weeksub gets emailed assert.strictEqual(subs.includes(uidIndex.daysub.toString()), false); // daysub gets emailed @@ -1498,11 +1498,11 @@ describe('User', function () { ], done); }); - it('should accurately build digest list given ACP default "off"', function (done) { + it('should accurately build digest list given ACP default "off"', (done) => { async.series([ async.apply(meta.configs.set, 'dailyDigestFreq', 'off'), function (next) { - User.digest.getSubscribers('day', function (err, subs) { + User.digest.getSubscribers('day', (err, subs) => { assert.ifError(err); assert.strictEqual(subs.length, 1); @@ -1513,9 +1513,9 @@ describe('User', function () { }); }); - describe('digests', function () { + describe('digests', () => { var uid; - before(function (done) { + before((done) => { async.waterfall([ function (next) { User.create({ username: 'digestuser', email: 'test@example.com' }, next); @@ -1533,22 +1533,22 @@ describe('User', function () { ], done); }); - it('should send digests', function (done) { - User.digest.execute({ interval: 'day' }, function (err) { + it('should send digests', (done) => { + User.digest.execute({ interval: 'day' }, (err) => { assert.ifError(err); done(); }); }); - it('should not send digests', function (done) { - User.digest.execute({ interval: 'month' }, function (err) { + it('should not send digests', (done) => { + User.digest.execute({ interval: 'month' }, (err) => { assert.ifError(err); done(); }); }); - describe('unsubscribe via POST', function () { - it('should unsubscribe from digest if one-click unsubscribe is POSTed', function (done) { + describe('unsubscribe via POST', () => { + it('should unsubscribe from digest if one-click unsubscribe is POSTed', (done) => { const token = jwt.sign({ template: 'digest', uid: uid, @@ -1557,11 +1557,11 @@ describe('User', function () { request({ method: 'post', url: `${nconf.get('url')}/email/unsubscribe/${token}`, - }, function (err, res) { + }, (err, res) => { assert.ifError(err); assert.strictEqual(res.statusCode, 200); - db.getObjectField(`user:${uid}:settings`, 'dailyDigestFreq', function (err, value) { + db.getObjectField(`user:${uid}:settings`, 'dailyDigestFreq', (err, value) => { assert.ifError(err); assert.strictEqual(value, 'off'); done(); @@ -1569,7 +1569,7 @@ describe('User', function () { }); }); - it('should unsubscribe from notifications if one-click unsubscribe is POSTed', function (done) { + it('should unsubscribe from notifications if one-click unsubscribe is POSTed', (done) => { const token = jwt.sign({ template: 'notification', type: 'test', @@ -1579,11 +1579,11 @@ describe('User', function () { request({ method: 'post', url: `${nconf.get('url')}/email/unsubscribe/${token}`, - }, function (err, res) { + }, (err, res) => { assert.ifError(err); assert.strictEqual(res.statusCode, 200); - db.getObjectField(`user:${uid}:settings`, 'notificationType_test', function (err, value) { + db.getObjectField(`user:${uid}:settings`, 'notificationType_test', (err, value) => { assert.ifError(err); assert.strictEqual(value, 'notification'); done(); @@ -1591,7 +1591,7 @@ describe('User', function () { }); }); - it('should return errors on missing template in token', function (done) { + it('should return errors on missing template in token', (done) => { const token = jwt.sign({ uid: uid, }, nconf.get('secret')); @@ -1599,14 +1599,14 @@ describe('User', function () { request({ method: 'post', url: `${nconf.get('url')}/email/unsubscribe/${token}`, - }, function (err, res) { + }, (err, res) => { assert.ifError(err); assert.strictEqual(res.statusCode, 404); done(); }); }); - it('should return errors on wrong template in token', function (done) { + it('should return errors on wrong template in token', (done) => { const token = jwt.sign({ template: 'user', uid: uid, @@ -1615,25 +1615,25 @@ describe('User', function () { request({ method: 'post', url: `${nconf.get('url')}/email/unsubscribe/${token}`, - }, function (err, res) { + }, (err, res) => { assert.ifError(err); assert.strictEqual(res.statusCode, 404); done(); }); }); - it('should return errors on missing token', function (done) { + it('should return errors on missing token', (done) => { request({ method: 'post', url: `${nconf.get('url')}/email/unsubscribe/`, - }, function (err, res) { + }, (err, res) => { assert.ifError(err); assert.strictEqual(res.statusCode, 404); done(); }); }); - it('should return errors on token signed with wrong secret (verify-failure)', function (done) { + it('should return errors on token signed with wrong secret (verify-failure)', (done) => { const token = jwt.sign({ template: 'notification', type: 'test', @@ -1643,7 +1643,7 @@ describe('User', function () { request({ method: 'post', url: `${nconf.get('url')}/email/unsubscribe/${token}`, - }, function (err, res) { + }, (err, res) => { assert.ifError(err); assert.strictEqual(res.statusCode, 403); done(); @@ -1652,48 +1652,48 @@ describe('User', function () { }); }); - describe('socket methods', function () { + describe('socket methods', () => { var socketUser = require('../src/socket.io/user'); - it('should fail with invalid data', function (done) { - socketUser.exists({ uid: testUid }, null, function (err) { + it('should fail with invalid data', (done) => { + socketUser.exists({ uid: testUid }, null, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); }); - it('should return true if user/group exists', function (done) { - socketUser.exists({ uid: testUid }, { username: 'registered-users' }, function (err, exists) { + it('should return true if user/group exists', (done) => { + socketUser.exists({ uid: testUid }, { username: 'registered-users' }, (err, exists) => { assert.ifError(err); assert(exists); done(); }); }); - it('should return true if user/group exists', function (done) { - socketUser.exists({ uid: testUid }, { username: 'John Smith' }, function (err, exists) { + it('should return true if user/group exists', (done) => { + socketUser.exists({ uid: testUid }, { username: 'John Smith' }, (err, exists) => { assert.ifError(err); assert(exists); done(); }); }); - it('should return false if user/group does not exists', function (done) { - socketUser.exists({ uid: testUid }, { username: 'doesnot exist' }, function (err, exists) { + it('should return false if user/group does not exists', (done) => { + socketUser.exists({ uid: testUid }, { username: 'doesnot exist' }, (err, exists) => { assert.ifError(err); assert(!exists); done(); }); }); - it('should delete user', async function () { + it('should delete user', async () => { const uid = await User.create({ username: 'willbedeleted' }); await socketUser.deleteAccount({ uid: uid }, {}); const exists = await socketUser.exists({ uid: testUid }, { username: 'willbedeleted' }); assert(!exists); }); - it('should fail to delete user with wrong password', async function () { + it('should fail to delete user with wrong password', async () => { const uid = await User.create({ username: 'willbedeletedpwd', password: '123456' }); let err; try { @@ -1704,14 +1704,14 @@ describe('User', function () { assert.strictEqual(err.message, '[[error:invalid-password]]'); }); - it('should delete user with correct password', async function () { + it('should delete user with correct password', async () => { const uid = await User.create({ username: 'willbedeletedcorrectpwd', password: '123456' }); await socketUser.deleteAccount({ uid: uid }, { password: '123456' }); const exists = await User.exists(uid); assert(!exists); }); - it('should fail to delete user if account deletion is not allowed', async function () { + it('should fail to delete user if account deletion is not allowed', async () => { const oldValue = meta.config.allowAccountDeletion; meta.config.allowAccountDeletion = 0; const uid = await User.create({ username: 'tobedeleted' }); @@ -1723,78 +1723,78 @@ describe('User', function () { meta.config.allowAccountDeletion = oldValue; }); - it('should fail if data is invalid', function (done) { - socketUser.emailExists({ uid: testUid }, null, function (err) { + it('should fail if data is invalid', (done) => { + socketUser.emailExists({ uid: testUid }, null, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); }); - it('should return true if email exists', function (done) { - socketUser.emailExists({ uid: testUid }, { email: 'john@example.com' }, function (err, exists) { + it('should return true if email exists', (done) => { + socketUser.emailExists({ uid: testUid }, { email: 'john@example.com' }, (err, exists) => { assert.ifError(err); assert(exists); done(); }); }); - it('should return false if email does not exist', function (done) { - socketUser.emailExists({ uid: testUid }, { email: 'does@not.exist' }, function (err, exists) { + it('should return false if email does not exist', (done) => { + socketUser.emailExists({ uid: testUid }, { email: 'does@not.exist' }, (err, exists) => { assert.ifError(err); assert(!exists); done(); }); }); - it('should error if requireEmailConfirmation is disabled', function (done) { - socketUser.emailConfirm({ uid: testUid }, {}, function (err) { + it('should error if requireEmailConfirmation is disabled', (done) => { + socketUser.emailConfirm({ uid: testUid }, {}, (err) => { assert.equal(err.message, '[[error:email-confirmations-are-disabled]]'); done(); }); }); - it('should send email confirm', function (done) { + it('should send email confirm', (done) => { meta.config.requireEmailConfirmation = 1; - socketUser.emailConfirm({ uid: testUid }, {}, function (err) { + socketUser.emailConfirm({ uid: testUid }, {}, (err) => { assert.ifError(err); meta.config.requireEmailConfirmation = 0; done(); }); }); - it('should send reset email', function (done) { - socketUser.reset.send({ uid: 0 }, 'john@example.com', function (err) { + it('should send reset email', (done) => { + socketUser.reset.send({ uid: 0 }, 'john@example.com', (err) => { assert.ifError(err); done(); }); }); - it('should return invalid-data error', function (done) { - socketUser.reset.send({ uid: 0 }, null, function (err) { + it('should return invalid-data error', (done) => { + socketUser.reset.send({ uid: 0 }, null, (err) => { assert.equal(err.message, '[[error:invalid-data]]'); done(); }); }); - it('should not error', function (done) { - socketUser.reset.send({ uid: 0 }, 'doestnot@exist.com', function (err) { + it('should not error', (done) => { + socketUser.reset.send({ uid: 0 }, 'doestnot@exist.com', (err) => { assert.ifError(err); done(); }); }); - it('should commit reset', function (done) { - db.getObject('reset:uid', function (err, data) { + it('should commit reset', (done) => { + db.getObject('reset:uid', (err, data) => { assert.ifError(err); var code = Object.keys(data).find(code => parseInt(data[code], 10) === parseInt(testUid, 10)); - socketUser.reset.commit({ uid: 0 }, { code: code, password: 'pwdchange' }, function (err) { + socketUser.reset.commit({ uid: 0 }, { code: code, password: 'pwdchange' }, (err) => { assert.ifError(err); done(); }); }); }); - it('should save user settings', function (done) { + it('should save user settings', (done) => { var data = { uid: testUid, settings: { @@ -1814,9 +1814,9 @@ describe('User', function () { followTopicsOnReply: 1, }, }; - socketUser.saveSettings({ uid: testUid }, data, function (err) { + socketUser.saveSettings({ uid: testUid }, data, (err) => { assert.ifError(err); - User.getSettings(testUid, function (err, data) { + User.getSettings(testUid, (err, data) => { assert.ifError(err); assert.equal(data.usePagination, true); done(); @@ -1824,7 +1824,7 @@ describe('User', function () { }); }); - it('should properly escape homePageRoute', function (done) { + it('should properly escape homePageRoute', (done) => { var data = { uid: testUid, settings: { @@ -1844,9 +1844,9 @@ describe('User', function () { followTopicsOnReply: 1, }, }; - socketUser.saveSettings({ uid: testUid }, data, function (err) { + socketUser.saveSettings({ uid: testUid }, data, (err) => { assert.ifError(err); - User.getSettings(testUid, function (err, data) { + User.getSettings(testUid, (err, data) => { assert.ifError(err); assert.strictEqual(data.homePageRoute, 'category/6/testing-ground'); done(); @@ -1855,7 +1855,7 @@ describe('User', function () { }); - it('should error if language is invalid', function (done) { + it('should error if language is invalid', (done) => { var data = { uid: testUid, settings: { @@ -1864,13 +1864,13 @@ describe('User', function () { postsPerPage: '5', }, }; - socketUser.saveSettings({ uid: testUid }, data, function (err) { + socketUser.saveSettings({ uid: testUid }, data, (err) => { assert.equal(err.message, '[[error:invalid-language]]'); done(); }); }); - it('should set moderation note', function (done) { + it('should set moderation note', (done) => { var adminUid; async.waterfall([ function (next) { @@ -1892,7 +1892,7 @@ describe('User', function () { function (next) { User.getModerationNotes(testUid, 0, -1, next); }, - ], function (err, notes) { + ], (err, notes) => { assert.ifError(err); assert.equal(notes[0].note, '<svg/onload=alert(document.location);//'); assert.equal(notes[0].uid, adminUid); @@ -1903,36 +1903,36 @@ describe('User', function () { }); }); - describe('approval queue', function () { + describe('approval queue', () => { var oldRegistrationApprovalType; var adminUid; - before(function (done) { + before((done) => { oldRegistrationApprovalType = meta.config.registrationApprovalType; meta.config.registrationApprovalType = 'admin-approval'; - User.create({ username: 'admin', password: '123456' }, function (err, uid) { + User.create({ username: 'admin', password: '123456' }, (err, uid) => { assert.ifError(err); adminUid = uid; groups.join('administrators', uid, done); }); }); - after(function (done) { + after((done) => { meta.config.registrationApprovalType = oldRegistrationApprovalType; done(); }); - it('should add user to approval queue', function (done) { + it('should add user to approval queue', (done) => { helpers.registerUser({ username: 'rejectme', password: '123456', 'password-confirm': '123456', email: '
Pellentesque habitant morbi tristique senectus' + 'Aenean vitae est.Mauris eleifend leo.