eslint: enable extra rules

no-implicit-coercion, no-extra-boolean-cast, no-invalid-this, logical-assignment-operators, no-unmodified-loop-condition
This commit is contained in:
undefined committed 2023-01-06 00:28:35 +08:00
1 parent 5ac9d930b2
commit 7f51df236a
34 files changed
+100 -96

No files matched your search

+1 -1
View File
@@ -546,7 +546,7 @@ export class ContestManagementHandler extends ContestManagementBaseHandler {
if (size >= system.get('limit.contest_files_size')) {
throw new FileLimitExceededError('size');
}
if (!filename) filename = file.originalFilename || String.random(16);
filename ||= file.originalFilename || String.random(16);
if (filename.includes('/') || filename.includes('..')) throw new ValidationError('filename', null, 'Bad filename');
await storage.put(`contest/${domainId}/${tid}/${filename}`, file.filepath, this.user._id);
const meta = await storage.getMeta(`contest/${domainId}/${tid}/${filename}`);
+2 -2
View File
@@ -65,8 +65,8 @@ class DiscussionHandler extends Handler {
}
}
if (this.ddoc) {
this.ddoc.parentType = this.ddoc.parentType || this.vnode.type;
this.ddoc.parentId = this.ddoc.parentId || this.vnode.id;
this.ddoc.parentType ||= this.vnode.type;
this.ddoc.parentId ||= this.vnode.id;
}
}
}
+5 -7
View File
@@ -375,13 +375,11 @@ class HomeMessagesHandler extends Handler {
const parsed = {};
for (const m of messages) {
const target = m.from === this.user._id ? m.to : m.from;
if (!parsed[target]) {
parsed[target] = {
_id: target,
udoc: { ...udict[target], avatarUrl: avatar(udict[target].avatar) },
messages: [],
};
}
parsed[target] ||= {
_id: target,
udoc: { ...udict[target], avatarUrl: avatar(udict[target].avatar) },
messages: [],
};
parsed[target].messages.push(m);
}
await user.setById(this.user._id, { unreadMsg: 0 });
+1 -1
View File
@@ -115,7 +115,7 @@ export async function postJudge(rdoc: RecordDoc) {
}
export async function end(body: Partial<JudgeResultBody>) {
if (body.rid) body.rid = new ObjectID(body.rid);
body.rid &&= new ObjectID(body.rid);
let rdoc = await record.get(body.rid);
if (!rdoc) return;
const $set: Partial<RecordDoc> = {};
+1 -1
View File
@@ -242,7 +242,7 @@ class SystemUserImportHandler extends SystemHandler {
try {
const data = JSON.parse(extra);
if (data.group) {
if (!groups[data.group]) groups[data.group] = [];
groups[data.group] ||= [];
groups[data.group].push(email);
}
if (data.school) payload.school = data.school;
+1 -1
View File
@@ -57,7 +57,7 @@ export class FilesHandler extends Handler {
if (size >= system.get('limit.user_files_size')) {
if (!this.user.hasPriv(PRIV.PRIV_UNLIMITED_QUOTA)) throw new FileLimitExceededError('size');
}
if (!filename) filename = file.originalFilename || String.random(16);
filename ||= file.originalFilename || String.random(16);
if (filename.includes('/') || filename.includes('..')) throw new ValidationError('filename', null, 'Bad filename');
if (this.user._files.filter((i) => i.name === filename).length) throw new FileExistsError(filename);
await storage.put(`user/${this.user._id}/${filename}`, file.filepath, this.user._id);
+2 -2
View File
@@ -161,7 +161,7 @@ export class ProblemMainHandler extends Handler {
total = result.total;
pcountRelation = result.countRelation;
if (!result.hits.length) fail = true;
if (!query.$and) query.$and = [];
query.$and ||= [];
query.$and.push({
$or: result.hits.map((i) => {
const [did, docId] = i.split('/');
@@ -723,7 +723,7 @@ export class ProblemFilesHandler extends ProblemDetailHandler {
async postUploadFile(domainId: string, filename: string, type = 'testdata') {
if (this.pdoc.reference) throw new ProblemIsReferencedError('edit files');
if (!this.request.files.file) throw new ValidationError('file');
if (!filename) filename = this.request.files.file.originalFilename || String.random(16);
filename ||= this.request.files.file.originalFilename || String.random(16);
if (filename.includes('/') || filename.includes('..')) throw new ValidationError('filename', null, 'Bad filename');
if (!this.user.own(this.pdoc, PERM.PERM_EDIT_PROBLEM_SELF)) this.checkPerm(PERM.PERM_EDIT_PROBLEM);
const files = [];
+1 -1
View File
@@ -15,7 +15,7 @@ async function getStatus() {
let desc = '';
const online = new Date(stat.updateAt).getTime() > new Date().getTime() - 300000;
if (!online) desc = 'Offline';
desc = desc || 'Online';
desc ||= 'Online';
stat.isOnline = online;
stat.status = desc;
}
+1 -1
View File
@@ -268,7 +268,7 @@ export class TrainingFilesHandler extends Handler {
if (size >= system.get('limit.contest_files_size')) {
throw new FileLimitExceededError('size');
}
if (!filename) filename = file.originalFilename || String.random(16);
filename ||= file.originalFilename || String.random(16);
if (filename.includes('/') || filename.includes('..')) throw new ValidationError('filename', null, 'Bad filename');
await storage.put(`training/${domainId}/${tid}/${filename}`, file.filepath, this.user._id);
const meta = await storage.getMeta(`training/${domainId}/${tid}/${filename}`);
+2 -2
View File
@@ -119,7 +119,7 @@ class UserLoginHandler extends Handler {
async post(domainId: string, uname: string, password: string, rememberme = false, redirect = '', tfa = '') {
if (!system.get('server.login')) throw new BuiltinLoginError();
let udoc = await user.getByEmail(domainId, uname);
if (!udoc) udoc = await user.getByUname(domainId, uname);
udoc ||= await user.getByUname(domainId, uname);
if (!udoc) throw new UserNotFoundError(uname);
await Promise.all([
this.limitRate('user_login', 60, 30, false),
@@ -425,7 +425,7 @@ class OauthCallbackHandler extends Handler {
}
this.checkPriv(PRIV.PRIV_REGISTER_USER);
let username = '';
r.uname = r.uname || [];
r.uname ||= [];
r.uname.push(String.random(16));
const mailDomain = r.email.split('@')[1];
if (await BlackListModel.get(`mail::${mailDomain}`)) throw new BlacklistedError(mailDomain);
+1 -1
View File
@@ -18,7 +18,7 @@ if (!global.Hydro) {
lib: {},
module: new Proxy({} as any, {
get(self, key) {
if (!self[key]) self[key] = {};
self[key] ||= {};
return self[key];
},
}),
+1 -1
View File
@@ -11,7 +11,7 @@ export const providers: Record<string, AvatarProvider> = {
};
function avatar(src: string, size = 64, fallback = '') {
src = src || fallback;
src ||= fallback;
let index = src.indexOf(':');
if (index === -1) src = fallback;
index = src.indexOf(':');
+1 -1
View File
@@ -19,7 +19,7 @@ class I18nService extends Service {
}
load(lang: string, content: Record<string, string>) {
if (!translations[lang]) translations[lang] = [];
translations[lang] ||= [];
translations[lang].unshift(content);
this.caller?.on('dispose', () => {
translations[lang] = translations[lang].filter((i) => i !== content);
+1 -1
View File
@@ -26,7 +26,7 @@ const buildChecker = (...permPrivChecker: PermPrivChecker) => {
export const nodes = new Proxy({}, {
get(self, key) {
if (!self[key]) self[key] = [];
self[key] ||= [];
return self[key];
},
});
+15 -16
View File
@@ -35,18 +35,17 @@ interface AcmDetail extends AcmJournal {
function buildContestRule<T>(def: ContestRule<T>): ContestRule<T>;
function buildContestRule<T>(def: Partial<ContestRule<T>>, baseRule: ContestRule<T>): ContestRule<T>;
function buildContestRule<T>(def: Partial<ContestRule<T>>, { _originalRule: base }: ContestRule<T> = { _originalRule: {} } as any) {
def._originalRule = {
scoreboard: def.scoreboard || base.scoreboard,
scoreboardRow: def.scoreboardRow || base.scoreboardRow,
scoreboardHeader: def.scoreboardHeader || base.scoreboardHeader,
stat: def.stat || base.stat,
};
def.scoreboard = (def.scoreboard || base.scoreboard).bind(def);
def.scoreboardHeader = (def.scoreboardHeader || base.scoreboardHeader).bind(def);
def.scoreboardRow = (def.scoreboardRow || base.scoreboardRow).bind(def);
def.stat = (def.stat || base.stat).bind(def);
return def as ContestRule<T>;
function buildContestRule<T>(def: Partial<ContestRule<T>>, baseRule: ContestRule<T> = {} as any) {
const base = baseRule._originalRule || {};
const funcs = ['scoreboard', 'scoreboardRow', 'scoreboardHeader', 'stat'];
const f = {};
const rule = { ...baseRule, ...def };
for (const key of funcs) {
f[key] = def[key] || base[key];
rule[key] = f[key].bind(rule);
}
rule._originalRule = f;
return rule;
}
const acm = buildContestRule({
@@ -708,24 +707,24 @@ export async function unlockScoreboard(domainId: string, tid: ObjectID) {
await edit(domainId, tid, { unlocked: true });
}
export function canViewHiddenScoreboard(tdoc: Tdoc<30>) {
export function canViewHiddenScoreboard(this: Handler, tdoc: Tdoc<30>) {
if (tdoc.rule === 'homework') return this.user.hasPerm(PERM.PERM_VIEW_HOMEWORK_HIDDEN_SCOREBOARD);
return this.user.hasPerm(PERM.PERM_VIEW_CONTEST_HIDDEN_SCOREBOARD);
}
export function canShowRecord(tdoc: Tdoc<30>, allowPermOverride = true) {
export function canShowRecord(this: Handler, tdoc: Tdoc<30>, allowPermOverride = true) {
if (RULES[tdoc.rule].showRecord(tdoc, new Date())) return true;
if (allowPermOverride && canViewHiddenScoreboard.call(this, tdoc)) return true;
return false;
}
export function canShowSelfRecord(tdoc: Tdoc<30>, allowPermOverride = true) {
export function canShowSelfRecord(this: Handler, tdoc: Tdoc<30>, allowPermOverride = true) {
if (RULES[tdoc.rule].showSelfRecord(tdoc, new Date())) return true;
if (allowPermOverride && canViewHiddenScoreboard.call(this, tdoc)) return true;
return false;
}
export function canShowScoreboard(tdoc: Tdoc<30>, allowPermOverride = true) {
export function canShowScoreboard(this: Handler, tdoc: Tdoc<30>, allowPermOverride = true) {
if (RULES[tdoc.rule].showScoreboard(tdoc, new Date())) return true;
if (allowPermOverride && canViewHiddenScoreboard.call(this, tdoc)) return true;
return false;
+1 -1
View File
@@ -305,7 +305,7 @@ export async function getListVnodes(domainId: string, ddocs: any, getHidden = fa
const res = {};
async function task(ddoc: DiscussionDoc) {
const vnode = await getVnode(domainId, ddoc.parentType, ddoc.parentId.toString());
if (!res[ddoc.parentType]) res[ddoc.parentType] = {};
res[ddoc.parentType] ||= {};
if (!getHidden && vnode.hidden) return;
if (vnode.assign?.length && Set.intersection(vnode.assign, assign).size) return;
res[ddoc.parentType][ddoc.parentId] = vnode;
+2 -2
View File
@@ -178,10 +178,10 @@ class DomainModel {
static async getDomainUser(domainId: string, udoc: DomainUserArg) {
let dudoc = await collUser.findOne({ domainId, uid: udoc._id });
dudoc = dudoc || {};
dudoc ||= {};
if (!(udoc.priv & PRIV.PRIV_USER_PROFILE)) dudoc.role = 'guest';
if (udoc.priv & PRIV.PRIV_MANAGE_ALL_DOMAIN) dudoc.role = 'root';
dudoc.role = dudoc.role || 'default';
dudoc.role ||= 'default';
const ddoc = await DomainModel.get(domainId);
dudoc.perm = ddoc?.roles[dudoc.role]
? BigInt(ddoc?.roles[dudoc.role])
+1 -1
View File
@@ -13,7 +13,7 @@ const coll = db.collection('schedule');
async function getFirst(query: FilterQuery<Schedule>) {
if (process.env.CI) return null;
const q = { ...query };
q.executeAfter = q.executeAfter || { $lt: new Date() };
q.executeAfter ||= { $lt: new Date() };
const res = await coll.findOneAndDelete(q);
if (res.value) {
logger.debug('%o', res.value);
+1 -1
View File
@@ -209,7 +209,7 @@ class UserModel {
const unameLower = uname.trim().toLowerCase();
if (cache.has(`name/${unameLower}/${domainId}`)) return cache.get(`name/${unameLower}/${domainId}`) || null;
let udoc = await coll.findOne({ unameLower });
if (!udoc) udoc = await collV.findOne({ unameLower });
udoc ||= await collV.findOne({ unameLower });
if (!udoc) return null;
const dudoc = await domain.getDomainUser(domainId, udoc);
const res = await new UserModel.User(udoc, dudoc).init();
+1 -1
View File
@@ -111,7 +111,7 @@ export async function calcLevel(domainId: string, report: Function) {
let bulk = coll.initializeUnorderedBulkOp();
for await (const dudoc of ducur) {
count++;
if (!dudoc.rp) dudoc.rp = null;
dudoc.rp ||= null;
if (dudoc.rp !== last.rp) rank = count;
bulk.find({ _id: dudoc._id }).updateOne({ $set: { rank } });
last = dudoc;
+2 -2
View File
@@ -166,8 +166,8 @@ function _buildParam(name: string, source: 'get' | 'post' | 'all' | 'route', ...
function _descriptor(v: ParamOption) {
return function desc(this: Handler, target: any, funcName: string, obj: any) {
if (!target.__param) target.__param = {};
if (!target.__param[target.constructor.name]) target.__param[target.constructor.name] = {};
target.__param ||= {};
target.__param[target.constructor.name] ||= {};
if (!target.__param[target.constructor.name][funcName]) {
target.__param[target.constructor.name][funcName] = [{ name: 'domainId', type: 'string', source: 'route' }];
const originalMethod = obj.value;
+1 -1
View File
@@ -194,7 +194,7 @@ export class Handler extends HandlerCommon {
}
async onerror(error: HydroError) {
if (!error.msg) error.msg = () => error.message;
error.msg ||= () => error.message;
if (error instanceof UserFacingError && !process.env.DEV) error.stack = '';
if (!(error instanceof NotFoundError)) {
// eslint-disable-next-line max-len
+1 -1
View File
@@ -71,7 +71,7 @@ export async function setConfig(key: string, value: any) {
const t = path.pop();
let cursor = systemConfig;
for (const p of path) {
if (!cursor[p]) cursor[p] = {};
cursor[p] ||= {};
cursor = cursor[p];
}
cursor[t] = value;