small refactorings

This commit is contained in:
zadam 2023-05-04 22:16:18 +02:00
parent ecd2a5cbac
commit 8edf06d28d
28 changed files with 49 additions and 44 deletions

View File

@ -141,7 +141,7 @@ class BAttribute extends AbstractBeccaEntity {
*/ */
getTargetNote() { getTargetNote() {
if (this.type !== 'relation') { if (this.type !== 'relation') {
throw new Error(`Attribute ${this.attributeId} is not relation`); throw new Error(`Attribute '${this.attributeId}' is not a relation.`);
} }
if (!this.value) { if (!this.value) {

View File

@ -1445,14 +1445,16 @@ class BNote extends AbstractBeccaEntity {
const targetRelations = this.getTargetRelations().filter(relation => relation.name === 'imageLink'); const targetRelations = this.getTargetRelations().filter(relation => relation.name === 'imageLink');
if (targetRelations.length !== 1) { if (targetRelations.length > 1) {
return false; return false;
} }
const parentNote = this.getParentNotes()[0]; // at this point note can have only one parent const parentNote = this.getParentNotes()[0]; // at this point note can have only one parent
const referencingNote = targetRelations[0].getNote(); const referencingNote = targetRelations[0]?.getNote();
if (parentNote !== referencingNote || parentNote.type !== 'text' || !parentNote.isContentAvailable()) { if (referencingNote && parentNote !== referencingNote) {
return false;
} else if (parentNote.type !== 'text' || !parentNote.isContentAvailable()) {
return false; return false;
} }

View File

@ -20,7 +20,7 @@ const ENTITY_NAME_TO_ENTITY = {
function getEntityFromEntityName(entityName) { function getEntityFromEntityName(entityName) {
if (!(entityName in ENTITY_NAME_TO_ENTITY)) { if (!(entityName in ENTITY_NAME_TO_ENTITY)) {
throw new Error(`Entity for table ${entityName} not found!`); throw new Error(`Entity for table '${entityName}' not found!`);
} }
return ENTITY_NAME_TO_ENTITY[entityName]; return ENTITY_NAME_TO_ENTITY[entityName];

View File

@ -29,7 +29,7 @@ function register(router, loginMiddleware) {
if (!etapiToken) { if (!etapiToken) {
// shouldn't happen since this already passed auth validation // shouldn't happen since this already passed auth validation
throw new Error(`Cannot find the token ${parsed.etapiTokenId}.`); throw new Error(`Cannot find the token '${parsed.etapiTokenId}'.`);
} }
etapiToken.markAsDeletedSimple(); etapiToken.markAsDeletedSimple();

View File

@ -252,14 +252,16 @@ class FNote {
const targetRelations = this.getTargetRelations().filter(relation => relation.name === 'imageLink'); const targetRelations = this.getTargetRelations().filter(relation => relation.name === 'imageLink');
if (targetRelations.length !== 1) { if (targetRelations.length > 1) {
return false; return false;
} }
const parentNote = this.getParentNotes()[0]; // at this point note can have only one parent const parentNote = this.getParentNotes()[0]; // at this point note can have only one parent
const referencingNote = targetRelations[0].getNote(); const referencingNote = targetRelations[0]?.getNote();
if (parentNote !== referencingNote || parentNote.type !== 'text' || !parentNote.isContentAvailable()) { if (referencingNote && referencingNote !== parentNote) {
return false;
} else if (parentNote.type !== 'text' || !parentNote.isContentAvailable()) {
return false; return false;
} }

View File

@ -5,7 +5,7 @@ export default class FlexContainer extends Container {
super(); super();
if (!direction || !['row', 'column'].includes(direction)) { if (!direction || !['row', 'column'].includes(direction)) {
throw new Error(`Direction argument given as "${direction}", use either 'row' or 'column'`); throw new Error(`Direction argument given as '${direction}', use either 'row' or 'column'`);
} }
this.attrs.style = `display: flex; flex-direction: ${direction};`; this.attrs.style = `display: flex; flex-direction: ${direction};`;

View File

@ -203,7 +203,7 @@ export default class ExportDialog extends BasicWidget {
this.$singleType.prop("checked", true).trigger('change'); this.$singleType.prop("checked", true).trigger('change');
} }
else { else {
throw new Error(`Unrecognized type ${defaultType}`); throw new Error(`Unrecognized type '${defaultType}'`);
} }
this.$widget.find(".opml-v2").prop("checked", true); // setting default this.$widget.find(".opml-v2").prop("checked", true); // setting default

View File

@ -32,7 +32,7 @@ class MobileDetailMenuWidget extends BasicWidget {
const branchId = await treeService.getBranchIdFromNotePath(notePath); const branchId = await treeService.getBranchIdFromNotePath(notePath);
if (!branchId) { if (!branchId) {
throw new Error(`Cannot get branchId for notePath ${notePath}`); throw new Error(`Cannot get branchId for notePath '${notePath}'`);
} }
if (await branchService.deleteNotes([branchId])) { if (await branchService.deleteNotes([branchId])) {

View File

@ -174,7 +174,7 @@ export default class NoteDetailWidget extends NoteContextAwareWidget {
getTypeWidget() { getTypeWidget() {
if (!this.typeWidgets[this.type]) { if (!this.typeWidgets[this.type]) {
throw new Error(`Could not find typeWidget for type: ${this.type}`); throw new Error(`Could not find typeWidget for type '${this.type}'`);
} }
return this.typeWidgets[this.type]; return this.typeWidgets[this.type];

View File

@ -475,7 +475,7 @@ export default class NoteTreeWidget extends NoteContextAwareWidget {
} else if (data.hitMode === "over") { } else if (data.hitMode === "over") {
branchService.moveToParentNote(selectedBranchIds, node.data.branchId); branchService.moveToParentNote(selectedBranchIds, node.data.branchId);
} else { } else {
throw new Error(`Unknown hitMode=${data.hitMode}`); throw new Error(`Unknown hitMode '${data.hitMode}'`);
} }
} }
} }
@ -691,7 +691,7 @@ export default class NoteTreeWidget extends NoteContextAwareWidget {
const note = branch.getNoteFromCache(); const note = branch.getNoteFromCache();
if (!note) { if (!note) {
throw new Error(`Branch "${branch.branchId}" has no child note "${branch.noteId}"`); throw new Error(`Branch '${branch.branchId}' has no child note '${branch.noteId}'`);
} }
const title = `${branch.prefix ? (`${branch.prefix} - `) : ""}${note.title}`; const title = `${branch.prefix ? (`${branch.prefix} - `) : ""}${note.title}`;

View File

@ -101,7 +101,7 @@ export default class BookPropertiesWidget extends NoteContextAwareWidget {
async toggleViewType(type) { async toggleViewType(type) {
if (type !== 'list' && type !== 'grid') { if (type !== 'list' && type !== 'grid') {
throw new Error(`Invalid view type ${type}`); throw new Error(`Invalid view type '${type}'`);
} }
await attributeService.setLabel(this.noteId, 'viewType', type); await attributeService.setLabel(this.noteId, 'viewType', type);

View File

@ -33,7 +33,7 @@ export default class AttachmentListTypeWidget extends TypeWidget {
const attachments = await server.get(`notes/${this.noteId}/attachments?includeContent=true`); const attachments = await server.get(`notes/${this.noteId}/attachments?includeContent=true`);
if (attachments.length === 0) { if (attachments.length === 0) {
this.$list.html("<strong>This note has no attachments.</strong>"); this.$list.html('<div class="alert alert-info">This note has no attachments.</div>');
return; return;
} }

View File

@ -79,7 +79,7 @@ class ImageTypeWidget extends TypeWidget {
utils.dynamicRequire('electron'); utils.dynamicRequire('electron');
webContents.copyImageAt(e.pageX, e.pageY); webContents.copyImageAt(e.pageX, e.pageY);
} else { } else {
throw new Error(`Unrecognized command ${command}`); throw new Error(`Unrecognized command '${command}'`);
} }
} }
}); });

View File

@ -24,7 +24,7 @@ function moveBranchToParent(req) {
const branchToMove = becca.getBranch(branchId); const branchToMove = becca.getBranch(branchId);
if (!parentBranch || !branchToMove) { if (!parentBranch || !branchToMove) {
throw new ValidationError(`One or both branches ${branchId}, ${parentBranchId} have not been found`); throw new ValidationError(`One or both branches '${branchId}', '${parentBranchId}' have not been found`);
} }
return branchService.moveBranchToBranch(branchToMove, parentBranch, branchId); return branchService.moveBranchToBranch(branchToMove, parentBranch, branchId);

View File

@ -93,7 +93,7 @@ function updateOptions(req) {
if (!update(optionName, req.body[optionName])) { if (!update(optionName, req.body[optionName])) {
// this should be improved // this should be improved
// it should return 400 instead of current 500, but at least it now rollbacks transaction // it should return 400 instead of current 500, but at least it now rollbacks transaction
throw new Error(`${optionName} is not allowed to change`); throw new Error(`Option '${optionName}' is not allowed to be changed`);
} }
} }
} }

View File

@ -48,7 +48,7 @@ function cloneNoteToBranch(noteId, parentBranchId, prefix) {
const parentBranch = becca.getBranch(parentBranchId); const parentBranch = becca.getBranch(parentBranchId);
if (!parentBranch) { if (!parentBranch) {
return { success: false, message: `Parent branch ${parentBranchId} does not exist.` }; return { success: false, message: `Parent branch '${parentBranchId}' does not exist.` };
} }
const ret = cloneNoteToParentNote(noteId, parentBranch.noteId, prefix); const ret = cloneNoteToParentNote(noteId, parentBranch.noteId, prefix);

View File

@ -47,7 +47,7 @@ function parseDateTime(str) {
return new Date(Date.parse(str)); return new Date(Date.parse(str));
} }
catch (e) { catch (e) {
throw new Error(`Can't parse date from ${str}: ${e.stack}`); throw new Error(`Can't parse date from '${str}': ${e.stack}`);
} }
} }

View File

@ -137,7 +137,7 @@ function fillEntityChanges(entityName, entityPrimaryKey, condition = '') {
} }
if (createdCount > 0) { if (createdCount > 0) {
log.info(`Created ${createdCount} missing entity changes for ${entityName}.`); log.info(`Created ${createdCount} missing entity changes for entity '${entityName}'.`);
} }
}); });
} }

