From 842561d2b834ea5e2d640c635b135f531dd09349 Mon Sep 17 00:00:00 2001 From: Nils-Johan Gynther Date: Sun, 3 May 2026 14:11:30 +0200 Subject: [PATCH] refactor(categories-service): optimize path building in findFlattened method --- backend/src/categories/categories.service.ts | 25 +++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/backend/src/categories/categories.service.ts b/backend/src/categories/categories.service.ts index 99e6d3ae..7b00276b 100644 --- a/backend/src/categories/categories.service.ts +++ b/backend/src/categories/categories.service.ts @@ -39,12 +39,31 @@ export class CategoriesService { async findFlattened(): Promise { const all = await this.prisma.category.findMany({ orderBy: { name: 'asc' } }); - const nameMap = new Map(); - all.forEach((c) => nameMap.set(c.id, c.name)); + + const byId = new Map(); + all.forEach((c) => byId.set(c.id, c)); + + const pathCache = new Map(); + + const buildPath = (id: number): string => { + const cached = pathCache.get(id); + if (cached) return cached; + + const current = byId.get(id); + if (!current) return ''; + + const path = current.parentId == null + ? current.name + : `${buildPath(current.parentId)} > ${current.name}`; + + pathCache.set(id, path); + return path; + }; + return all.map((c) => ({ id: c.id, name: c.name, - path: c.parentId ? `${nameMap.get(c.parentId) ?? ''} > ${c.name}` : c.name, + path: buildPath(c.id), })); } }