Skip to content

Commit

Permalink
Merge pull request #1347 from TriliumNext/chore_eslint-fixes_src-routes
Browse files Browse the repository at this point in the history
chore(lint): fix eslint issues in `src/routes`
  • Loading branch information
eliandoran authored Mar 8, 2025
2 parents 4cffc50 + c120132 commit 14c3fd5
Show file tree
Hide file tree
Showing 27 changed files with 172 additions and 95 deletions.
2 changes: 1 addition & 1 deletion src/becca/entities/bnote.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1618,7 +1618,7 @@ class BNote extends AbstractBeccaEntity<BNote> {
* @param matchBy - choose by which property we detect if to update an existing attachment.
* Supported values are either 'attachmentId' (default) or 'title'
*/
saveAttachment({ attachmentId, role, mime, title, content, position }: AttachmentRow, matchBy = "attachmentId") {
saveAttachment({ attachmentId, role, mime, title, content, position }: AttachmentRow, matchBy: "attachmentId" | "title" | undefined = "attachmentId") {
if (!["attachmentId", "title"].includes(matchBy)) {
throw new Error(`Unsupported value '${matchBy}' for matchBy param, has to be either 'attachmentId' or 'title'.`);
}
Expand Down
4 changes: 2 additions & 2 deletions src/becca/entities/brevision.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import becca from "../becca.js";
import AbstractBeccaEntity from "./abstract_becca_entity.js";
import sql from "../../services/sql.js";
import BAttachment from "./battachment.js";
import type { AttachmentRow, RevisionRow } from "./rows.js";
import type { AttachmentRow, NoteType, RevisionRow } from "./rows.js";
import eraseService from "../../services/erase.js";

interface ContentOpts {
Expand Down Expand Up @@ -36,7 +36,7 @@ class BRevision extends AbstractBeccaEntity<BRevision> {

revisionId?: string;
noteId!: string;
type!: string;
type!: NoteType;
mime!: string;
title!: string;
dateLastEdited?: string;
Expand Down
2 changes: 1 addition & 1 deletion src/becca/entities/rows.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ export interface AttachmentRow {
export interface RevisionRow {
revisionId?: string;
noteId: string;
type: string;
type: NoteType;
mime: string;
isProtected?: boolean;
title: string;
Expand Down
12 changes: 12 additions & 0 deletions src/errors/forbidden_error.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import HttpError from "./http_error.js";

class ForbiddenError extends HttpError {

constructor(message: string) {
super(message, 403);
this.name = "ForbiddenError";
}

}

export default ForbiddenError;
13 changes: 13 additions & 0 deletions src/errors/http_error.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
class HttpError extends Error {

statusCode: number;

constructor(message: string, statusCode: number) {
super(message);
this.name = "HttpError";
this.statusCode = statusCode;
}

}

export default HttpError;
9 changes: 6 additions & 3 deletions src/errors/not_found_error.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
class NotFoundError {
message: string;
import HttpError from "./http_error.js";

class NotFoundError extends HttpError {

constructor(message: string) {
this.message = message;
super(message, 404);
this.name = "NotFoundError";
}

}

export default NotFoundError;
9 changes: 6 additions & 3 deletions src/errors/validation_error.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
class ValidationError {
message: string;
import HttpError from "./http_error.js";

class ValidationError extends HttpError {

constructor(message: string) {
this.message = message;
super(message, 400)
this.name = "ValidationError";
}

}

export default ValidationError;
13 changes: 11 additions & 2 deletions src/routes/api/attachments.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,15 +33,24 @@ function getAllAttachments(req: Request) {
function saveAttachment(req: Request) {
const { noteId } = req.params;
const { attachmentId, role, mime, title, content } = req.body;
const { matchBy } = req.query as any;
const matchByQuery = req.query.matchBy
const isValidMatchBy = (typeof matchByQuery === "string") && (matchByQuery === "attachmentId" || matchByQuery === "title");
const matchBy = isValidMatchBy ? matchByQuery : undefined;

const note = becca.getNoteOrThrow(noteId);
note.saveAttachment({ attachmentId, role, mime, title, content }, matchBy);
}

function uploadAttachment(req: Request) {
const { noteId } = req.params;
const { file } = req as any;
const { file } = req;

if (!file) {
return {
uploaded: false,
message: `Missing attachment data.`
};
}

const note = becca.getNoteOrThrow(noteId);
let url;
Expand Down
23 changes: 10 additions & 13 deletions src/routes/api/clipper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,12 @@ function addClipping(req: Request) {
// if a note under the clipperInbox has the same 'pageUrl' attribute,
// add the content to that note and clone it under today's inbox
// otherwise just create a new note under today's inbox
let { title, content, pageUrl, images } = req.body;
const { title, content, images } = req.body;
const clipType = "clippings";

const clipperInbox = getClipperInboxNote();

pageUrl = htmlSanitizer.sanitizeUrl(pageUrl);
const pageUrl = htmlSanitizer.sanitizeUrl(req.body.pageUrl);
let clippingNote = findClippingNote(clipperInbox, pageUrl, clipType);

if (!clippingNote) {
Expand Down Expand Up @@ -100,16 +100,15 @@ function getClipperInboxNote() {
}

function createNote(req: Request) {
let { title, content, pageUrl, images, clipType, labels } = req.body;
const { content, images, labels } = req.body;

if (!title || !title.trim()) {
title = `Clipped note from ${pageUrl}`;
}
const clipType = htmlSanitizer.sanitize(req.body.clipType);
const pageUrl = htmlSanitizer.sanitizeUrl(req.body.pageUrl);

clipType = htmlSanitizer.sanitize(clipType);
const trimmedTitle = (typeof req.body.title === "string") ? req.body.title.trim() : "";
const title = trimmedTitle || `Clipped note from ${pageUrl}`;

const clipperInbox = getClipperInboxNote();
pageUrl = htmlSanitizer.sanitizeUrl(pageUrl);
let note = findClippingNote(clipperInbox, pageUrl, clipType);

if (!note) {
Expand All @@ -123,8 +122,6 @@ function createNote(req: Request) {
note.setLabel("clipType", clipType);

if (pageUrl) {
pageUrl = htmlSanitizer.sanitizeUrl(pageUrl);

note.setLabel("pageUrl", pageUrl);
note.setLabel("iconClass", "bx bx-globe");
}
Expand All @@ -139,7 +136,7 @@ function createNote(req: Request) {

const existingContent = note.getContent();
if (typeof existingContent !== "string") {
throw new ValidationError("Invalid note content tpye.");
throw new ValidationError("Invalid note content type.");
}
const rewrittenContent = processContent(images, note, content);
const newContent = `${existingContent}${existingContent.trim() ? "<br/>" : ""}${rewrittenContent}`;
Expand Down Expand Up @@ -219,9 +216,9 @@ function handshake() {
}

function findNotesByUrl(req: Request) {
let pageUrl = req.params.noteUrl;
const pageUrl = req.params.noteUrl;
const clipperInbox = getClipperInboxNote();
let foundPage = findClippingNote(clipperInbox, pageUrl, null);
const foundPage = findClippingNote(clipperInbox, pageUrl, null);
return {
noteId: foundPage ? foundPage.noteId : null
};
Expand Down
8 changes: 5 additions & 3 deletions src/routes/api/export.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import log from "../../services/log.js";
import NotFoundError from "../../errors/not_found_error.js";
import type { Request, Response } from "express";
import ValidationError from "../../errors/validation_error.js";
import { safeExtractMessageAndStackFromError } from "../../services/utils.js";

function exportBranch(req: Request, res: Response) {
const { branchId, type, format, version, taskId } = req.params;
Expand Down Expand Up @@ -37,11 +38,12 @@ function exportBranch(req: Request, res: Response) {
} else {
throw new NotFoundError(`Unrecognized export format '${format}'`);
}
} catch (e: any) {
const message = `Export failed with following error: '${e.message}'. More details might be in the logs.`;
} catch (e: unknown) {
const [errMessage, errStack] = safeExtractMessageAndStackFromError(e);
const message = `Export failed with following error: '${errMessage}'. More details might be in the logs.`;
taskContext.reportError(message);

log.error(message + e.stack);
log.error(errMessage + errStack);

res.setHeader("Content-Type", "text/plain").status(500).send(message);
}
Expand Down
2 changes: 1 addition & 1 deletion src/routes/api/image.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ function updateImage(req: Request) {
const { noteId } = req.params;
const { file } = req;

const note = becca.getNoteOrThrow(noteId);
const _note = becca.getNoteOrThrow(noteId);

if (!file) {
return {
Expand Down
16 changes: 10 additions & 6 deletions src/routes/api/import.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import TaskContext from "../../services/task_context.js";
import ValidationError from "../../errors/validation_error.js";
import type { Request } from "express";
import type BNote from "../../becca/entities/bnote.js";
import { safeExtractMessageAndStackFromError } from "../../services/utils.js";

async function importNotesToBranch(req: Request) {
const { parentNoteId } = req.params;
Expand Down Expand Up @@ -68,11 +69,12 @@ async function importNotesToBranch(req: Request) {
} else {
note = await singleImportService.importSingleFile(taskContext, file, parentNote);
}
} catch (e: any) {
const message = `Import failed with following error: '${e.message}'. More details might be in the logs.`;
} catch (e: unknown) {
const [errMessage, errStack] = safeExtractMessageAndStackFromError(e);
const message = `Import failed with following error: '${errMessage}'. More details might be in the logs.`;
taskContext.reportError(message);

log.error(message + e.stack);
log.error(message + errStack);

return [500, message];
}
Expand Down Expand Up @@ -120,11 +122,13 @@ async function importAttachmentsToNote(req: Request) {

try {
await singleImportService.importAttachment(taskContext, file, parentNote);
} catch (e: any) {
const message = `Import failed with following error: '${e.message}'. More details might be in the logs.`;
} catch (e: unknown) {
const [errMessage, errStack] = safeExtractMessageAndStackFromError(e);

const message = `Import failed with following error: '${errMessage}'. More details might be in the logs.`;
taskContext.reportError(message);

log.error(message + e.stack);
log.error(message + errStack);

return [500, message];
}
Expand Down
1 change: 0 additions & 1 deletion src/routes/api/recent_changes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import protectedSessionService from "../../services/protected_session.js";
import noteService from "../../services/notes.js";
import becca from "../../becca/becca.js";
import type { Request } from "express";
import type { RevisionRow } from "../../becca/entities/rows.js";

interface RecentChangeRow {
noteId: string;
Expand Down
2 changes: 1 addition & 1 deletion src/routes/api/relation-map.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ function getRelationMap(req: Request) {
return resp;
}

const questionMarks = noteIds.map((noteId) => "?").join(",");
const questionMarks = noteIds.map((_noteId) => "?").join(",");

const relationMapNote = becca.getNoteOrThrow(relationMapNoteId);

Expand Down
5 changes: 2 additions & 3 deletions src/routes/api/revisions.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
"use strict";

import beccaService from "../../becca/becca_service.js";
import revisionService from "../../services/revisions.js";
import utils from "../../services/utils.js";
import sql from "../../services/sql.js";
import cls from "../../services/cls.js";
Expand Down Expand Up @@ -111,7 +110,7 @@ function eraseRevision(req: Request) {
}

function eraseAllExcessRevisions() {
let allNoteIds = sql.getRows("SELECT noteId FROM notes WHERE SUBSTRING(noteId, 1, 1) != '_'") as { noteId: string }[];
const allNoteIds = sql.getRows("SELECT noteId FROM notes WHERE SUBSTRING(noteId, 1, 1) != '_'") as { noteId: string }[];
allNoteIds.forEach((row) => {
becca.getNote(row.noteId)?.eraseExcessRevisionSnapshots();
});
Expand Down Expand Up @@ -145,7 +144,7 @@ function restoreRevision(req: Request) {

note.title = revision.title;
note.mime = revision.mime;
note.type = revision.type as any;
note.type = revision.type;
note.setContent(revisionContent, { forceSave: true });
});
}
Expand Down
9 changes: 7 additions & 2 deletions src/routes/api/script.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import becca from "../../becca/becca.js";
import syncService from "../../services/sync.js";
import sql from "../../services/sql.js";
import type { Request } from "express";
import { safeExtractMessageAndStackFromError } from "../../services/utils.js";

interface ScriptBody {
script: string;
Expand Down Expand Up @@ -33,8 +34,12 @@ async function exec(req: Request) {
executionResult: result,
maxEntityChangeId: syncService.getMaxEntityChangeId()
};
} catch (e: any) {
return { success: false, error: e.message };
} catch (e: unknown) {
const [errMessage] = safeExtractMessageAndStackFromError(e);
return {
success: false,
error: errMessage
};
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/routes/api/similar_notes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import becca from "../../becca/becca.js";
async function getSimilarNotes(req: Request) {
const noteId = req.params.noteId;

const note = becca.getNoteOrThrow(noteId);
const _note = becca.getNoteOrThrow(noteId);

return await similarityService.findSimilarNotes(noteId);
}
Expand Down
6 changes: 4 additions & 2 deletions src/routes/api/sql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import sql from "../../services/sql.js";
import becca from "../../becca/becca.js";
import type { Request } from "express";
import ValidationError from "../../errors/validation_error.js";
import { safeExtractMessageAndStackFromError } from "../../services/utils.js";

function getSchema() {
const tableNames = sql.getColumn(`SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name`);
Expand Down Expand Up @@ -56,10 +57,11 @@ function execute(req: Request) {
success: true,
results
};
} catch (e: any) {
} catch (e: unknown) {
const [errMessage] = safeExtractMessageAndStackFromError(e);
return {
success: false,
error: e.message
error: errMessage
};
}
}
Expand Down
7 changes: 4 additions & 3 deletions src/routes/api/sync.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import optionService from "../../services/options.js";
import contentHashService from "../../services/content_hash.js";
import log from "../../services/log.js";
import syncOptions from "../../services/sync_options.js";
import utils from "../../services/utils.js";
import utils, { safeExtractMessageAndStackFromError } from "../../services/utils.js";
import ws from "../../services/ws.js";
import type { Request } from "express";
import type { EntityChange } from "../../services/entity_changes_interface.js";
Expand All @@ -30,10 +30,11 @@ async function testSync() {
syncService.sync();

return { success: true, message: t("test_sync.successful") };
} catch (e: any) {
} catch (e: unknown) {
const [errMessage] = safeExtractMessageAndStackFromError(e);
return {
success: false,
message: e.message
error: errMessage
};
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/routes/api_docs.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { Application, Router } from "express";
import type { Application } from "express";
import swaggerUi from "swagger-ui-express";
import { readFile } from "fs/promises";
import { fileURLToPath } from "url";
Expand Down
2 changes: 1 addition & 1 deletion src/routes/assets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import express from "express";
import { isDev, isElectron } from "../services/utils.js";
import type serveStatic from "serve-static";

const persistentCacheStatic = (root: string, options?: serveStatic.ServeStaticOptions<express.Response<any, Record<string, any>>>) => {
const persistentCacheStatic = (root: string, options?: serveStatic.ServeStaticOptions<express.Response<unknown, Record<string, unknown>>>) => {
if (!isDev) {
options = {
maxAge: "1y",
Expand Down
Loading

0 comments on commit 14c3fd5

Please sign in to comment.