View File

@ -97,7 +97,7 @@ function renameToken(etapiTokenId, newName) {
const etapiToken = becca.getEtapiToken(etapiTokenId); const etapiToken = becca.getEtapiToken(etapiTokenId);
if (!etapiToken) { if (!etapiToken) {
throw new Error(`Token ${etapiTokenId} does not exist`); throw new Error(`Token '${etapiTokenId}' does not exist`);
} }
etapiToken.name = newName; etapiToken.name = newName;

View File

@ -49,7 +49,7 @@ function emit(eventType, data) {
listener(data); listener(data);
} }
catch (e) { catch (e) {
log.error(`Listener threw error: ${e.stack}`); log.error(`Listener threw error: ${e.message}, stack: ${e.stack}`);
// we won't stop execution because of listener // we won't stop execution because of listener
} }
} }

View File

@ -218,11 +218,8 @@ eventService.subscribe(eventService.ENTITY_DELETED, ({ entityName, entity }) =>
if (entityName === 'notes' && entity.noteId.startsWith("_")) { if (entityName === 'notes' && entity.noteId.startsWith("_")) {
// "named" note has been deleted, we will probably need to rebuild the hidden subtree // "named" note has been deleted, we will probably need to rebuild the hidden subtree
// scheduling so that bulk deletes won't trigger so many checks // scheduling so that bulk deletes won't trigger so many checks
oneTimeTimer.scheduleExecution('hidden-subtree-check', 1000, () => { oneTimeTimer.scheduleExecution('hidden-subtree-check', 1000,
console.log("Checking hidden subtree"); () => hiddenSubtreeService.checkHiddenSubtree());
hiddenSubtreeService.checkHiddenSubtree();
});
} }
}); });

