Skip to content

Commit

Permalink
Adding Some ESLint rules
Browse files Browse the repository at this point in the history
  • Loading branch information
bhavik001 committed Dec 11, 2023
1 parent 8da693d commit db99344
Show file tree
Hide file tree
Showing 8 changed files with 97 additions and 34 deletions.
3 changes: 3 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,5 +25,8 @@ module.exports = {
rules: {
"no-prototype-builtins": "off",
"no-unused-vars": ["error", { argsIgnorePattern: "^_" }],
semi: ["error", "always"],
"no-cond-assign": ["error", "always"],
curly: "error",
},
};
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@
"test": "nightwatch tests && nightwatch tests --env jwt",
"prettier": "prettier . --write",
"prettier-check": "prettier . --check",
"lint": "eslint --config .eslintrc.js \"./server/*.js\" \"tests/*.js\""
"lint": "eslint --config .eslintrc.js \"./server/*.js\" \"tests/*.js\"",
"lint-fix": "eslint --config .eslintrc.js \"./server/*.js\" \"tests/*.js\" --fix"
},
"main": "./server/server.js",
"repository": {
Expand Down
57 changes: 42 additions & 15 deletions server/boardData.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,9 +72,14 @@ class BoardData {
*/
addChild(parentId, child) {
var obj = this.board[parentId];
if (typeof obj !== "object") return false;
if (Array.isArray(obj._children)) obj._children.push(child);
else obj._children = [child];
if (typeof obj !== "object") {
return false;
}
if (Array.isArray(obj._children)) {
obj._children.push(child);
} else {
obj._children = [child];
}

this.validate(obj);
this.delaySave();
Expand Down Expand Up @@ -158,17 +163,25 @@ class BoardData {
* @param {BoardMessage} message instruction to apply to the board
*/
processMessage(message) {
if (message._children) return this.processMessageBatch(message._children);
if (message._children) {
return this.processMessageBatch(message._children);
}
let id = message.id;
switch (message.type) {
case "delete":
if (id) this.delete(id);
if (id) {
this.delete(id);
}
break;
case "update":
if (id) this.update(id, message);
if (id) {
this.update(id, message);
}
break;
case "copy":
if (id) this.copy(id, message);
if (id) {
this.copy(id, message);
}
break;
case "child":
this.addChild(message.parent, message);
Expand All @@ -182,7 +195,9 @@ class BoardData {
break;
default:
//Add data
if (!id) throw new Error("Invalid message: ", message);
if (!id) {
throw new Error("Invalid message: ", message);
}
this.set(id, message);
}
}
Expand All @@ -207,10 +222,13 @@ class BoardData {

/** Delays the triggering of auto-save by SAVE_INTERVAL seconds */
delaySave() {
if (this.saveTimeoutId !== undefined) clearTimeout(this.saveTimeoutId);
if (this.saveTimeoutId !== undefined) {
clearTimeout(this.saveTimeoutId);
}
this.saveTimeoutId = setTimeout(this.save.bind(this), config.SAVE_INTERVAL);
if (Date.now() - this.lastSaveDate > config.MAX_SAVE_DELAY)
if (Date.now() - this.lastSaveDate > config.MAX_SAVE_DELAY) {
setTimeout(this.save.bind(this), 0);
}
}

/** Saves the data in the board to a file. */
Expand Down Expand Up @@ -267,7 +285,9 @@ class BoardData {
return (board[x].time | 0) - (board[y].time | 0);
})
.slice(0, -config.MAX_ITEM_COUNT);
for (var i = 0; i < toDestroy.length; i++) delete board[toDestroy[i]];
for (var i = 0; i < toDestroy.length; i++) {
delete board[toDestroy[i]];
}
log("cleaned board", { removed: toDestroy.length, board: this.name });
}
}
Expand All @@ -290,12 +310,17 @@ class BoardData {
}
if (item.hasOwnProperty("opacity")) {
item.opacity = Math.min(Math.max(item.opacity, 0.1), 1) || 1;
if (item.opacity === 1) delete item.opacity;
if (item.opacity === 1) {
delete item.opacity;
}
}
if (item.hasOwnProperty("_children")) {
if (!Array.isArray(item._children)) item._children = [];
if (item._children.length > config.MAX_CHILDREN)
if (!Array.isArray(item._children)) {
item._children = [];
}
if (item._children.length > config.MAX_CHILDREN) {
item._children.length = config.MAX_CHILDREN;
}
for (var i = 0; i < item._children.length; i++) {
this.validate(item._children[i]);
}
Expand All @@ -311,7 +336,9 @@ class BoardData {
try {
data = await fs.promises.readFile(boardData.file);
boardData.board = JSON.parse(data);
for (const id in boardData.board) boardData.validate(boardData.board[id]);
for (const id in boardData.board) {
boardData.validate(boardData.board[id]);
}
log("disk load", { board: boardData.name });
} catch (e) {
// If the file doesn't exist, this is not an error
Expand Down
3 changes: 2 additions & 1 deletion server/check_output_directory.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,9 @@ async function get_error(directory) {
for (const elem of files) {
if (/^board-(.*)\.json$/.test(elem.name)) {
const elemPath = path.join(directory, elem.name);
if (!elem.isFile())
if (!elem.isFile()) {
return `contains a board file named "${elemPath}" which is not a normal file`;
}
fileChecks.push(
fs.promises.access(elemPath, R_OK | W_OK).catch(function () {
return elemPath;
Expand Down
19 changes: 14 additions & 5 deletions server/createSVG.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ const fs = require("./fs_promises.js"),
require("../client-data/tools/pencil/wbo_pencil_point.js").wboPencilPoint;

function htmlspecialchars(str) {
if (typeof str !== "string") return "";
if (typeof str !== "string") {
return "";
}

return str.replace(/[<>&"']/g, function (c) {
switch (c) {
Expand Down Expand Up @@ -81,7 +83,9 @@ const Tools = {
* @return {string}
*/
Pencil: function (el) {
if (!el._children) return "";
if (!el._children) {
return "";
}
let pts = el._children.reduce(function (pts, point) {
return wboPencilPoint(pts, point.x, point.y);
}, []);
Expand Down Expand Up @@ -175,7 +179,9 @@ async function toSVG(obj, writeable) {
const elems = Object.values(obj);
const dim = elems.reduce(
function (dim, elem) {
if (elem._children && elem._children.length) elem = elem._children[0];
if (elem._children && elem._children.length) {
elem = elem._children[0];
}
return [
Math.max((elem.x + margin + (elem.deltax | 0)) | 0, dim[0]),
Math.max((elem.y + margin + (elem.deltay | 0)) | 0, dim[1]),
Expand All @@ -200,8 +206,11 @@ async function toSVG(obj, writeable) {
elems.map(async function (elem) {
await Promise.resolve(); // Do not block the event loop
const renderFun = Tools[elem.tool];
if (renderFun) writeable.write(renderFun(elem));
else console.warn("Missing render function for tool", elem.tool);
if (renderFun) {
writeable.write(renderFun(elem));
} else {
console.warn("Missing render function for tool", elem.tool);
}
}),
);
writeable.write("</svg>");
Expand Down
15 changes: 11 additions & 4 deletions server/log.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,9 @@ const config = require("./configuration.js"),
function parse_statsd_url(url) {
const regex = /^(tcp|udp|statsd):\/\/(.*):(\d+)$/;
const match = url.match(regex);
if (!match)
if (!match) {
throw new Error("Invalid statsd connection string, doesn't match " + regex);
}
// eslint-disable-next-line no-unused-vars
const [_, protocol, host, port_str] = match;
const tcp = protocol === "tcp";
Expand Down Expand Up @@ -43,10 +44,14 @@ if (statsd) {
*/
function log(type, infos) {
var msg = type;
if (infos) msg += "\t" + JSON.stringify(infos);
if (infos) {
msg += "\t" + JSON.stringify(infos);
}
if (statsd) {
let stat_name = type;
if (infos.board) stat_name += "." + infos.board;
if (infos.board) {
stat_name += "." + infos.board;
}
statsd.increment(stat_name);
}
console.log(msg);
Expand Down Expand Up @@ -84,7 +89,9 @@ function monitorFunction(f) {
* @param {{[name:string]: string}=} tags
*/
function gauge(name, value, tags) {
if (statsd) statsd.gauge(name, value, tags);
if (statsd) {
statsd.gauge(name, value, tags);
}
}

module.exports = { log, gauge, monitorFunction };
16 changes: 12 additions & 4 deletions server/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,9 @@ const indexTemplate = new templating.Template(
* @throws {Error}
*/
function validateBoardName(boardName) {
if (/^[\w%\-_~()]*$/.test(boardName)) return boardName;
if (/^[\w%\-_~()]*$/.test(boardName)) {
return boardName;
}
throw new Error("Illegal board name: " + boardName);
}

Expand All @@ -105,7 +107,9 @@ function handleRequest(request, response) {
var parsedUrl = new URL(request.url, "http://wbo/");
var parts = parsedUrl.pathname.split("/");

if (parts[0] === "") parts.shift();
if (parts[0] === "") {
parts.shift();
}

var fileExt = path.extname(parsedUrl.pathname);
var staticResources = [".js", ".css", ".svg", ".ico", ".png", ".jpg", "gif"];
Expand Down Expand Up @@ -149,7 +153,9 @@ function handleRequest(request, response) {
}
log("download", { file: history_file });
fs.readFile(history_file, function (err, data) {
if (err) return serveError(request, response)(err);
if (err) {
return serveError(request, response)(err);
}
response.writeHead(200, {
"Content-Type": "application/json",
"Content-Disposition": 'attachment; filename="' + boardName + '.wbo"',
Expand Down Expand Up @@ -229,7 +235,9 @@ function handleRequest(request, response) {
Location: "boards/" + encodeURIComponent(config.DEFAULT_BOARD),
});
response.end(name);
} else indexTemplate.serve(request, response);
} else {
indexTemplate.serve(request, response);
}
break;

default:
Expand Down
15 changes: 11 additions & 4 deletions server/sockets.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,9 @@ function startIO(app) {
config.AUTH_SECRET_KEY,
// function (err, decoded) {
function (err) {
if (err)
if (err) {
return next(new Error("Authentication error: Invalid JWT"));
}
next();
},
);
Expand Down Expand Up @@ -78,7 +79,9 @@ function handleSocketConnection(socket) {
*/
async function joinBoard(name) {
// Default to the public board
if (!name) name = "anonymous";
if (!name) {
name = "anonymous";
}

// Join the board
socket.join(name);
Expand Down Expand Up @@ -134,7 +137,9 @@ function handleSocketConnection(socket) {
var boardName = message.board || "anonymous";
var data = message.data;

if (!socket.rooms.has(boardName)) socket.join(boardName);
if (!socket.rooms.has(boardName)) {
socket.join(boardName);
}

if (!data) {
console.warn("Received invalid message: %s.", JSON.stringify(message));
Expand Down Expand Up @@ -169,7 +174,9 @@ function handleSocketConnection(socket) {
reason,
});
gauge("connected." + board.name, userCount);
if (userCount === 0) unloadBoard(room);
if (userCount === 0) {
unloadBoard(room);
}
}
});
});
Expand Down

0 comments on commit db99344

Please sign in to comment.