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() {
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) {

View File

@ -1445,14 +1445,16 @@ class BNote extends AbstractBeccaEntity {
const targetRelations = this.getTargetRelations().filter(relation => relation.name === 'imageLink');
if (targetRelations.length !== 1) {
if (targetRelations.length > 1) {
return false;
}
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;
}

View File

@ -20,7 +20,7 @@ const ENTITY_NAME_TO_ENTITY = {
function getEntityFromEntityName(entityName) {
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];

View File

@ -29,7 +29,7 @@ function register(router, loginMiddleware) {
if (!etapiToken) {
// 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();

View File

@ -252,14 +252,16 @@ class FNote {
const targetRelations = this.getTargetRelations().filter(relation => relation.name === 'imageLink');
if (targetRelations.length !== 1) {
if (targetRelations.length > 1) {
return false;
}
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;
}

View File

@ -5,7 +5,7 @@ export default class FlexContainer extends Container {
super();
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};`;

View File

@ -203,7 +203,7 @@ export default class ExportDialog extends BasicWidget {
this.$singleType.prop("checked", true).trigger('change');
}
else {
throw new Error(`Unrecognized type ${defaultType}`);
throw new Error(`Unrecognized type '${defaultType}'`);
}
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);
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])) {

View File

@ -174,7 +174,7 @@ export default class NoteDetailWidget extends NoteContextAwareWidget {
getTypeWidget() {
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];

View File

@ -475,7 +475,7 @@ export default class NoteTreeWidget extends NoteContextAwareWidget {
} else if (data.hitMode === "over") {
branchService.moveToParentNote(selectedBranchIds, node.data.branchId);
} 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();
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}`;

View File

@ -101,7 +101,7 @@ export default class BookPropertiesWidget extends NoteContextAwareWidget {
async toggleViewType(type) {
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);

View File

@ -33,7 +33,7 @@ export default class AttachmentListTypeWidget extends TypeWidget {
const attachments = await server.get(`notes/${this.noteId}/attachments?includeContent=true`);
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;
}

View File

@ -79,7 +79,7 @@ class ImageTypeWidget extends TypeWidget {
utils.dynamicRequire('electron');
webContents.copyImageAt(e.pageX, e.pageY);
} 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);
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);

View File

@ -93,7 +93,7 @@ function updateOptions(req) {
if (!update(optionName, req.body[optionName])) {
// this should be improved
// 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);
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);

View File

@ -47,7 +47,7 @@ function parseDateTime(str) {
return new Date(Date.parse(str));
}
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) {
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);
if (!etapiToken) {
throw new Error(`Token ${etapiTokenId} does not exist`);
throw new Error(`Token '${etapiTokenId}' does not exist`);
}
etapiToken.name = newName;

View File

@ -49,7 +49,7 @@ function emit(eventType, data) {
listener(data);
}
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
}
}

View File

@ -218,11 +218,8 @@ eventService.subscribe(eventService.ENTITY_DELETED, ({ entityName, entity }) =>
if (entityName === 'notes' && entity.noteId.startsWith("_")) {
// "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
oneTimeTimer.scheduleExecution('hidden-subtree-check', 1000, () => {
console.log("Checking hidden subtree");
hiddenSubtreeService.checkHiddenSubtree();
});
oneTimeTimer.scheduleExecution('hidden-subtree-check', 1000,
() => hiddenSubtreeService.checkHiddenSubtree());
}
});

View File

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

View File

@ -116,7 +116,7 @@ function getAndValidateParent(params) {
const parentNote = becca.notes[params.parentNoteId];
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') {
@ -281,7 +281,7 @@ function createNewNoteWithTarget(target, targetBranchId, params) {
return retObject;
}
else {
throw new Error(`Unknown target ${target}`);
throw new Error(`Unknown target '${target}'`);
}
}
@ -883,11 +883,15 @@ function eraseUnusedBlobs() {
FROM blobs
LEFT JOIN notes ON notes.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
AND attachments.attachmentId IS NULL
AND note_revisions.noteRevisionId IS NULL`);
if (unusedBlobIds.length === 0) {
return;
}
sql.executeMany(`DELETE FROM blobs WHERE blobId IN (???)`, unusedBlobIds);
setEntityChangesAsErased(sql.getManyRows(`SELECT * FROM entity_changes WHERE entityName = 'blobs' AND entityId IN (???)`, unusedBlobIds));

View File

@ -10,7 +10,7 @@ function getOptionOrNull(name) {
// e.g. in initial sync becca is not loaded because DB is not initialized
option = sql.getRow("SELECT * FROM options WHERE name = ?", name);
}
return option ? option.value : null;
}
@ -33,7 +33,7 @@ function getOptionInt(name) {
const intVal = parseInt(val);
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;
@ -46,7 +46,7 @@ function getOptionBool(name) {
const val = getOption(name);
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';

View File

@ -182,7 +182,7 @@ function getClient(opts) {
return require(protocol.substr(0, protocol.length - 1));
}
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) {
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;
@ -312,13 +312,13 @@ function getEntityChangeRow(entityName, entityId) {
const primaryKey = entityConstructor.getEntityFromEntityName(entityName).primaryKeyName;
if (!primaryKey) {
throw new Error(`Unknown entity ${entityName}`);
throw new Error(`Unknown entity '${entityName}'`);
}
const entity = sql.getRow(`SELECT * FROM ${entityName} WHERE ${primaryKey} = ?`, [entityId]);
if (!entity) {
throw new Error(`Entity ${entityName} ${entityId} not found.`);
throw new Error(`Entity ${entityName} '${entityId}' not found.`);
}
if (entityName === 'blobs' && entity.content !== null) {

View File

@ -200,7 +200,7 @@ function setNoteToParent(noteId, prefix, parentNoteId) {
const parentNote = becca.getNote(parentNoteId);
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
@ -224,7 +224,7 @@ function setNoteToParent(noteId, prefix, parentNoteId) {
const note = becca.getNote(noteId);
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]);

View File

@ -89,7 +89,7 @@ class SAttribute extends AbstractShacaEntity {
/** @returns {SNote|null} */
getTargetNote() {
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) {