View File

@ -17,7 +17,7 @@ function isHoistedInHiddenSubtree() {
const hoistedNote = becca.getNote(hoistedNoteId); const hoistedNote = becca.getNote(hoistedNoteId);
if (!hoistedNote) { if (!hoistedNote) {
throw new Error(`Cannot find hoisted note ${hoistedNoteId}`); throw new Error(`Cannot find hoisted note '${hoistedNoteId}'`);
} }
return hoistedNote.isHiddenCompletely(); return hoistedNote.isHiddenCompletely();

View File

@ -116,7 +116,7 @@ function getAndValidateParent(params) {
const parentNote = becca.notes[params.parentNoteId]; const parentNote = becca.notes[params.parentNoteId];
if (!parentNote) { if (!parentNote) {
throw new ValidationError(`Parent note "${params.parentNoteId}" not found.`); throw new ValidationError(`Parent note '${params.parentNoteId}' was not found.`);
} }
if (parentNote.type === 'launcher' && parentNote.noteId !== '_lbBookmarks') { if (parentNote.type === 'launcher' && parentNote.noteId !== '_lbBookmarks') {
@ -281,7 +281,7 @@ function createNewNoteWithTarget(target, targetBranchId, params) {
return retObject; return retObject;
} }
else { else {
throw new Error(`Unknown target ${target}`); throw new Error(`Unknown target '${target}'`);
} }
} }
@ -883,11 +883,15 @@ function eraseUnusedBlobs() {
FROM blobs FROM blobs
LEFT JOIN notes ON notes.blobId = blobs.blobId LEFT JOIN notes ON notes.blobId = blobs.blobId
LEFT JOIN attachments ON attachments.blobId = blobs.blobId LEFT JOIN attachments ON attachments.blobId = blobs.blobId
LEFT JOIN note_revisions ON attachments.blobId = blobs.blobId LEFT JOIN note_revisions ON note_revisions.blobId = blobs.blobId
WHERE notes.noteId IS NULL WHERE notes.noteId IS NULL
AND attachments.attachmentId IS NULL AND attachments.attachmentId IS NULL
AND note_revisions.noteRevisionId IS NULL`); AND note_revisions.noteRevisionId IS NULL`);
if (unusedBlobIds.length === 0) {
return;
}
sql.executeMany(`DELETE FROM blobs WHERE blobId IN (???)`, unusedBlobIds); sql.executeMany(`DELETE FROM blobs WHERE blobId IN (???)`, unusedBlobIds);
setEntityChangesAsErased(sql.getManyRows(`SELECT * FROM entity_changes WHERE entityName = 'blobs' AND entityId IN (???)`, unusedBlobIds)); setEntityChangesAsErased(sql.getManyRows(`SELECT * FROM entity_changes WHERE entityName = 'blobs' AND entityId IN (???)`, unusedBlobIds));

View File

@ -33,7 +33,7 @@ function getOptionInt(name) {
const intVal = parseInt(val); const intVal = parseInt(val);
if (isNaN(intVal)) { if (isNaN(intVal)) {
throw new Error(`Could not parse "${val}" into integer for option "${name}"`); throw new Error(`Could not parse '${val}' into integer for option '${name}'`);
} }
return intVal; return intVal;
@ -46,7 +46,7 @@ function getOptionBool(name) {
const val = getOption(name); const val = getOption(name);
if (!['true', 'false'].includes(val)) { if (!['true', 'false'].includes(val)) {
throw new Error(`Could not parse "${val}" into boolean for option "${name}"`); throw new Error(`Could not parse '${val}' into boolean for option '${name}'`);
} }
return val === 'true'; return val === 'true';

View File

@ -182,7 +182,7 @@ function getClient(opts) {
return require(protocol.substr(0, protocol.length - 1)); return require(protocol.substr(0, protocol.length - 1));
} }
else { else {
throw new Error(`Unrecognized protocol "${protocol}"`); throw new Error(`Unrecognized protocol '${protocol}'`);
} }
} }
} }

