chore: eslint prefer-destructuring

v1.18.x
Peter Jaszkowiak 4 years ago committed by Julian Lam
parent 8d1462ffd8
commit 23f212a4c0

@ -59,12 +59,11 @@
"function-paren-newline": ["error", "consistent"], "function-paren-newline": ["error", "consistent"],
// only require const if all parts of destructuring can be const // only require const if all parts of destructuring can be const
"prefer-const": ["error", { "destructuring": "all" }], "prefer-const": ["error", { "destructuring": "all" }],
// don't require destructuring when assigning // don't require destructuring for arrays or assignment
// "prefer-destructuring": ["error", { "prefer-destructuring": ["error", {
// "VariableDeclarator": { "array": true, "object": true }, "VariableDeclarator": { "array": false, "object": true },
// "AssignmentExpression": { "array": false, "object": false } "AssignmentExpression": { "array": false, "object": false }
// }], }],
"prefer-destructuring": "off",
// identical to airbnb rule, except for allowing for..of, because we want to use it // identical to airbnb rule, except for allowing for..of, because we want to use it
// "no-restricted-syntax": [ // "no-restricted-syntax": [
// "error", // "error",

@ -7,9 +7,9 @@ nconf.argv().env({
separator: '__', separator: '__',
}); });
const winston = require('winston'); const winston = require('winston');
const fork = require('child_process').fork; const { fork } = require('child_process');
const env = process.env; const { env } = process;
let worker; let worker;
env.NODE_ENV = env.NODE_ENV || 'development'; env.NODE_ENV = env.NODE_ENV || 'development';

@ -4,7 +4,7 @@ const nconf = require('nconf');
const fs = require('fs'); const fs = require('fs');
const url = require('url'); const url = require('url');
const path = require('path'); const path = require('path');
const fork = require('child_process').fork; const { fork } = require('child_process');
const async = require('async'); const async = require('async');
const logrotate = require('logrotate-stream'); const logrotate = require('logrotate-stream');
const mkdirp = require('mkdirp'); const mkdirp = require('mkdirp');

