import useDatabase from '~/composables/useDatabase'; import { explorerContentTable } from '~/db/schema'; import type { NavigationItem } from '~/schemas/navigation'; export type NavigationTreeItem = NavigationItem & { children?: NavigationItem[] }; export default defineEventHandler(async (e) => { const { user } = await getUserSession(e); /*if(!user) { throw createError({ statusCode: 401, statusText: 'Unauthorized' }); }*/ const db = useDatabase(); const content = db.select({ path: explorerContentTable.path, type: explorerContentTable.type, owner: explorerContentTable.owner, title: explorerContentTable.title, navigable: explorerContentTable.navigable, private: explorerContentTable.private, order: explorerContentTable.order, }).from(explorerContentTable).prepare().all(); if(content.length > 0) { const navigation: NavigationTreeItem[] = []; 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: NavigationTreeItem[], e: NavigationItem): 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({ ...e }); arr.sort((a, b) => { if(a.order && b.order) return a.order - b.order; return a.title.localeCompare(b.title); }); } }