obsidian-visualiser/server/api/project/[projectId]/navigation.get.ts

70 lines
1.9 KiB
TypeScript

import useDatabase from '~/composables/useDatabase';
import { Navigation } from '~/types/api';
export default defineEventHandler(async (e) => {
const project = getRouterParam(e, "projectId");
const { user } = await getUserSession(e);
if(!project)
{
setResponseStatus(e, 404);
return;
}
const db = useDatabase();
const content = db.query(`SELECT "path", "title", "type", "order", "private", "navigable", "owner" FROM explorer_files WHERE project = ?1`).all(project!).sort((a: any, b: any) => a.path.length - b.path.length) as Navigation[];
if(content.length > 0)
{
const navigation: Navigation[] = [];
for(const idx in content)
{
const item = content[idx];
if(!!item.private && (user?.id ?? -1) !== item.owner || !item.navigable)
{
delete content[idx];
continue;
}
const parent = item.path.includes('/') ? item.path.substring(0, item.path.lastIndexOf('/')) : undefined;
if(parent && !content.find(e => e && e.path === parent))
{
delete content[idx];
continue;
}
}
for(const item of content.filter(e => !!e))
{
addChild(navigation, item);
}
return navigation;
}
setResponseStatus(e, 404);
});
function addChild(arr: Navigation[], e: Navigation): void
{
const parent = arr.find(f => e.path.startsWith(f.path));
if(parent)
{
if(!parent.children)
parent.children = [];
addChild(parent.children, e);
}
else
{
arr.push({ title: e.title, path: e.path, type: e.type, order: e.order, private: e.private });
arr.sort((a, b) => {
if(a.order && b.order)
return a.order - b.order;
return a.title.localeCompare(b.title);
});
}
}