@ -7,7 +7,7 @@ const nconf = require('nconf');
const winston = require('winston'); const winston = require('winston');
const file = require('../file'); const file = require('../file');
const Translator = require('../translator').Translator; const { Translator } = require('../translator');
function filterDirectories(directories) { function filterDirectories(directories) {
return directories.map( return directories.map(

@ -15,7 +15,7 @@ exports.buildReqObject = (req, payload) => {
req = req || {}; req = req || {};
const headers = req.headers || {}; const headers = req.headers || {};
const encrypted = req.connection ? !!req.connection.encrypted : false; const encrypted = req.connection ? !!req.connection.encrypted : false;
let host = headers.host; let { host } = headers;
const referer = headers.referer || ''; const referer = headers.referer || '';
if (!host) { if (!host) {

@ -8,7 +8,7 @@ const privileges = require('../privileges');
const apiHelpers = require('./helpers'); const apiHelpers = require('./helpers');
const doTopicAction = apiHelpers.doTopicAction; const { doTopicAction } = apiHelpers;
const websockets = require('../socket.io'); const websockets = require('../socket.io');
const socketHelpers = require('../socket.io/helpers'); const socketHelpers = require('../socket.io/helpers');

@ -229,7 +229,7 @@ usersAPI.unban = async function (caller, data) {
}; };
async function isPrivilegedOrSelfAndPasswordMatch(caller, data) { async function isPrivilegedOrSelfAndPasswordMatch(caller, data) {
const uid = caller.uid; const { uid } = caller;
const isSelf = parseInt(uid, 10) === parseInt(data.uid, 10); const isSelf = parseInt(uid, 10) === parseInt(data.uid, 10);
const [isAdmin, isTargetAdmin, isGlobalMod] = await Promise.all([ const [isAdmin, isTargetAdmin, isGlobalMod] = await Promise.all([

@ -27,7 +27,7 @@ module.exports = function (Categories) {
}; };
async function purgeCategory(categoryData) { async function purgeCategory(categoryData) {
const cid = categoryData.cid; const { cid } = categoryData;
await db.sortedSetRemoveBulk([ await db.sortedSetRemoveBulk([
['categories:cid', cid], ['categories:cid', cid],
['categories:name', `${categoryData.name.substr(0, 200).toLowerCase()}:${cid}`], ['categories:name', `${categoryData.name.substr(0, 200).toLowerCase()}:${cid}`],

@ -55,7 +55,7 @@ module.exports = function (Categories) {
return result && result.tids; return result && result.tids;
} }
let start = data.start; let { start } = data;
if (start > 0 && totalPinnedCount) { if (start > 0 && totalPinnedCount) {
start -= totalPinnedCount - pinnedCountOnPage; start -= totalPinnedCount - pinnedCountOnPage;
} }
@ -91,7 +91,7 @@ module.exports = function (Categories) {
}; };
Categories.buildTopicsSortedSet = async function (data) { Categories.buildTopicsSortedSet = async function (data) {
const cid = data.cid; const { cid } = data;
let set = `cid:${cid}:tids`; let set = `cid:${cid}:tids`;
const sort = data.sort || (data.settings && data.settings.categoryTopicSort) || meta.config.categoryTopicSort || 'newest_to_oldest'; const sort = data.sort || (data.settings && data.settings.categoryTopicSort) || meta.config.categoryTopicSort || 'newest_to_oldest';

@ -29,7 +29,7 @@ module.exports = function (Categories) {
} }
const result = await plugins.hooks.fire('filter:category.update', { cid: cid, category: modifiedFields }); const result = await plugins.hooks.fire('filter:category.update', { cid: cid, category: modifiedFields });
const category = result.category; const { category } = result;
const fields = Object.keys(category); const fields = Object.keys(category);
// move parent to front, so its updated first // move parent to front, so its updated first
const parentCidIndex = fields.indexOf('parentCid'); const parentCidIndex = fields.indexOf('parentCid');

@ -5,7 +5,7 @@
// to include color styling in the output // to include color styling in the output
// so the CLI looks nice // so the CLI looks nice
const Command = require('commander').Command; const { Command } = require('commander');
const commandColor = 'yellow'; const commandColor = 'yellow';
const optionColor = 'cyan'; const optionColor = 'cyan';

@ -41,7 +41,7 @@ try {
const defaultPackage = require('../../install/package.json'); const defaultPackage = require('../../install/package.json');
const checkVersion = function (packageName) { const checkVersion = function (packageName) {
const version = JSON.parse(fs.readFileSync(path.join(paths.nodeModules, packageName, 'package.json'), 'utf8')).version; const { version } = JSON.parse(fs.readFileSync(path.join(paths.nodeModules, packageName, 'package.json'), 'utf8'));
if (!semver.satisfies(version, defaultPackage.dependencies[packageName])) { if (!semver.satisfies(version, defaultPackage.dependencies[packageName])) {
const e = new TypeError(`Incorrect dependency version: ${packageName}`); const e = new TypeError(`Incorrect dependency version: ${packageName}`);
e.code = 'DEP_WRONG_VERSION'; e.code = 'DEP_WRONG_VERSION';

@ -94,7 +94,7 @@ async function listEvents(count) {
async function info() { async function info() {
console.log(''); console.log('');
const version = require('../../package.json').version; const { version } = require('../../package.json');
console.log(` version: ${version}`); console.log(` version: ${version}`);
console.log(` Node ver: ${process.version}`); console.log(` Node ver: ${process.version}`);

@ -7,7 +7,7 @@ const packageInstall = require('./package-install');
const upgrade = require('../upgrade'); const upgrade = require('../upgrade');
const build = require('../meta/build'); const build = require('../meta/build');
const db = require('../database'); const db = require('../database');
const upgradePlugins = require('./upgrade-plugins').upgradePlugins; const { upgradePlugins } = require('./upgrade-plugins');
const steps = { const steps = {
package: { package: {
@ -69,7 +69,7 @@ function runSteps(tasks) {
const message = 'NodeBB Upgrade Complete!'; const message = 'NodeBB Upgrade Complete!';
// some consoles will return undefined/zero columns, so just use 2 spaces in upgrade script if we can't get our column count // some consoles will return undefined/zero columns, so just use 2 spaces in upgrade script if we can't get our column count
const columns = process.stdout.columns; const { columns } = process.stdout;
const spaces = columns ? new Array(Math.floor(columns / 2) - (message.length / 2) + 1).join(' ') : ' '; const spaces = columns ? new Array(Math.floor(columns / 2) - (message.length / 2) + 1).join(' ') : ' ';
console.log(`\n\n${spaces}${message.green.bold}${'\n'.reset}`); console.log(`\n\n${spaces}${message.green.bold}${'\n'.reset}`);

@ -28,12 +28,12 @@ helpers.getUserDataByUserSlug = async function (userslug, callerUID) {
} }
await parseAboutMe(results.userData); await parseAboutMe(results.userData);
const userData = results.userData; const { userData } = results;
const userSettings = results.userSettings; const { userSettings } = results;
const isAdmin = results.isAdmin; const { isAdmin } = results;
const isGlobalModerator = results.isGlobalModerator; const { isGlobalModerator } = results;
const isModerator = results.isModerator; const { isModerator } = results;
const canViewInfo = results.canViewInfo; const { canViewInfo } = results;
const isSelf = parseInt(callerUID, 10) === parseInt(userData.uid, 10); const isSelf = parseInt(callerUID, 10) === parseInt(userData.uid, 10);
userData.age = Math.max(0, userData.birthday ? Math.floor((new Date().getTime() - new Date(userData.birthday).getTime()) / 31536000000) : 0); userData.age = Math.max(0, userData.birthday ? Math.floor((new Date().getTime() - new Date(userData.birthday).getTime()) / 31536000000) : 0);
@ -140,7 +140,7 @@ async function getAllData(uid, callerUID) {
} }
async function getCounts(userData, callerUID) { async function getCounts(userData, callerUID) {
const uid = userData.uid; const { uid } = userData;
const cids = await categories.getCidsByPrivilege('categories:cid', callerUID, 'topics:read'); const cids = await categories.getCidsByPrivilege('categories:cid', callerUID, 'topics:read');
const promises = { const promises = {
posts: db.sortedSetsCardSum(cids.map(c => `cid:${c}:uid:${uid}:pids`)), posts: db.sortedSetsCardSum(cids.map(c => `cid:${c}:uid:${uid}:pids`)),

@ -62,7 +62,7 @@ const templateToData = {
return `uid:${userData.uid}:followed_tids`; return `uid:${userData.uid}:followed_tids`;
}, },
getTopics: async function (set, req, start, stop) { getTopics: async function (set, req, start, stop) {
const sort = req.query.sort; const { sort } = req.query;
const map = { const map = {
votes: 'topics:votes', votes: 'topics:votes',
posts: 'topics:posts', posts: 'topics:posts',

@ -7,7 +7,7 @@ const utils = require('../../utils');
cacheController.get = function (req, res) { cacheController.get = function (req, res) {
const postCache = require('../../posts/cache'); const postCache = require('../../posts/cache');
const groupCache = require('../../groups').cache; const groupCache = require('../../groups').cache;
const objectCache = require('../../database').objectCache; const { objectCache } = require('../../database');
const localCache = require('../../cache'); const localCache = require('../../cache');
function getInfo(cache) { function getInfo(cache) {

@ -69,7 +69,7 @@ async function getGroupNames() {
} }
groupsController.getCSV = async function (req, res) { groupsController.getCSV = async function (req, res) {
const referer = req.headers.referer; const { referer } = req.headers;
if (!referer || !referer.replace(nconf.get('url'), '').startsWith('/admin/manage/groups')) { if (!referer || !referer.replace(nconf.get('url'), '').startsWith('/admin/manage/groups')) {
return res.status(403).send('[[error:invalid-origin]]'); return res.status(403).send('[[error:invalid-origin]]');

@ -3,7 +3,7 @@
const os = require('os'); const os = require('os');
const winston = require('winston'); const winston = require('winston');
const nconf = require('nconf'); const nconf = require('nconf');
const exec = require('child_process').exec; const { exec } = require('child_process');
const pubsub = require('../../pubsub'); const pubsub = require('../../pubsub');
const rooms = require('../../socket.io/admin/rooms'); const rooms = require('../../socket.io/admin/rooms');

@ -227,7 +227,7 @@ async function getInvites() {
async function render(req, res, data) { async function render(req, res, data) {
data.pagination = pagination.create(data.page, data.pageCount, req.query); data.pagination = pagination.create(data.page, data.pageCount, req.query);
const registrationType = meta.config.registrationType; const { registrationType } = meta.config;
data.inviteOnly = registrationType === 'invite-only' || registrationType === 'admin-invite-only'; data.inviteOnly = registrationType === 'invite-only' || registrationType === 'admin-invite-only';
data.adminInviteOnly = registrationType === 'admin-invite-only'; data.adminInviteOnly = registrationType === 'admin-invite-only';

@ -183,7 +183,7 @@ authenticationController.registerComplete = function (req, res, next) {
} else { } else {
// Update user hash, clear registration data in session // Update user hash, clear registration data in session
const payload = req.session.registration; const payload = req.session.registration;
const uid = payload.uid; const { uid } = payload;
delete payload.uid; delete payload.uid;
delete payload.returnTo; delete payload.returnTo;
@ -418,8 +418,8 @@ authenticationController.logout = async function (req, res, next) {
res.clearCookie(nconf.get('sessionKey'), meta.configs.cookie.get()); res.clearCookie(nconf.get('sessionKey'), meta.configs.cookie.get());
return res.status(200).send('not-logged-in'); return res.status(200).send('not-logged-in');
} }
const uid = req.uid; const { uid } = req;
const sessionID = req.sessionID; const { sessionID } = req;
try { try {
await user.auth.revokeSession(sessionID, uid); await user.auth.revokeSession(sessionID, uid);

@ -40,7 +40,7 @@ exports.get = async function (req, res, callback) {
}; };
exports.post = async function (req, res) { exports.post = async function (req, res) {
const body = req.body; const { body } = req;
const data = { const data = {
uid: req.uid, uid: req.uid,
req: req, req: req,

@ -282,10 +282,8 @@ async function getCategoryData(cids, uid, selectedCid, states, privilege) {
} }
helpers.getVisibleCategories = async function (params) { helpers.getVisibleCategories = async function (params) {
const cids = params.cids; const { cids, uid, privilege } = params;
const uid = params.uid;
const states = params.states || [categories.watchStates.watching, categories.watchStates.notwatching]; const states = params.states || [categories.watchStates.watching, categories.watchStates.notwatching];
const privilege = params.privilege;
const showLinks = !!params.showLinks; const showLinks = !!params.showLinks;
let [allowed, watchState, categoriesData, isAdmin, isModerator] = await Promise.all([ let [allowed, watchState, categoriesData, isAdmin, isModerator] = await Promise.all([
@ -434,7 +432,7 @@ helpers.formatApiResponse = async (statusCode, res, payload) => {
response: payload || {}, response: payload || {},
}); });
} else if (payload instanceof Error) { } else if (payload instanceof Error) {
const message = payload.message; const { message } = payload;
const response = {}; const response = {};
// Update status code based on some common error codes // Update status code based on some common error codes

@ -37,7 +37,7 @@ async function rewrite(req, res, next) {
return next(err); return next(err);
} }
const pathname = parsedUrl.pathname; const { pathname } = parsedUrl;
const hook = `action:homepage.get:${pathname}`; const hook = `action:homepage.get:${pathname}`;
if (!plugins.hooks.hasListeners(hook)) { if (!plugins.hooks.hasListeners(hook)) {
req.url = req.path + (!req.path.endsWith('/') ? '/' : '') + pathname; req.url = req.path + (!req.path.endsWith('/') ? '/' : '') + pathname;

@ -153,7 +153,7 @@ modsController.postQueue = async function (req, res, next) {
if (!isPrivileged) { if (!isPrivileged) {
return next(); return next();
} }
const cid = req.query.cid; const { cid } = req.query;
const page = parseInt(req.query.page, 10) || 1; const page = parseInt(req.query.page, 10) || 1;
const postsPerPage = 20; const postsPerPage = 20;

@ -24,7 +24,7 @@ recentController.get = async function (req, res, next) {
recentController.getData = async function (req, url, sort) { recentController.getData = async function (req, url, sort) {
const page = parseInt(req.query.page, 10) || 1; const page = parseInt(req.query.page, 10) || 1;
let term = helpers.terms[req.query.term]; let term = helpers.terms[req.query.term];
const cid = req.query.cid; const { cid } = req.query;
const filter = req.query.filter || ''; const filter = req.query.filter || '';
if (!term && req.query.term) { if (!term && req.query.term) {

@ -13,7 +13,7 @@ const helpers = require('./helpers');
const unreadController = module.exports; const unreadController = module.exports;
unreadController.get = async function (req, res) { unreadController.get = async function (req, res) {
const cid = req.query.cid; const { cid } = req.query;
const filter = req.query.filter || ''; const filter = req.query.filter || '';
const [categoryData, userSettings, isPrivileged] = await Promise.all([ const [categoryData, userSettings, isPrivileged] = await Promise.all([

@ -165,7 +165,7 @@ usersController.getUsersAndCount = async function (set, uid, start, stop) {
}; };
async function render(req, res, data) { async function render(req, res, data) {
const registrationType = meta.config.registrationType; const { registrationType } = meta.config;
data.maximumInvites = meta.config.maximumInvites; data.maximumInvites = meta.config.maximumInvites;
data.inviteOnly = registrationType === 'invite-only' || registrationType === 'admin-invite-only'; data.inviteOnly = registrationType === 'invite-only' || registrationType === 'admin-invite-only';

@ -182,7 +182,7 @@ Users.invite = async (req, res) => {
return helpers.formatApiResponse(403, res, new Error('[[error:no-privileges]]')); return helpers.formatApiResponse(403, res, new Error('[[error:no-privileges]]'));
} }
const registrationType = meta.config.registrationType; const { registrationType } = meta.config;
const isAdmin = await user.isAdministrator(req.uid); const isAdmin = await user.isAdministrator(req.uid);
if (registrationType === 'admin-invite-only' && !isAdmin) { if (registrationType === 'admin-invite-only' && !isAdmin) {
return helpers.formatApiResponse(403, res, new Error('[[error:no-privileges]]')); return helpers.formatApiResponse(403, res, new Error('[[error:no-privileges]]'));

@ -46,7 +46,7 @@ postgresModule.questions = [
]; ];
postgresModule.init = async function () { postgresModule.init = async function () {
const Pool = require('pg').Pool; const { Pool } = require('pg');
const connOptions = connection.getConnectionOptions(); const connOptions = connection.getConnectionOptions();
const pool = new Pool(connOptions); const pool = new Pool(connOptions);
postgresModule.pool = pool; postgresModule.pool = pool;

@ -34,7 +34,7 @@ connection.getConnectionOptions = function (postgres) {
}; };
connection.connect = async function (options) { connection.connect = async function (options) {
const Pool = require('pg').Pool; const { Pool } = require('pg');
const connOptions = connection.getConnectionOptions(options); const connOptions = connection.getConnectionOptions(options);
const db = new Pool(connOptions); const db = new Pool(connOptions);
await db.connect(); await db.connect();

@ -41,7 +41,7 @@ module.exports = function (module) {
}; };
module.scan = async function (params) { module.scan = async function (params) {
let match = params.match; let { match } = params;
if (match.startsWith('*')) { if (match.startsWith('*')) {
match = `%${match.substring(1)}`; match = `%${match.substring(1)}`;
} }

@ -606,7 +606,7 @@ DELETE FROM "legacy_zset" z
} }
module.getSortedSetScan = async function (params) { module.getSortedSetScan = async function (params) {
let match = params.match; let { match } = params;
if (match.startsWith('*')) { if (match.startsWith('*')) {
match = `%${match.substring(1)}`; match = `%${match.substring(1)}`;
} }

@ -37,7 +37,7 @@ SELECT COUNT(*) c
}; };
async function getSortedSetIntersect(params) { async function getSortedSetIntersect(params) {
const sets = params.sets; const { sets } = params;
const start = params.hasOwnProperty('start') ? params.start : 0; const start = params.hasOwnProperty('start') ? params.start : 0;
const stop = params.hasOwnProperty('stop') ? params.stop : -1; const stop = params.hasOwnProperty('stop') ? params.stop : -1;
let weights = params.weights || []; let weights = params.weights || [];

@ -31,7 +31,7 @@ SELECT COUNT(DISTINCT z."value") c
}; };
async function getSortedSetUnion(params) { async function getSortedSetUnion(params) {
const sets = params.sets; const { sets } = params;
const start = params.hasOwnProperty('start') ? params.start : 0; const start = params.hasOwnProperty('start') ? params.start : 0;
const stop = params.hasOwnProperty('stop') ? params.stop : -1; const stop = params.hasOwnProperty('stop') ? params.stop : -1;
let weights = params.weights || []; let weights = params.weights || [];

@ -3,7 +3,7 @@
const nconf = require('nconf'); const nconf = require('nconf');
const util = require('util'); const util = require('util');
const winston = require('winston'); const winston = require('winston');
const EventEmitter = require('events').EventEmitter; const { EventEmitter } = require('events');
const connection = require('./connection'); const connection = require('./connection');
let channelName; let channelName;

@ -30,7 +30,7 @@ module.exports = function (module) {
}; };
async function getSortedSetRevIntersect(params) { async function getSortedSetRevIntersect(params) {
const sets = params.sets; const { sets } = params;
const start = params.hasOwnProperty('start') ? params.start : 0; const start = params.hasOwnProperty('start') ? params.start : 0;
const stop = params.hasOwnProperty('stop') ? params.stop : -1; const stop = params.hasOwnProperty('stop') ? params.stop : -1;
const weights = params.weights || []; const weights = params.weights || [];

@ -37,7 +37,7 @@ module.exports = function (Groups) {
uid: uid, uid: uid,
name: 'groupCover', name: 'groupCover',
}); });
const url = uploadData.url; const { url } = uploadData;
await Groups.setGroupField(data.groupName, 'cover:url', url); await Groups.setGroupField(data.groupName, 'cover:url', url);
await image.resizeImage({ await image.resizeImage({

@ -3,7 +3,7 @@
const fs = require('fs'); const fs = require('fs');
const path = require('path'); const path = require('path');
const utils = require('./utils'); const utils = require('./utils');
const paths = require('./constants').paths; const { paths } = require('./constants');
const Languages = module.exports; const Languages = module.exports;
const languagesPath = path.join(__dirname, '../build/public/language'); const languagesPath = path.join(__dirname, '../build/public/language');

@ -207,7 +207,7 @@ Logger.io_one = function (socket, uid) {
if (socket && meta.config.loggerIOStatus > 0) { if (socket && meta.config.loggerIOStatus > 0) {
// courtesy of: http://stackoverflow.com/a/9674248 // courtesy of: http://stackoverflow.com/a/9674248
socket.oEmit = socket.emit; socket.oEmit = socket.emit;
const emit = socket.emit; const { emit } = socket;
socket.emit = override(emit, 'emit', 'Logger.io_one: emit.apply: Failed'); socket.emit = override(emit, 'emit', 'Logger.io_one: emit.apply: Failed');
socket.$onvent = socket.onevent; socket.$onvent = socket.onevent;

@ -1,6 +1,6 @@
'use strict'; 'use strict';
const fork = require('child_process').fork; const { fork } = require('child_process');
let debugArg = process.execArgv.find(arg => /^--(debug|inspect)/.test(arg)); let debugArg = process.execArgv.find(arg => /^--(debug|inspect)/.test(arg));
const debugging = !!debugArg; const debugging = !!debugArg;

@ -143,7 +143,7 @@ async function minifyModules(modules, fork) {
} }
async function linkModules() { async function linkModules() {
const modules = JS.scripts.modules; const { modules } = JS.scripts;
await Promise.all(Object.keys(modules).map(async (relPath) => { await Promise.all(Object.keys(modules).map(async (relPath) => {
const srcPath = path.join(__dirname, '../../', modules[relPath]); const srcPath = path.join(__dirname, '../../', modules[relPath]);
@ -179,8 +179,8 @@ async function getModuleList() {
const moduleFiles = []; const moduleFiles = [];
await Promise.all(modules.map(async (module) => { await Promise.all(modules.map(async (module) => {
const srcPath = module.srcPath; const { srcPath } = module;
const destPath = module.destPath; const { destPath } = module;
const stats = await fs.promises.stat(srcPath); const stats = await fs.promises.stat(srcPath);
if (!stats.isDirectory()) { if (!stats.isDirectory()) {

@ -71,8 +71,8 @@ async function writeLanguageFile(language, namespace, translations) {
// run through core and all plugins to generate // run through core and all plugins to generate
// a full translation hash // a full translation hash
async function buildTranslations(ref) { async function buildTranslations(ref) {
const namespaces = ref.namespaces; const { namespaces } = ref;
const languages = ref.languages; const { languages } = ref;
const plugins = _.values(Plugins.pluginsData).filter(plugin => typeof plugin.languages === 'string'); const plugins = _.values(Plugins.pluginsData).filter(plugin => typeof plugin.languages === 'string');
const promises = []; const promises = [];

@ -104,7 +104,7 @@ const actions = {};
if (process.env.minifier_child) { if (process.env.minifier_child) {
process.on('message', (message) => { process.on('message', (message) => {
if (message.type === 'action') { if (message.type === 'action') {
const action = message.action; const { action } = message;
if (typeof actions[action.act] !== 'function') { if (typeof actions[action.act] !== 'function') {
process.send({ process.send({
type: 'error', type: 'error',

@ -42,7 +42,7 @@ middleware.renderHeader = async (req, res, data) => {
privileges: privileges.admin.get(req.uid), privileges: privileges.admin.get(req.uid),
}); });
const userData = results.userData; const { userData } = results;
userData.uid = req.uid; userData.uid = req.uid;
userData['email:confirmed'] = userData['email:confirmed'] === 1; userData['email:confirmed'] = userData['email:confirmed'] === 1;
userData.privileges = results.privileges; userData.privileges = results.privileges;

@ -190,7 +190,7 @@ async function appendUnreadCounts({ uid, navigation, unreadData }) {
} }
}); });
const tidsByFilter = results.unreadData.tidsByFilter; const { tidsByFilter } = results.unreadData;
navigation = navigation.map((item) => { navigation = navigation.map((item) => {
function modifyNavItem(item, route, filter, content) { function modifyNavItem(item, route, filter, content) {
if (item && item.originalRoute === route) { if (item && item.originalRoute === route) {

@ -16,10 +16,10 @@ const relative_path = nconf.get('relative_path');
module.exports = function (middleware) { module.exports = function (middleware) {
middleware.processRender = function processRender(req, res, next) { middleware.processRender = function processRender(req, res, next) {
// res.render post-processing, modified from here: https://gist.github.com/mrlannigan/5051687 // res.render post-processing, modified from here: https://gist.github.com/mrlannigan/5051687
const render = res.render; const { render } = res;
res.render = async function renderOverride(template, options, fn) { res.render = async function renderOverride(template, options, fn) {
const self = this; const self = this;
const req = this.req; const { req } = this;
options = options || {}; options = options || {};
if (typeof options === 'function') { if (typeof options === 'function') {

@ -176,7 +176,7 @@ Plugins.list = async function (matching) {
if (matching === undefined) { if (matching === undefined) {
matching = true; matching = true;
} }
const version = require(paths.currentPackage).version; const { version } = require(paths.currentPackage);
const url = `${nconf.get('registry') || 'https://packages.nodebb.org'}/api/v1/plugins${matching !== false ? `?version=${version}` : ''}`; const url = `${nconf.get('registry') || 'https://packages.nodebb.org'}/api/v1/plugins${matching !== false ? `?version=${version}` : ''}`;
try { try {
const body = await request(url, { const body = await request(url, {
@ -198,7 +198,7 @@ Plugins.listTrending = async () => {
Plugins.normalise = async function (apiReturn) { Plugins.normalise = async function (apiReturn) {
const pluginMap = {}; const pluginMap = {};
const dependencies = require(paths.currentPackage).dependencies; const { dependencies } = require(paths.currentPackage);
apiReturn = Array.isArray(apiReturn) ? apiReturn : []; apiReturn = Array.isArray(apiReturn) ? apiReturn : [];
apiReturn.forEach((packageData) => { apiReturn.forEach((packageData) => {
packageData.id = packageData.name; packageData.id = packageData.name;

@ -14,8 +14,8 @@ const utils = require('../utils');
module.exports = function (Posts) { module.exports = function (Posts) {
Posts.create = async function (data) { Posts.create = async function (data) {
// This is an internal method, consider using Topics.reply instead // This is an internal method, consider using Topics.reply instead
const uid = data.uid; const { uid } = data;
const tid = data.tid; const { tid } = data;
const content = data.content.toString(); const content = data.content.toString();
const timestamp = data.timestamp || Date.now(); const timestamp = data.timestamp || Date.now();
const isMain = data.isMain || false; const isMain = data.isMain || false;

@ -94,7 +94,7 @@ module.exports = function (Posts) {
}; };
async function editMainPost(data, postData) { async function editMainPost(data, postData) {
const tid = postData.tid; const { tid } = postData;
const title = data.title ? data.title.trim() : ''; const title = data.title ? data.title.trim() : '';
const [topicData, isMain] = await Promise.all([ const [topicData, isMain] = await Promise.all([

@ -162,11 +162,11 @@ module.exports = function (privileges) {
return { flag: false, message: '[[error:topic-locked]]' }; return { flag: false, message: '[[error:topic-locked]]' };
} }
const postDeleteDuration = meta.config.postDeleteDuration; const { postDeleteDuration } = meta.config;
if (!results.isMod && postDeleteDuration && (Date.now() - postData.timestamp > postDeleteDuration * 1000)) { if (!results.isMod && postDeleteDuration && (Date.now() - postData.timestamp > postDeleteDuration * 1000)) {
return { flag: false, message: `[[error:post-delete-duration-expired, ${meta.config.postDeleteDuration}]]` }; return { flag: false, message: `[[error:post-delete-duration-expired, ${meta.config.postDeleteDuration}]]` };
} }
const deleterUid = postData.deleterUid; const { deleterUid } = postData;
const flag = results['posts:delete'] && ((results.isOwner && (deleterUid === 0 || deleterUid === postData.uid)) || results.isMod); const flag = results['posts:delete'] && ((results.isOwner && (deleterUid === 0 || deleterUid === postData.uid)) || results.isMod);
return { flag: flag, message: '[[error:no-privileges]]' }; return { flag: flag, message: '[[error:no-privileges]]' };
}; };

@ -126,7 +126,7 @@ module.exports = function (privileges) {
return true; return true;
} }
const preventTopicDeleteAfterReplies = meta.config.preventTopicDeleteAfterReplies; const { preventTopicDeleteAfterReplies } = meta.config;
if (!isModerator && preventTopicDeleteAfterReplies && (topicData.postcount - 1) >= preventTopicDeleteAfterReplies) { if (!isModerator && preventTopicDeleteAfterReplies && (topicData.postcount - 1) >= preventTopicDeleteAfterReplies) {
const langKey = preventTopicDeleteAfterReplies > 1 ? const langKey = preventTopicDeleteAfterReplies > 1 ?
`[[error:cant-delete-topic-has-replies, ${meta.config.preventTopicDeleteAfterReplies}]]` : `[[error:cant-delete-topic-has-replies, ${meta.config.preventTopicDeleteAfterReplies}]]` :
@ -134,7 +134,7 @@ module.exports = function (privileges) {
throw new Error(langKey); throw new Error(langKey);
} }
const deleterUid = topicData.deleterUid; const { deleterUid } = topicData;
return allowedTo[0] && ((isOwner && (deleterUid === 0 || deleterUid === topicData.uid)) || isModerator); return allowedTo[0] && ((isOwner && (deleterUid === 0 || deleterUid === topicData.uid)) || isModerator);
}; };

@ -5,7 +5,7 @@ const nconf = require('nconf');
const helpers = require('./helpers'); const helpers = require('./helpers');
const setupPageRoute = helpers.setupPageRoute; const { setupPageRoute } = helpers;
module.exports = function (app, middleware, controllers) { module.exports = function (app, middleware, controllers) {
const middlewares = [middleware.exposeUid, middleware.canViewUsers]; const middlewares = [middleware.exposeUid, middleware.canViewUsers];

@ -76,7 +76,7 @@ Auth.verifyToken = async function (token, done) {
Auth.reloadRoutes = async function (params) { Auth.reloadRoutes = async function (params) {
loginStrategies.length = 0; loginStrategies.length = 0;
const router = params.router; const { router } = params;
// Local Logins // Local Logins
if (plugins.hooks.hasListeners('action:auth.overrideLogin')) { if (plugins.hooks.hasListeners('action:auth.overrideLogin')) {

@ -16,7 +16,7 @@ module.exports = function (app) {
// Redoc // Redoc
router.get('/spec/:type', async (req, res, next) => { router.get('/spec/:type', async (req, res, next) => {
const types = ['read', 'write']; const types = ['read', 'write'];
const type = req.params.type; const { type } = req.params;
if (!types.includes(type)) { if (!types.includes(type)) {
return next(); return next();
} }

@ -39,7 +39,7 @@ module.exports = function (app, middleware) {
async function validateTokenIfRequiresLogin(requiresLogin, cid, req, res) { async function validateTokenIfRequiresLogin(requiresLogin, cid, req, res) {
const uid = parseInt(req.query.uid, 10) || 0; const uid = parseInt(req.query.uid, 10) || 0;
const token = req.query.token; const { token } = req.query;
if (!requiresLogin) { if (!requiresLogin) {
return true; return true;
@ -379,7 +379,7 @@ async function generateForUserTopics(req, res, next) {
return controllers404.send404(req, res); return controllers404.send404(req, res);
} }
const userslug = req.params.userslug; const { userslug } = req.params;
const uid = await user.getUidByUserslug(userslug); const uid = await user.getUidByUserslug(userslug);
if (!uid) { if (!uid) {
return next(); return next();

@ -18,7 +18,7 @@ const authRoutes = require('./authentication');
const writeRoutes = require('./write'); const writeRoutes = require('./write');
const helpers = require('./helpers'); const helpers = require('./helpers');
const setupPageRoute = helpers.setupPageRoute; const { setupPageRoute } = helpers;
function mainRoutes(app, middleware, controllers) { function mainRoutes(app, middleware, controllers) {
const loginRegisterMiddleware = [middleware.redirectToAccountIfLoggedIn]; const loginRegisterMiddleware = [middleware.redirectToAccountIfLoggedIn];

@ -5,7 +5,7 @@ const middleware = require('../../middleware');
const controllers = require('../../controllers'); const controllers = require('../../controllers');
const routeHelpers = require('../helpers'); const routeHelpers = require('../helpers');
const setupApiRoute = routeHelpers.setupApiRoute; const { setupApiRoute } = routeHelpers;
module.exports = function () { module.exports = function () {
const middlewares = [middleware.authenticate]; const middlewares = [middleware.authenticate];

@ -5,7 +5,7 @@ const middleware = require('../../middleware');
const controllers = require('../../controllers'); const controllers = require('../../controllers');
const routeHelpers = require('../helpers'); const routeHelpers = require('../helpers');
const setupApiRoute = routeHelpers.setupApiRoute; const { setupApiRoute } = routeHelpers;
module.exports = function () { module.exports = function () {
const middlewares = [middleware.authenticate]; const middlewares = [middleware.authenticate];

@ -5,7 +5,7 @@ const middleware = require('../../middleware');
const controllers = require('../../controllers'); const controllers = require('../../controllers');
const routeHelpers = require('../helpers'); const routeHelpers = require('../helpers');
const setupApiRoute = routeHelpers.setupApiRoute; const { setupApiRoute } = routeHelpers;
module.exports = function () { module.exports = function () {
const middlewares = [middleware.authenticate]; const middlewares = [middleware.authenticate];

@ -5,7 +5,7 @@ const middleware = require('../../middleware');
const controllers = require('../../controllers'); const controllers = require('../../controllers');
const routeHelpers = require('../helpers'); const routeHelpers = require('../helpers');
const setupApiRoute = routeHelpers.setupApiRoute; const { setupApiRoute } = routeHelpers;
module.exports = function () { module.exports = function () {
const middlewares = [middleware.authenticate]; const middlewares = [middleware.authenticate];

@ -10,7 +10,7 @@ const helpers = require('../../controllers/helpers');
const Write = module.exports; const Write = module.exports;
Write.reload = async (params) => { Write.reload = async (params) => {
const router = params.router; const { router } = params;
let apiSettings = await meta.settings.get('core.api'); let apiSettings = await meta.settings.get('core.api');
plugins.hooks.register('core', { plugins.hooks.register('core', {
hook: 'action:settings.set', hook: 'action:settings.set',

@ -5,7 +5,7 @@ const middleware = require('../../middleware');
const controllers = require('../../controllers'); const controllers = require('../../controllers');
const routeHelpers = require('../helpers'); const routeHelpers = require('../helpers');
const setupApiRoute = routeHelpers.setupApiRoute; const { setupApiRoute } = routeHelpers;
module.exports = function () { module.exports = function () {
const middlewares = [middleware.authenticate]; const middlewares = [middleware.authenticate];

@ -5,7 +5,7 @@ const middleware = require('../../middleware');
const controllers = require('../../controllers'); const controllers = require('../../controllers');
const routeHelpers = require('../helpers'); const routeHelpers = require('../helpers');
const setupApiRoute = routeHelpers.setupApiRoute; const { setupApiRoute } = routeHelpers;
module.exports = function () { module.exports = function () {
const middlewares = [middleware.authenticate]; const middlewares = [middleware.authenticate];

@ -5,7 +5,7 @@ const middleware = require('../../middleware');
const controllers = require('../../controllers'); const controllers = require('../../controllers');
const routeHelpers = require('../helpers'); const routeHelpers = require('../helpers');
const setupApiRoute = routeHelpers.setupApiRoute; const { setupApiRoute } = routeHelpers;
// eslint-disable-next-line no-unused-vars // eslint-disable-next-line no-unused-vars
function guestRoutes() { function guestRoutes() {

@ -5,7 +5,7 @@ const middleware = require('../../middleware');
const controllers = require('../../controllers'); const controllers = require('../../controllers');
const routeHelpers = require('../helpers'); const routeHelpers = require('../helpers');
const setupApiRoute = routeHelpers.setupApiRoute; const { setupApiRoute } = routeHelpers;
module.exports = function () { module.exports = function () {
// The "ping" routes are mounted at root level, but for organizational purposes, the controllers are in `utilities.js` // The "ping" routes are mounted at root level, but for organizational purposes, the controllers are in `utilities.js`

@ -6,7 +6,7 @@ const userDigest = require('../../user/digest');
const Digest = module.exports; const Digest = module.exports;
Digest.resend = async (socket, data) => { Digest.resend = async (socket, data) => {
const uid = data.uid; const { uid } = data;
const interval = data.action.startsWith('resend-') ? data.action.slice(7) : await userDigest.getUsersInterval(uid); const interval = data.action.startsWith('resend-') ? data.action.slice(7) : await userDigest.getUsersInterval(uid);
if (!interval && meta.config.dailyDigestFreq === 'off') { if (!interval && meta.config.dailyDigestFreq === 'off') {

@ -36,8 +36,8 @@ SocketHelpers.notifyNew = async function (uid, type, result) {
async function notifyUids(uid, uids, type, result) { async function notifyUids(uid, uids, type, result) {
const post = result.posts[0]; const post = result.posts[0];
const tid = post.topic.tid; const { tid } = post.topic;
const cid = post.topic.cid; const { cid } = post.topic;
uids = await privileges.topics.filterUids('topics:read', tid, uids); uids = await privileges.topics.filterUids('topics:read', tid, uids);
const watchStateUids = uids; const watchStateUids = uids;
@ -150,10 +150,10 @@ SocketHelpers.upvote = async function (data, notification) {
return; return;
} }
const votes = data.post.votes; const { votes } = data.post;
const touid = data.post.uid; const touid = data.post.uid;
const fromuid = data.fromuid; const { fromuid } = data;
const pid = data.post.pid; const { pid } = data.post;
const shouldNotify = { const shouldNotify = {
all: function () { all: function () {

@ -207,7 +207,7 @@ async function validateSession(socket) {
const cookieParserAsync = util.promisify((req, callback) => cookieParser(req, {}, err => callback(err))); const cookieParserAsync = util.promisify((req, callback) => cookieParser(req, {}, err => callback(err)));
async function authorize(socket, callback) { async function authorize(socket, callback) {
const request = socket.request; const { request } = socket;
if (!request) { if (!request) {
return callback(new Error('[[error:not-authorized]]')); return callback(new Error('[[error:not-authorized]]'));

@ -21,7 +21,7 @@ uploads.upload = async function (socket, data) {
inProgress[socket.id] = inProgress[socket.id] || {}; inProgress[socket.id] = inProgress[socket.id] || {};
const socketUploads = inProgress[socket.id]; const socketUploads = inProgress[socket.id];
const method = data.params.method; const { method } = data.params;
socketUploads[method] = socketUploads[method] || { imageData: '' }; socketUploads[method] = socketUploads[method] || { imageData: '' };
socketUploads[method].imageData += data.chunk; socketUploads[method].imageData += data.chunk;

@ -17,7 +17,7 @@ module.exports = function (SocketUser) {
throw new Error('[[error:invalid-data]]'); throw new Error('[[error:invalid-data]]');
} }
const type = data.type; const { type } = data;
let picture = ''; let picture = '';
await user.isAdminOrGlobalModOrSelf(socket.uid, data.uid); await user.isAdminOrGlobalModOrSelf(socket.uid, data.uid);
if (type === 'default') { if (type === 'default') {

@ -54,7 +54,7 @@ module.exports = function (SocketUser) {
}; };
async function isPrivilegedOrSelfAndPasswordMatch(socket, data) { async function isPrivilegedOrSelfAndPasswordMatch(socket, data) {
const uid = socket.uid; const { uid } = socket;
const isSelf = parseInt(uid, 10) === parseInt(data.uid, 10); const isSelf = parseInt(uid, 10) === parseInt(data.uid, 10);
const [isAdmin, isTargetAdmin, isGlobalMod] = await Promise.all([ const [isAdmin, isTargetAdmin, isGlobalMod] = await Promise.all([

@ -62,7 +62,7 @@ module.exports = function (Topics) {
}; };
Topics.post = async function (data) { Topics.post = async function (data) {
const uid = data.uid; const { uid } = data;
data.title = String(data.title).trim(); data.title = String(data.title).trim();
data.tags = data.tags || []; data.tags = data.tags || [];
if (data.content) { if (data.content) {
@ -133,8 +133,8 @@ module.exports = function (Topics) {
}; };
Topics.reply = async function (data) { Topics.reply = async function (data) {
const tid = data.tid; const { tid } = data;
const uid = data.uid; const { uid } = data;
const topicData = await Topics.getTopicData(tid); const topicData = await Topics.getTopicData(tid);
if (!topicData) { if (!topicData) {
@ -199,8 +199,8 @@ module.exports = function (Topics) {
}; };
async function onNewPost(postData, data) { async function onNewPost(postData, data) {
const tid = postData.tid; const { tid } = postData;
const uid = postData.uid; const { uid } = postData;
await Topics.markAsUnreadForAll(tid); await Topics.markAsUnreadForAll(tid);
await Topics.markAsRead([tid], uid); await Topics.markAsRead([tid], uid);
const [ const [

@ -157,7 +157,7 @@ module.exports = function (Topics) {
return; return;
} }
let title = postData.topic.title; let { title } = postData.topic;
if (title) { if (title) {
title = utils.decodeHTMLEntities(title); title = utils.decodeHTMLEntities(title);
} }

@ -121,8 +121,8 @@ module.exports = function (Topics) {
} }
async function filterTids(tids, params) { async function filterTids(tids, params) {
const filter = params.filter; const { filter } = params;
const uid = params.uid; const { uid } = params;
if (filter === 'new') { if (filter === 'new') {
tids = await Topics.filterNewTids(tids, uid); tids = await Topics.filterNewTids(tids, uid);

@ -411,7 +411,7 @@ module.exports = function (Topics) {
} }
async function findMatches(data) { async function findMatches(data) {
let query = data.query; let { query } = data;
let tagWhitelist = []; let tagWhitelist = [];
if (parseInt(data.cid, 10)) { if (parseInt(data.cid, 10)) {
tagWhitelist = await categories.getTagWhitelist([data.cid]); tagWhitelist = await categories.getTagWhitelist([data.cid]);

@ -17,7 +17,7 @@ module.exports = function (Topics) {
return []; return [];
} }
let uid = options; let uid = options;
let teaserPost = meta.config.teaserPost; let { teaserPost } = meta.config;
if (typeof options === 'object') { if (typeof options === 'object') {
uid = options.uid; uid = options.uid;
teaserPost = options.teaserPost || meta.config.teaserPost; teaserPost = options.teaserPost || meta.config.teaserPost;

@ -218,7 +218,7 @@ module.exports = function (Topics) {
} }
async function doesTidHaveUnblockedUnreadPosts(tid, params) { async function doesTidHaveUnblockedUnreadPosts(tid, params) {
const userLastReadTimestamp = params.userLastReadTimestamp; const { userLastReadTimestamp } = params;
if (!userLastReadTimestamp) { if (!userLastReadTimestamp) {
return true; return true;
} }

@ -10,7 +10,7 @@ module.exports = {
timestamp: Date.UTC(2016, 0, 14), timestamp: Date.UTC(2016, 0, 14),
method: function (callback) { method: function (callback) {
const batch = require('../../batch'); const batch = require('../../batch');
const progress = this.progress; const { progress } = this;
batch.processSortedSet('posts:pid', (ids, next) => { batch.processSortedSet('posts:pid', (ids, next) => {
async.eachSeries(ids, (id, next) => { async.eachSeries(ids, (id, next) => {

@ -23,8 +23,8 @@ module.exports = {
return next(err); return next(err);
} }
const groups = data.groups; const { groups } = data;
const users = data.users; const { users } = data;
async.waterfall([ async.waterfall([
function (next) { function (next) {

@ -12,7 +12,7 @@ module.exports = {
const batch = require('../../batch'); const batch = require('../../batch');
const posts = require('../../posts'); const posts = require('../../posts');
let count = 0; let count = 0;
const progress = this.progress; const { progress } = this;
batch.processSortedSet('posts:pid', (pids, next) => { batch.processSortedSet('posts:pid', (pids, next) => {
winston.verbose(`upgraded ${count} posts`); winston.verbose(`upgraded ${count} posts`);

@ -11,7 +11,7 @@ module.exports = {
name: 'Hash all IP addresses stored in Recent IPs zset', name: 'Hash all IP addresses stored in Recent IPs zset',
timestamp: Date.UTC(2018, 5, 22), timestamp: Date.UTC(2018, 5, 22),
method: function (callback) { method: function (callback) {
const progress = this.progress; const { progress } = this;
const hashed = /[a-f0-9]{32}/; const hashed = /[a-f0-9]{32}/;
let hash; let hash;

@ -9,7 +9,7 @@ module.exports = {
name: 'add filters to events', name: 'add filters to events',
timestamp: Date.UTC(2018, 9, 4), timestamp: Date.UTC(2018, 9, 4),
method: function (callback) { method: function (callback) {
const progress = this.progress; const { progress } = this;
batch.processSortedSet('events:time', (eids, next) => { batch.processSortedSet('events:time', (eids, next) => {
async.eachSeries(eids, (eid, next) => { async.eachSeries(eids, (eid, next) => {

@ -9,7 +9,7 @@ module.exports = {
name: 'Fix category post zsets', name: 'Fix category post zsets',
timestamp: Date.UTC(2018, 9, 10), timestamp: Date.UTC(2018, 9, 10),
method: function (callback) { method: function (callback) {
const progress = this.progress; const { progress } = this;
db.getSortedSetRange('categories:cid', 0, -1, (err, cids) => { db.getSortedSetRange('categories:cid', 0, -1, (err, cids) => {
if (err) { if (err) {

@ -9,7 +9,7 @@ module.exports = {
name: 'Fix category topic zsets', name: 'Fix category topic zsets',
timestamp: Date.UTC(2018, 9, 11), timestamp: Date.UTC(2018, 9, 11),
method: function (callback) { method: function (callback) {
const progress = this.progress; const { progress } = this;
const topics = require('../../topics'); const topics = require('../../topics');
batch.processSortedSet('topics:tid', (tids, next) => { batch.processSortedSet('topics:tid', (tids, next) => {

@ -10,7 +10,7 @@ module.exports = {
name: 'Upgrade bans to hashes', name: 'Upgrade bans to hashes',
timestamp: Date.UTC(2018, 8, 24), timestamp: Date.UTC(2018, 8, 24),
method: function (callback) { method: function (callback) {
const progress = this.progress; const { progress } = this;
batch.processSortedSet('users:joindate', (uids, next) => { batch.processSortedSet('users:joindate', (uids, next) => {
async.eachSeries(uids, (uid, next) => { async.eachSeries(uids, (uid, next) => {

@ -10,7 +10,7 @@ module.exports = {
name: 'Record first entry in username/email history', name: 'Record first entry in username/email history',
timestamp: Date.UTC(2018, 7, 28), timestamp: Date.UTC(2018, 7, 28),
method: function (callback) { method: function (callback) {
const progress = this.progress; const { progress } = this;
batch.processSortedSet('users:joindate', (ids, next) => { batch.processSortedSet('users:joindate', (ids, next) => {
async.each(ids, (uid, next) => { async.each(ids, (uid, next) => {

@ -8,7 +8,7 @@ module.exports = {
name: 'Remove uid:<uid>:ignored:cids', name: 'Remove uid:<uid>:ignored:cids',
timestamp: Date.UTC(2018, 11, 11), timestamp: Date.UTC(2018, 11, 11),
method: function (callback) { method: function (callback) {
const progress = this.progress; const { progress } = this;
batch.processSortedSet('users:joindate', (uids, next) => { batch.processSortedSet('users:joindate', (uids, next) => {
progress.incr(uids.length); progress.incr(uids.length);

@ -10,7 +10,7 @@ module.exports = {
name: 'Update category watch data', name: 'Update category watch data',
timestamp: Date.UTC(2018, 11, 13), timestamp: Date.UTC(2018, 11, 13),
method: function (callback) { method: function (callback) {
const progress = this.progress; const { progress } = this;
let keys; let keys;
async.waterfall([ async.waterfall([
function (next) { function (next) {

@ -8,7 +8,7 @@ module.exports = {
name: 'Delete username email history for deleted users', name: 'Delete username email history for deleted users',
timestamp: Date.UTC(2019, 2, 25), timestamp: Date.UTC(2019, 2, 25),
method: function (callback) { method: function (callback) {
const progress = this.progress; const { progress } = this;
let currentUid = 1; let currentUid = 1;
db.getObjectField('global', 'nextUid', (err, nextUid) => { db.getObjectField('global', 'nextUid', (err, nextUid) => {
if (err) { if (err) {

@ -9,7 +9,7 @@ module.exports = {
name: 'Update moderation notes to hashes', name: 'Update moderation notes to hashes',
timestamp: Date.UTC(2019, 3, 5), timestamp: Date.UTC(2019, 3, 5),
method: function (callback) { method: function (callback) {
const progress = this.progress; const { progress } = this;
batch.processSortedSet('users:joindate', (ids, next) => { batch.processSortedSet('users:joindate', (ids, next) => {
async.each(ids, (uid, next) => { async.each(ids, (uid, next) => {

@ -9,7 +9,7 @@ module.exports = {
name: 'Calculate image sizes of all uploaded images', name: 'Calculate image sizes of all uploaded images',
timestamp: Date.UTC(2019, 2, 16), timestamp: Date.UTC(2019, 2, 16),
method: function (callback) { method: function (callback) {
const progress = this.progress; const { progress } = this;
batch.processSortedSet('posts:pid', (postData, next) => { batch.processSortedSet('posts:pid', (postData, next) => {
async.eachSeries(postData, async (pid) => { async.eachSeries(postData, async (pid) => {

@ -11,7 +11,7 @@ module.exports = {
name: 'Create zsets for user posts per category', name: 'Create zsets for user posts per category',
timestamp: Date.UTC(2019, 5, 23), timestamp: Date.UTC(2019, 5, 23),
method: function (callback) { method: function (callback) {
const progress = this.progress; const { progress } = this;
batch.processSortedSet('posts:pid', (pids, next) => { batch.processSortedSet('posts:pid', (pids, next) => {
progress.incr(pids.length); progress.incr(pids.length);

@ -7,7 +7,7 @@ module.exports = {
name: 'Clean flag byCid zsets', name: 'Clean flag byCid zsets',
timestamp: Date.UTC(2019, 8, 24), timestamp: Date.UTC(2019, 8, 24),
method: async function () { method: async function () {
const progress = this.progress; const { progress } = this;
await batch.processSortedSet('flags:datetime', async (flagIds) => { await batch.processSortedSet('flags:datetime', async (flagIds) => {
progress.incr(flagIds.length); progress.incr(flagIds.length);

@ -7,7 +7,7 @@ module.exports = {
name: 'Clean up post hash data', name: 'Clean up post hash data',
timestamp: Date.UTC(2019, 9, 7), timestamp: Date.UTC(2019, 9, 7),
method: async function () { method: async function () {
const progress = this.progress; const { progress } = this;
await cleanPost(progress); await cleanPost(progress);
await cleanTopic(progress); await cleanTopic(progress);
}, },

@ -8,7 +8,7 @@ module.exports = {
name: 'Clean up old notifications and hash data', name: 'Clean up old notifications and hash data',
timestamp: Date.UTC(2019, 9, 7), timestamp: Date.UTC(2019, 9, 7),
method: async function () { method: async function () {
const progress = this.progress; const { progress } = this;
const week = 604800000; const week = 604800000;
const cutoffTime = Date.now() - week; const cutoffTime = Date.now() - week;
await batch.processSortedSet('users:joindate', async (uids) => { await batch.processSortedSet('users:joindate', async (uids) => {

@ -7,7 +7,7 @@ module.exports = {
name: 'Fix user sorted sets', name: 'Fix user sorted sets',
timestamp: Date.UTC(2020, 4, 2), timestamp: Date.UTC(2020, 4, 2),
method: async function () { method: async function () {
const progress = this.progress; const { progress } = this;
const nextUid = await db.getObjectField('global', 'nextUid'); const nextUid = await db.getObjectField('global', 'nextUid');
const allUids = []; const allUids = [];
for (let i = 1; i <= nextUid; i++) { for (let i = 1; i <= nextUid; i++) {

@ -8,7 +8,7 @@ module.exports = {
name: 'Re-add deleted topics to topics:recent', name: 'Re-add deleted topics to topics:recent',
timestamp: Date.UTC(2018, 9, 11), timestamp: Date.UTC(2018, 9, 11),
method: async function () { method: async function () {
const progress = this.progress; const { progress } = this;
await batch.processSortedSet('topics:tid', async (tids) => { await batch.processSortedSet('topics:tid', async (tids) => {
progress.incr(tids.length); progress.incr(tids.length);

@ -8,7 +8,7 @@ module.exports = {
name: 'Add target uid to flag objects', name: 'Add target uid to flag objects',
timestamp: Date.UTC(2020, 7, 22), timestamp: Date.UTC(2020, 7, 22),
method: async function () { method: async function () {
const progress = this.progress; const { progress } = this;
await batch.processSortedSet('flags:datetime', async (flagIds) => { await batch.processSortedSet('flags:datetime', async (flagIds) => {
progress.incr(flagIds.length); progress.incr(flagIds.length);
@ -16,7 +16,7 @@ module.exports = {
for (const flagObj of flagData) { for (const flagObj of flagData) {
/* eslint-disable no-await-in-loop */ /* eslint-disable no-await-in-loop */
if (flagObj) { if (flagObj) {
const targetId = flagObj.targetId; const { targetId } = flagObj;
if (targetId) { if (targetId) {
if (flagObj.type === 'post') { if (flagObj.type === 'post') {
const targetUid = await posts.getPostField(targetId, 'uid'); const targetUid = await posts.getPostField(targetId, 'uid');

@ -9,7 +9,7 @@ module.exports = {
name: 'Consolidate multiple flags reports, going forward', name: 'Consolidate multiple flags reports, going forward',
timestamp: Date.UTC(2020, 6, 16), timestamp: Date.UTC(2020, 6, 16),
method: async function () { method: async function () {
const progress = this.progress; const { progress } = this;
let flags = await db.getSortedSetRange('flags:datetime', 0, -1); let flags = await db.getSortedSetRange('flags:datetime', 0, -1);
flags = flags.map(flagId => `flag:${flagId}`); flags = flags.map(flagId => `flag:${flagId}`);

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save