diff --git a/src/utils/__tests__/data.test.ts b/src/utils/__tests__/data.test.ts new file mode 100644 index 0000000..525645f --- /dev/null +++ b/src/utils/__tests__/data.test.ts @@ -0,0 +1,39 @@ +import { getFullPath } from '../data'; + +describe('getFullPath', () => { + test('should return just the path if parentId is root', () => { + const path = getFullPath('admin.users.$id', { + root: { + path: '' + }, + 'admin.users.$id': { + parentId: 'root', + path: 'admin/users/:id' + } + }); + + expect(path).toBe('admin/users/:id'); + }); + + test('should return the full path of a route with multiple parents', () => { + const path = getFullPath('blog.post.$id', { + root: { + path: '' + }, + blog: { + parentId: 'root', + path: 'blog' + }, + 'blog.post': { + parentId: 'blog', + path: 'post' + }, + 'blog.post.$id': { + parentId: 'blog.post', + path: ':id' + } + }); + + expect(path).toBe('blog/post/:id'); + }); +}); diff --git a/src/utils/data.ts b/src/utils/data.ts index 073a41b..18c1b0a 100644 --- a/src/utils/data.ts +++ b/src/utils/data.ts @@ -22,8 +22,7 @@ export function getRouteData(route: string, context: EntryContext) { } : undefined; - const path = - !manifest.path && manifest.parentId === 'root' ? '' : manifest?.path; + const path = getFullPath(route, context.manifest.routes); const parents = manifest.id?.split('/').slice(0, -1); @@ -44,6 +43,17 @@ export function getRouteData(route: string, context: EntryContext) { }; } +export function getFullPath( + route: string, + routes: Record +): string | undefined { + const manifest = routes[route]; + + if (!manifest.parentId || manifest.parentId === 'root') return manifest.path; + + return `${getFullPath(manifest.parentId, routes)}/${manifest.path}`; +} + type GetOptionalSegmentDataParams = { route: string; context: EntryContext;