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"],
// only require const if all parts of destructuring can be const
"prefer-const": ["error", { "destructuring": "all" }],
// don't require destructuring when assigning
// "prefer-destructuring": ["error", {
// "VariableDeclarator": { "array": true, "object": true },
// "AssignmentExpression": { "array": false, "object": false }
// }],
"prefer-destructuring": "off",
// don't require destructuring for arrays or assignment
"prefer-destructuring": ["error", {
"VariableDeclarator": { "array": false, "object": true },
"AssignmentExpression": { "array": false, "object": false }
}],
// identical to airbnb rule, except for allowing for..of, because we want to use it
// "no-restricted-syntax": [
// "error",

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

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

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

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

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

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

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

@ -55,7 +55,7 @@ module.exports = function (Categories) {
return result && result.tids;
}
let start = data.start;
let { start } = data;
if (start > 0 && totalPinnedCount) {
start -= totalPinnedCount - pinnedCountOnPage;
}
@ -91,7 +91,7 @@ module.exports = function (Categories) {
};
Categories.buildTopicsSortedSet = async function (data) {
const cid = data.cid;
const { cid } = data;
let set = `cid:${cid}:tids`;
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 category = result.category;
const { category } = result;
const fields = Object.keys(category);
// move parent to front, so its updated first
const parentCidIndex = fields.indexOf('parentCid');

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

@ -41,7 +41,7 @@ try {
const defaultPackage = require('../../install/package.json');
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])) {
const e = new TypeError(`Incorrect dependency version: ${packageName}`);
e.code = 'DEP_WRONG_VERSION';

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

@ -7,7 +7,7 @@ const packageInstall = require('./package-install');
const upgrade = require('../upgrade');
const build = require('../meta/build');
const db = require('../database');
const upgradePlugins = require('./upgrade-plugins').upgradePlugins;
const { upgradePlugins } = require('./upgrade-plugins');
const steps = {
package: {
@ -69,7 +69,7 @@ function runSteps(tasks) {
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
const columns = process.stdout.columns;
const { columns } = process.stdout;
const spaces = columns ? new Array(Math.floor(columns / 2) - (message.length / 2) + 1).join(' ') : ' ';
console.log(`\n\n${spaces}${message.green.bold}${'\n'.reset}`);

@ -28,12 +28,12 @@ helpers.getUserDataByUserSlug = async function (userslug, callerUID) {
}
await parseAboutMe(results.userData);
const userData = results.userData;
const userSettings = results.userSettings;
const isAdmin = results.isAdmin;
const isGlobalModerator = results.isGlobalModerator;
const isModerator = results.isModerator;
const canViewInfo = results.canViewInfo;
const { userData } = results;
const { userSettings } = results;
const { isAdmin } = results;
const { isGlobalModerator } = results;
const { isModerator } = results;
const { canViewInfo } = results;
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);
@ -140,7 +140,7 @@ async function getAllData(uid, callerUID) {
}
async function getCounts(userData, callerUID) {
const uid = userData.uid;
const { uid } = userData;
const cids = await categories.getCidsByPrivilege('categories:cid', callerUID, 'topics:read');
const promises = {
posts: db.sortedSetsCardSum(cids.map(c => `cid:${c}:uid:${uid}:pids`)),

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

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

@ -69,7 +69,7 @@ async function getGroupNames() {
}
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')) {
return res.status(403).send('[[error:invalid-origin]]');

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

@ -227,7 +227,7 @@ async function getInvites() {
async function render(req, res, data) {
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.adminInviteOnly = registrationType === 'admin-invite-only';

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

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

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

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

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

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

@ -13,7 +13,7 @@ const helpers = require('./helpers');
const unreadController = module.exports;
unreadController.get = async function (req, res) {
const cid = req.query.cid;
const { cid } = req.query;
const filter = req.query.filter || '';
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) {
const registrationType = meta.config.registrationType;
const { registrationType } = meta.config;
data.maximumInvites = meta.config.maximumInvites;
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]]'));
}
const registrationType = meta.config.registrationType;
const { registrationType } = meta.config;
const isAdmin = await user.isAdministrator(req.uid);
if (registrationType === 'admin-invite-only' && !isAdmin) {
return helpers.formatApiResponse(403, res, new Error('[[error:no-privileges]]'));

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

@ -42,7 +42,7 @@ middleware.renderHeader = async (req, res, data) => {
privileges: privileges.admin.get(req.uid),
});
const userData = results.userData;
const { userData } = results;
userData.uid = req.uid;
userData['email:confirmed'] = userData['email:confirmed'] === 1;
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) => {
function modifyNavItem(item, route, filter, content) {
if (item && item.originalRoute === route) {

@ -16,10 +16,10 @@ const relative_path = nconf.get('relative_path');
module.exports = function (middleware) {
middleware.processRender = function processRender(req, res, next) {
// 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) {
const self = this;
const req = this.req;
const { req } = this;
options = options || {};
if (typeof options === 'function') {

@ -176,7 +176,7 @@ Plugins.list = async function (matching) {
if (matching === undefined) {
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}` : ''}`;
try {
const body = await request(url, {
@ -198,7 +198,7 @@ Plugins.listTrending = async () => {
Plugins.normalise = async function (apiReturn) {
const pluginMap = {};
const dependencies = require(paths.currentPackage).dependencies;
const { dependencies } = require(paths.currentPackage);
apiReturn = Array.isArray(apiReturn) ? apiReturn : [];
apiReturn.forEach((packageData) => {
packageData.id = packageData.name;

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

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

@ -162,11 +162,11 @@ module.exports = function (privileges) {
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)) {
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);
return { flag: flag, message: '[[error:no-privileges]]' };
};

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

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

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

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

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

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

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

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

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

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

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

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

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

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

@ -5,7 +5,7 @@ const middleware = require('../../middleware');
const controllers = require('../../controllers');
const routeHelpers = require('../helpers');
const setupApiRoute = routeHelpers.setupApiRoute;
const { setupApiRoute } = routeHelpers;
module.exports = function () {
// 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;
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);
if (!interval && meta.config.dailyDigestFreq === 'off') {

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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