Notes/src/routes/api/relation-map.ts

79 lines
2.7 KiB
TypeScript
Raw Normal View History

2025-01-09 18:07:02 +02:00
import { Request } from "express";
import becca from "../../becca/becca.js";
import sql from "../../services/sql.js";
2023-04-14 16:49:06 +02:00
interface ResponseData {
noteTitles: Record<string, string>;
relations: {
2025-01-09 18:07:02 +02:00
attributeId: string;
sourceNoteId: string;
targetNoteId: string;
name: string;
}[];
inverseRelations: Record<string, string>;
}
function getRelationMap(req: Request) {
2025-01-09 18:07:02 +02:00
const { relationMapNoteId, noteIds } = req.body;
2023-04-14 16:49:06 +02:00
const resp: ResponseData = {
2023-04-14 16:49:06 +02:00
// noteId => title
noteTitles: {},
relations: [],
// relation name => inverse relation name
inverseRelations: {
2025-01-09 18:07:02 +02:00
internalLink: "internalLink"
2023-04-14 16:49:06 +02:00
}
};
if (!Array.isArray(noteIds) || noteIds.length === 0) {
2023-04-14 16:49:06 +02:00
return resp;
}
2025-01-09 18:07:02 +02:00
const questionMarks = noteIds.map((noteId) => "?").join(",");
2023-04-14 16:49:06 +02:00
const relationMapNote = becca.getNoteOrThrow(relationMapNoteId);
2023-04-14 16:49:06 +02:00
2025-01-09 18:07:02 +02:00
const displayRelationsVal = relationMapNote.getLabelValue("displayRelations");
const displayRelations = !displayRelationsVal ? [] : displayRelationsVal.split(",").map((token) => token.trim());
2023-04-14 16:49:06 +02:00
2025-01-09 18:07:02 +02:00
const hideRelationsVal = relationMapNote.getLabelValue("hideRelations");
const hideRelations = !hideRelationsVal ? [] : hideRelationsVal.split(",").map((token) => token.trim());
2023-04-14 16:49:06 +02:00
const foundNoteIds = sql.getColumn<string>(`SELECT noteId FROM notes WHERE isDeleted = 0 AND noteId IN (${questionMarks})`, noteIds);
2023-04-14 16:49:06 +02:00
const notes = becca.getNotes(foundNoteIds);
for (const note of notes) {
resp.noteTitles[note.noteId] = note.title;
2025-01-09 18:07:02 +02:00
resp.relations = resp.relations.concat(
note
.getRelations()
.filter((relation) => !relation.isAutoLink() || displayRelations.includes(relation.name))
.filter((relation) => (displayRelations.length > 0 ? displayRelations.includes(relation.name) : !hideRelations.includes(relation.name)))
.filter((relation) => noteIds.includes(relation.value))
.map((relation) => ({
attributeId: relation.attributeId,
sourceNoteId: relation.noteId,
targetNoteId: relation.value,
name: relation.name
}))
);
2023-04-14 16:49:06 +02:00
for (const relationDefinition of note.getRelationDefinitions()) {
const def = relationDefinition.getDefinition();
if (def.inverseRelation) {
resp.inverseRelations[relationDefinition.getDefinedName()] = def.inverseRelation;
resp.inverseRelations[def.inverseRelation] = relationDefinition.getDefinedName();
}
}
}
return resp;
}
export default {
2023-04-14 16:49:06 +02:00
getRelationMap
};