View File

@ -109,7 +109,7 @@ async function doLogin() {
}); });
if (resp.instanceId === instanceId) { if (resp.instanceId === instanceId) {
throw new Error(`Sync server has member ID ${resp.instanceId} which is also local. This usually happens when the sync client is (mis)configured to sync with itself (URL points back to client) instead of the correct sync server.`); throw new Error(`Sync server has member ID '${resp.instanceId}' which is also local. This usually happens when the sync client is (mis)configured to sync with itself (URL points back to client) instead of the correct sync server.`);
} }
syncContext.instanceId = resp.instanceId; syncContext.instanceId = resp.instanceId;
@ -312,13 +312,13 @@ function getEntityChangeRow(entityName, entityId) {
const primaryKey = entityConstructor.getEntityFromEntityName(entityName).primaryKeyName; const primaryKey = entityConstructor.getEntityFromEntityName(entityName).primaryKeyName;
if (!primaryKey) { if (!primaryKey) {
throw new Error(`Unknown entity ${entityName}`); throw new Error(`Unknown entity '${entityName}'`);
} }
const entity = sql.getRow(`SELECT * FROM ${entityName} WHERE ${primaryKey} = ?`, [entityId]); const entity = sql.getRow(`SELECT * FROM ${entityName} WHERE ${primaryKey} = ?`, [entityId]);
if (!entity) { if (!entity) {
throw new Error(`Entity ${entityName} ${entityId} not found.`); throw new Error(`Entity ${entityName} '${entityId}' not found.`);
} }
if (entityName === 'blobs' && entity.content !== null) { if (entityName === 'blobs' && entity.content !== null) {

View File

@ -200,7 +200,7 @@ function setNoteToParent(noteId, prefix, parentNoteId) {
const parentNote = becca.getNote(parentNoteId); const parentNote = becca.getNote(parentNoteId);
if (parentNote && parentNote.isDeleted) { if (parentNote && parentNote.isDeleted) {
throw new Error(`Cannot move note to deleted parent note ${parentNoteId}`); throw new Error(`Cannot move note to deleted parent note '${parentNoteId}'`);
} }
// case where there might be more such branches is ignored. It's expected there should be just one // case where there might be more such branches is ignored. It's expected there should be just one
@ -224,7 +224,7 @@ function setNoteToParent(noteId, prefix, parentNoteId) {
const note = becca.getNote(noteId); const note = becca.getNote(noteId);
if (note.isDeleted) { if (note.isDeleted) {
throw new Error(`Cannot create a branch for ${noteId} which is deleted.`); throw new Error(`Cannot create a branch for '${noteId}' which is deleted.`);
} }
const branchId = sql.getValue('SELECT branchId FROM branches WHERE isDeleted = 0 AND noteId = ? AND parentNoteId = ?', [noteId, parentNoteId]); const branchId = sql.getValue('SELECT branchId FROM branches WHERE isDeleted = 0 AND noteId = ? AND parentNoteId = ?', [noteId, parentNoteId]);

View File

@ -89,7 +89,7 @@ class SAttribute extends AbstractShacaEntity {
/** @returns {SNote|null} */ /** @returns {SNote|null} */
getTargetNote() { getTargetNote() {
if (this.type !== 'relation') { if (this.type !== 'relation') {
throw new Error(`Attribute ${this.attributeId} is not relation`); throw new Error(`Attribute '${this.attributeId}' is not relation`);
} }
if (!this.value) { if (!this.value) {