refactor(categories-service): optimize path building in findFlattened method
This commit is contained in:
@@ -39,12 +39,31 @@ export class CategoriesService {
|
||||
|
||||
async findFlattened(): Promise<FlatCategory[]> {
|
||||
const all = await this.prisma.category.findMany({ orderBy: { name: 'asc' } });
|
||||
const nameMap = new Map<number, string>();
|
||||
all.forEach((c) => nameMap.set(c.id, c.name));
|
||||
|
||||
const byId = new Map<number, { id: number; name: string; parentId: number | null }>();
|
||||
all.forEach((c) => byId.set(c.id, c));
|
||||
|
||||
const pathCache = new Map<number, string>();
|
||||
|
||||
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),
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user