Notes/src/routes/api/link_map.js

85 lines
2.1 KiB
JavaScript
Raw Normal View History

2019-06-03 22:55:59 +02:00
"use strict";
2021-05-31 23:38:47 +02:00
const becca = require("../../becca/becca");
2019-06-03 22:55:59 +02:00
2021-05-31 23:38:47 +02:00
function getRelations(noteId) {
const note = becca.getNote(noteId);
2019-06-03 22:55:59 +02:00
2021-05-31 23:38:47 +02:00
if (!note) {
throw new Error(noteId);
}
2019-06-03 22:55:59 +02:00
2021-05-31 23:38:47 +02:00
const allRelations = note.getOwnedRelations().concat(note.getTargetRelations());
2019-07-24 22:52:51 +02:00
2021-05-31 23:38:47 +02:00
return allRelations.filter(rel => {
if (rel.name === 'relationMapLink' || rel.name === 'template') {
return false;
}
else if (rel.name === 'imageLink') {
const parentNote = becca.getNote(rel.noteId);
2019-07-24 22:52:51 +02:00
2021-05-31 23:38:47 +02:00
return !parentNote.getChildNotes().find(childNote => childNote.noteId === rel.value);
}
else {
return true;
2019-07-24 22:52:51 +02:00
}
2021-05-31 23:38:47 +02:00
});
}
2019-07-24 22:52:51 +02:00
2021-05-31 23:38:47 +02:00
function collectRelations(noteId, relations, depth) {
if (depth === 0) {
return;
}
2019-06-03 22:55:59 +02:00
2021-05-31 23:38:47 +02:00
for (const relation of getRelations(noteId)) {
if (!relations.has(relation)) {
if (!relation.value) {
continue;
}
2021-05-31 23:38:47 +02:00
relations.add(relation);
2019-06-03 22:55:59 +02:00
2021-05-31 23:38:47 +02:00
if (relation.noteId !== noteId) {
2021-06-01 22:03:38 +02:00
collectRelations(relation.noteId, relations, depth - 1);
2021-05-31 23:38:47 +02:00
} else if (relation.value !== noteId) {
2021-06-01 22:03:38 +02:00
collectRelations(relation.value, relations, depth - 1);
}
}
2019-06-03 22:55:59 +02:00
}
2021-05-31 23:38:47 +02:00
}
function getLinkMap(req) {
const {noteId} = req.params;
const {maxDepth} = req.body;
let relations = new Set();
2019-06-03 22:55:59 +02:00
2021-05-31 23:38:47 +02:00
collectRelations(noteId, relations, maxDepth);
relations = Array.from(relations);
const noteIds = new Set(relations.map(rel => rel.noteId)
.concat(relations.map(rel => rel.targetNoteId))
.concat([noteId]));
const noteIdToLinkCountMap = {};
for (const noteId of noteIds) {
noteIdToLinkCountMap[noteId] = getRelations(noteId).length;
}
2019-06-03 22:55:59 +02:00
2021-05-31 23:38:47 +02:00
return {
noteIdToLinkCountMap,
links: Array.from(relations).map(rel => ({
2021-06-01 22:03:38 +02:00
id: rel.noteId + "-" + rel.name + "-" + rel.value,
2021-05-31 23:38:47 +02:00
sourceNoteId: rel.noteId,
targetNoteId: rel.value,
name: rel.name
}))
};
2019-06-03 22:55:59 +02:00
}
module.exports = {
getLinkMap
2020-06-20 12:31:38 +02:00
};