Notes/src/routes/api/link_map.js

59 lines
1.5 KiB
JavaScript
Raw Normal View History

2019-06-03 22:55:59 +02:00
"use strict";
const sql = require('../../services/sql');
2019-08-27 22:47:10 +02:00
async function getRelations(noteIds) {
return (await sql.getManyRows(`
2019-08-19 20:12:00 +02:00
SELECT noteId, name, value AS targetNoteId
2019-06-03 22:55:59 +02:00
FROM attributes
WHERE (noteId IN (???) OR value IN (???))
AND type = 'relation'
AND isDeleted = 0
2019-08-27 22:47:10 +02:00
AND noteId != ''
AND value != ''
2019-08-19 20:19:42 +02:00
`, Array.from(noteIds)));
2019-06-03 22:55:59 +02:00
}
async function getLinkMap(req) {
const {noteId} = req.params;
2019-08-19 20:19:42 +02:00
const {maxNotes, maxDepth} = req.body;
2019-06-03 22:55:59 +02:00
let noteIds = new Set([noteId]);
2019-08-19 20:12:00 +02:00
let relations;
2019-06-03 22:55:59 +02:00
2019-07-24 22:52:51 +02:00
let depth = 0;
2019-06-03 22:55:59 +02:00
while (true) {
2019-08-19 20:19:42 +02:00
relations = await getRelations(noteIds);
2019-07-24 22:52:51 +02:00
if (depth === maxDepth) {
break;
}
2019-08-19 20:12:00 +02:00
const newNoteIds = new Set(relations.map(rel => rel.noteId)
.concat(relations.map(rel => rel.targetNoteId)));
2019-06-03 22:55:59 +02:00
2019-06-04 22:57:10 +02:00
if (newNoteIds.size === noteIds.size) {
2019-06-03 22:55:59 +02:00
// no new note discovered, no need to search any further
break;
}
2019-08-27 22:47:10 +02:00
console.log(newNoteIds.size, maxNotes);
if (newNoteIds.size > maxNotes) {
2019-08-27 22:47:10 +02:00
// too many notes to display
2019-06-03 22:55:59 +02:00
break;
}
noteIds = newNoteIds;
2019-07-24 22:52:51 +02:00
depth++;
2019-06-03 22:55:59 +02:00
}
// keep only links coming from and targetting some note in the noteIds set
2019-08-19 20:12:00 +02:00
relations = relations.filter(rel => noteIds.has(rel.noteId) && noteIds.has(rel.targetNoteId));
2019-06-03 22:55:59 +02:00
2019-08-19 20:12:00 +02:00
return relations;
2019-06-03 22:55:59 +02:00
}
module.exports = {
getLinkMap
};