chore: eslint no-restricted-syntax

v1.18.x
Peter Jaszkowiak 4 years ago committed by Julian Lam
parent 115d19e289
commit 5c2f0f0557

@ -65,22 +65,21 @@
"AssignmentExpression": { "array": false, "object": false } "AssignmentExpression": { "array": false, "object": false }
}], }],
// 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",
// { {
// "selector": "ForInStatement", "selector": "ForInStatement",
// "message": "for..in loops iterate over the entire prototype chain, which is virtually never what you want. Use Object.{keys,values,entries}, and iterate over the resulting array." "message": "for..in loops iterate over the entire prototype chain, which is virtually never what you want. Use Object.{keys,values,entries}, and iterate over the resulting array."
// }, },
// { {
// "selector": "LabeledStatement", "selector": "LabeledStatement",
// "message": "Labels are a form of GOTO; using them makes code confusing and hard to maintain and understand." "message": "Labels are a form of GOTO; using them makes code confusing and hard to maintain and understand."
// }, },
// { {
// "selector": "WithStatement", "selector": "WithStatement",
// "message": "`with` is disallowed in strict mode because it makes code impossible to predict and optimize." "message": "`with` is disallowed in strict mode because it makes code impossible to predict and optimize."
// } }
// ], ],
"no-restricted-syntax": "off",
// allow lines of up to 120 characters // allow lines of up to 120 characters
// "max-len": ["error", { "code": 120, "tabWidth": 2, "ignoreUrls": true, "ignoreStrings": true, "ignoreTemplateLiterals": true, "ignoreRegExpLiterals": true }], // "max-len": ["error", { "code": 120, "tabWidth": 2, "ignoreUrls": true, "ignoreStrings": true, "ignoreTemplateLiterals": true, "ignoreRegExpLiterals": true }],
"max-len": "off", // do this LAST "max-len": "off", // do this LAST

@ -151,9 +151,9 @@ function install(req, res) {
req.setTimeout(0); req.setTimeout(0);
installing = true; installing = true;
const setupEnvVars = nconf.get(); const setupEnvVars = nconf.get();
for (const i in req.body) { for (const [key, value] of Object.entries(req.body)) {
if (req.body.hasOwnProperty(i) && !process.env.hasOwnProperty(i)) { if (!process.env.hasOwnProperty(key)) {
setupEnvVars[i.replace(':', '__')] = req.body[i]; setupEnvVars[key.replace(':', '__')] = value;
} }
} }
@ -161,12 +161,12 @@ function install(req, res) {
const pushToRoot = function (parentKey, key) { const pushToRoot = function (parentKey, key) {
setupEnvVars[`${parentKey}__${key}`] = setupEnvVars[parentKey][key]; setupEnvVars[`${parentKey}__${key}`] = setupEnvVars[parentKey][key];
}; };
for (const j in setupEnvVars) { for (const [parentKey, value] of Object.entries(setupEnvVars)) {
if (setupEnvVars.hasOwnProperty(j) && typeof setupEnvVars[j] === 'object' && setupEnvVars[j] !== null && !Array.isArray(setupEnvVars[j])) { if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
Object.keys(setupEnvVars[j]).forEach(pushToRoot.bind(null, j)); Object.keys(value).forEach(key => pushToRoot(parentKey, key));
delete setupEnvVars[j]; delete setupEnvVars[parentKey];
} else if (Array.isArray(setupEnvVars[j])) { } else if (Array.isArray(value)) {
setupEnvVars[j] = JSON.stringify(setupEnvVars[j]); setupEnvVars[parentKey] = JSON.stringify(value);
} }
} }

@ -128,14 +128,10 @@ Analytics.writeData = async function () {
uniqueIPCount = 0; uniqueIPCount = 0;
} }
if (Object.keys(counters).length > 0) { for (const [key, value] of Object.entries(counters)) {
for (const key in counters) { dbQueue.push(db.sortedSetIncrBy(`analytics:${key}`, value, today.getTime()));
if (counters.hasOwnProperty(key)) {
dbQueue.push(db.sortedSetIncrBy(`analytics:${key}`, counters[key], today.getTime()));
delete counters[key]; delete counters[key];
} }
}
}
try { try {
await Promise.all(dbQueue); await Promise.all(dbQueue);
} catch (err) { } catch (err) {

@ -28,9 +28,9 @@ helpers.fieldToString = function (field) {
helpers.serializeData = function (data) { helpers.serializeData = function (data) {
const serialized = {}; const serialized = {};
for (const field in data) { for (const [field, value] of Object.entries(data)) {
if (data.hasOwnProperty(field) && field !== '') { if (field !== '') {
serialized[helpers.fieldToString(field)] = data[field]; serialized[helpers.fieldToString(field)] = value;
} }
} }
return serialized; return serialized;
@ -38,10 +38,8 @@ helpers.serializeData = function (data) {
helpers.deserializeData = function (data) { helpers.deserializeData = function (data) {
const deserialized = {}; const deserialized = {};
for (const field in data) { for (const [field, value] of Object.entries(data)) {
if (data.hasOwnProperty(field)) { deserialized[field.replace(/\uff0E/g, '.')] = value;
deserialized[field.replace(/\uff0E/g, '.')] = data[field];
}
} }
return deserialized; return deserialized;
}; };

@ -135,15 +135,13 @@ Flags.getFlagIdsWithFilters = async function ({ filters, uid }) {
filters.page = filters.hasOwnProperty('page') ? Math.abs(parseInt(filters.page, 10) || 1) : 1; filters.page = filters.hasOwnProperty('page') ? Math.abs(parseInt(filters.page, 10) || 1) : 1;
filters.perPage = filters.hasOwnProperty('perPage') ? Math.abs(parseInt(filters.perPage, 10) || 20) : 20; filters.perPage = filters.hasOwnProperty('perPage') ? Math.abs(parseInt(filters.perPage, 10) || 20) : 20;
for (const type in filters) { for (const type of Object.keys(filters)) {
if (filters.hasOwnProperty(type)) {
if (Flags._filters.hasOwnProperty(type)) { if (Flags._filters.hasOwnProperty(type)) {
Flags._filters[type](sets, orSets, filters[type], uid); Flags._filters[type](sets, orSets, filters[type], uid);
} else { } else {
winston.warn(`[flags/list] No flag filter type found: ${type}`); winston.warn(`[flags/list] No flag filter type found: ${type}`);
} }
} }
}
sets = (sets.length || orSets.length) ? sets : ['flags:datetime']; // No filter default sets = (sets.length || orSets.length) ? sets : ['flags:datetime']; // No filter default
let flagIds = []; let flagIds = [];
@ -586,8 +584,7 @@ Flags.update = async function (flagId, uid, changeset) {
// Retrieve existing flag data to compare for history-saving/reference purposes // Retrieve existing flag data to compare for history-saving/reference purposes
const tasks = []; const tasks = [];
for (const prop in changeset) { for (const prop of Object.keys(changeset)) {
if (changeset.hasOwnProperty(prop)) {
if (current[prop] === changeset[prop]) { if (current[prop] === changeset[prop]) {
delete changeset[prop]; delete changeset[prop];
} else if (prop === 'state') { } else if (prop === 'state') {
@ -610,7 +607,6 @@ Flags.update = async function (flagId, uid, changeset) {
} }
} }
} }
}
if (!Object.keys(changeset).length) { if (!Object.keys(changeset).length) {
return; return;

@ -150,12 +150,7 @@ async function setupConfig() {
async function completeConfigSetup(config) { async function completeConfigSetup(config) {
// Add CI object // Add CI object
if (install.ciVals) { if (install.ciVals) {
config.test_database = {}; config.test_database = { ...install.ciVals };
for (const prop in install.ciVals) {
if (install.ciVals.hasOwnProperty(prop)) {
config.test_database[prop] = install.ciVals[prop];
}
}
} }
// Add package_manager object if set // Add package_manager object if set

@ -47,14 +47,12 @@ Settings.set = async function (hash, values, quiet) {
({ plugin: hash, settings: values, quiet } = await plugins.hooks.fire('filter:settings.set', { plugin: hash, settings: values, quiet })); ({ plugin: hash, settings: values, quiet } = await plugins.hooks.fire('filter:settings.set', { plugin: hash, settings: values, quiet }));
const sortedListData = {}; const sortedListData = {};
for (const key in values) { for (const [key, value] of Object.entries(values)) {
if (values.hasOwnProperty(key)) { if (Array.isArray(value) && typeof value[0] !== 'string') {
if (Array.isArray(values[key]) && typeof values[key][0] !== 'string') { sortedListData[key] = value;
sortedListData[key] = values[key];
delete values[key]; delete values[key];
} }
} }
}
const sortedLists = Object.keys(sortedListData); const sortedLists = Object.keys(sortedListData);
if (sortedLists.length) { if (sortedLists.length) {

@ -64,9 +64,9 @@ module.exports = function (middleware) {
headers['X-Upstream-Hostname'] = os.hostname(); headers['X-Upstream-Hostname'] = os.hostname();
} }
for (const key in headers) { for (const [key, value] of Object.entries(headers)) {
if (headers.hasOwnProperty(key) && headers[key]) { if (value) {
res.setHeader(key, headers[key]); res.setHeader(key, value);
} }
} }

@ -241,13 +241,7 @@ Plugins.normalise = async function (apiReturn) {
pluginMap[plugin.id].outdated = semver.gt(pluginMap[plugin.id].latest, pluginMap[plugin.id].version); pluginMap[plugin.id].outdated = semver.gt(pluginMap[plugin.id].latest, pluginMap[plugin.id].version);
}); });
const pluginArray = []; const pluginArray = Object.values(pluginMap);
for (const key in pluginMap) {
if (pluginMap.hasOwnProperty(key)) {
pluginArray.push(pluginMap[key]);
}
}
pluginArray.sort((a, b) => { pluginArray.sort((a, b) => {
if (a.name > b.name) { if (a.name > b.name) {

@ -4,17 +4,11 @@ const meta = require('./meta');
const pubsub = require('./pubsub'); const pubsub = require('./pubsub');
function expandObjBy(obj1, obj2) { function expandObjBy(obj1, obj2) {
let key;
let val1;
let val2;
let xorValIsArray;
let changed = false; let changed = false;
for (key in obj2) { for (const [key, val2] of Object.entries(obj2)) {
if (obj2.hasOwnProperty(key)) { const val1 = obj1[key];
val2 = obj2[key]; const xorIsArray = Array.isArray(val1) === Array.isArray(val2);
val1 = obj1[key]; if (xorIsArray || !obj1.hasOwnProperty(key) || typeof val2 !== typeof val1) {
xorValIsArray = Array.isArray(val1) === Array.isArray(val2);
if (xorValIsArray || !obj1.hasOwnProperty(key) || typeof val2 !== typeof val1) {
obj1[key] = val2; obj1[key] = val2;
changed = true; changed = true;
} else if (typeof val2 === 'object' && !Array.isArray(val2)) { } else if (typeof val2 === 'object' && !Array.isArray(val2)) {
@ -23,16 +17,11 @@ function expandObjBy(obj1, obj2) {
} }
} }
} }
}
return changed; return changed;
} }
function trim(obj1, obj2) { function trim(obj1, obj2) {
let key; for (const [key, val1] of Object.entries(obj1)) {
let val1;
for (key in obj1) {
if (obj1.hasOwnProperty(key)) {
val1 = obj1[key];
if (!obj2.hasOwnProperty(key)) { if (!obj2.hasOwnProperty(key)) {
delete obj1[key]; delete obj1[key];
} else if (typeof val1 === 'object' && !Array.isArray(val1)) { } else if (typeof val1 === 'object' && !Array.isArray(val1)) {
@ -40,7 +29,6 @@ function trim(obj1, obj2) {
} }
} }
} }
}
function mergeSettings(cfg, defCfg) { function mergeSettings(cfg, defCfg) {
if (typeof defCfg !== 'object') { if (typeof defCfg !== 'object') {

@ -32,16 +32,11 @@ Config.setMultiple = async function (socket, data) {
} }
}); });
await meta.configs.setMultiple(data); await meta.configs.setMultiple(data);
for (const field in data) { for (const [key, value] of Object.entries(data)) {
if (data.hasOwnProperty(field)) { const setting = { key, value };
const setting = {
key: field,
value: data[field],
};
plugins.hooks.fire('action:config.set', setting); plugins.hooks.fire('action:config.set', setting);
logger.monitorConfig({ io: index.server }, setting); logger.monitorConfig({ io: index.server }, setting);
} }
}
if (Object.keys(changes).length) { if (Object.keys(changes).length) {
changes.type = 'config-change'; changes.type = 'config-change';
changes.uid = socket.uid; changes.uid = socket.uid;

@ -64,23 +64,21 @@ SocketRooms.getAll = async function () {
category: 0, category: 0,
}; };
for (const instance in stats) { for (const instance of Object.values(stats)) {
if (stats.hasOwnProperty(instance)) { totals.onlineGuestCount += instance.onlineGuestCount;
totals.onlineGuestCount += stats[instance].onlineGuestCount; totals.onlineRegisteredCount += instance.onlineRegisteredCount;
totals.onlineRegisteredCount += stats[instance].onlineRegisteredCount; totals.socketCount += instance.socketCount;
totals.socketCount += stats[instance].socketCount; totals.users.categories += instance.users.categories;
totals.users.categories += stats[instance].users.categories; totals.users.recent += instance.users.recent;
totals.users.recent += stats[instance].users.recent; totals.users.unread += instance.users.unread;
totals.users.unread += stats[instance].users.unread; totals.users.topics += instance.users.topics;
totals.users.topics += stats[instance].users.topics; totals.users.category += instance.users.category;
totals.users.category += stats[instance].users.category;
instance.topics.forEach((topic) => {
stats[instance].topics.forEach((topic) => {
totals.topics[topic.tid] = totals.topics[topic.tid] || { count: 0, tid: topic.tid }; totals.topics[topic.tid] = totals.topics[topic.tid] || { count: 0, tid: topic.tid };
totals.topics[topic.tid].count += topic.count; totals.topics[topic.tid].count += topic.count;
}); });
} }
}
let topTenTopics = []; let topTenTopics = [];
Object.keys(totals.topics).forEach((tid) => { Object.keys(totals.topics).forEach((tid) => {

@ -285,10 +285,8 @@ module.exports = function (User) {
User.setUserFields = async function (uid, data) { User.setUserFields = async function (uid, data) {
await db.setObject(`user:${uid}`, data); await db.setObject(`user:${uid}`, data);
for (const field in data) { for (const [field, value] of Object.entries(data)) {
if (data.hasOwnProperty(field)) { plugins.hooks.fire('action:user.set', { uid, field, value, type: 'set' });
plugins.hooks.fire('action:user.set', { uid: uid, field: field, value: data[field], type: 'set' });
}
} }
}; };

@ -46,14 +46,12 @@ module.exports = function (User) {
User.stopJobs = function () { User.stopJobs = function () {
let terminated = 0; let terminated = 0;
// Terminate any active cron jobs // Terminate any active cron jobs
for (const jobId in jobs) { for (const jobId of Object.keys(jobs)) {
if (jobs.hasOwnProperty(jobId)) {
winston.verbose(`[user/jobs] Terminating job (${jobId})`); winston.verbose(`[user/jobs] Terminating job (${jobId})`);
jobs[jobId].stop(); jobs[jobId].stop();
delete jobs[jobId]; delete jobs[jobId];
terminated += 1; terminated += 1;
} }
}
if (terminated > 0) { if (terminated > 0) {
winston.verbose(`[user/jobs] ${terminated} jobs terminated`); winston.verbose(`[user/jobs] ${terminated} jobs terminated`);
} }

@ -131,8 +131,8 @@ UserReset.cleanByUid = async function (uid) {
await batch.processSortedSet('reset:issueDate', async (tokens) => { await batch.processSortedSet('reset:issueDate', async (tokens) => {
const results = await db.getObjectFields('reset:uid', tokens); const results = await db.getObjectFields('reset:uid', tokens);
for (const code in results) { for (const [code, result] of Object.entries(results)) {
if (results.hasOwnProperty(code) && parseInt(results[code], 10) === uid) { if (parseInt(result, 10) === uid) {
tokensToClean.push(code); tokensToClean.push(code);
} }
} }

@ -70,10 +70,8 @@ server.on('connection', (conn) => {
exports.destroy = function (callback) { exports.destroy = function (callback) {
server.close(callback); server.close(callback);
for (const key in connections) { for (const connection of Object.values(connections)) {
if (connections.hasOwnProperty(key)) { connection.destroy();
connections[key].destroy();
}
} }
}; };

@ -196,13 +196,8 @@ widgets.reset = async function () {
}; };
widgets.resetTemplate = async function (template) { widgets.resetTemplate = async function (template) {
let toBeDrafted = [];
const area = await db.getObject(`widgets:${template}.tpl`); const area = await db.getObject(`widgets:${template}.tpl`);
for (const location in area) { const toBeDrafted = _.flatMap(Object.values(area), value => JSON.parse(value));
if (area.hasOwnProperty(location)) {
toBeDrafted = toBeDrafted.concat(JSON.parse(area[location]));
}
}
await db.delete(`widgets:${template}.tpl`); await db.delete(`widgets:${template}.tpl`);
let draftWidgets = await db.getObjectField('widgets:global', 'drafts'); let draftWidgets = await db.getObjectField('widgets:global', 'drafts');
draftWidgets = JSON.parse(draftWidgets).concat(toBeDrafted); draftWidgets = JSON.parse(draftWidgets).concat(toBeDrafted);

@ -420,12 +420,10 @@ describe('API', async () => {
return memo; return memo;
}, {}); }, {});
for (const header in expectedHeaders) { for (const header of Object.keys(expectedHeaders)) {
if (expectedHeaders.hasOwnProperty(header)) {
assert(response.headers[header.toLowerCase()]); assert(response.headers[header.toLowerCase()]);
assert.strictEqual(response.headers[header.toLowerCase()], expectedHeaders[header]); assert.strictEqual(response.headers[header.toLowerCase()], expectedHeaders[header]);
} }
}
return; return;
} }

@ -55,12 +55,10 @@ describe('Flags', () => {
target_readable: 'Post 1', target_readable: 'Post 1',
}; };
assert(flagData); assert(flagData);
for (const key in compare) { for (const key of Object.keys(compare)) {
if (compare.hasOwnProperty(key)) {
assert.ok(flagData[key], `undefined key ${key}`); assert.ok(flagData[key], `undefined key ${key}`);
assert.equal(flagData[key], compare[key]); assert.equal(flagData[key], compare[key]);
} }
}
done(); done();
}); });
@ -131,12 +129,10 @@ describe('Flags', () => {
target_readable: 'Post 1', target_readable: 'Post 1',
}; };
assert(flagData); assert(flagData);
for (const key in compare) { for (const key of Object.keys(compare)) {
if (compare.hasOwnProperty(key)) {
assert.ok(flagData[key], `undefined key ${key}`); assert.ok(flagData[key], `undefined key ${key}`);
assert.equal(flagData[key], compare[key]); assert.equal(flagData[key], compare[key]);
} }
}
done(); done();
}); });
@ -483,12 +479,10 @@ describe('Flags', () => {
content: 'This is flaggable content', content: 'This is flaggable content',
}; };
for (const key in compare) { for (const key of Object.keys(compare)) {
if (compare.hasOwnProperty(key)) {
assert.ok(data[key]); assert.ok(data[key]);
assert.equal(data[key], compare[key]); assert.equal(data[key], compare[key]);
} }
}
done(); done();
}); });
@ -503,12 +497,10 @@ describe('Flags', () => {
email: 'b@c.com', email: 'b@c.com',
}; };
for (const key in compare) { for (const key of Object.keys(compare)) {
if (compare.hasOwnProperty(key)) {
assert.ok(data[key]); assert.ok(data[key]);
assert.equal(data[key], compare[key]); assert.equal(data[key], compare[key]);
} }
}
done(); done();
}); });
@ -644,12 +636,10 @@ describe('Flags', () => {
}; };
const data = notes[1]; const data = notes[1];
for (const key in compare) { for (const key of Object.keys(compare)) {
if (compare.hasOwnProperty(key)) {
assert.ok(data[key]); assert.ok(data[key]);
assert.strictEqual(data[key], compare[key]); assert.strictEqual(data[key], compare[key]);
} }
}
done(); done();
}); });

Loading…
Cancel
Save