Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(utils): flat routes if child routes have absolute paths #7604

Merged
merged 1 commit into from Jun 25, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
15 changes: 10 additions & 5 deletions packages/utils/src/route.js
Expand Up @@ -13,14 +13,19 @@ export const flatRoutes = function flatRoutes (router, fileName = '', routes = [
if (fileName === '' && r.path === '/') {
routes.push('/')
}

return flatRoutes(r.children, fileName + r.path + '/', routes)
}
fileName = fileName.replace(/\/+/g, '/')
routes.push(
(r.path === '' && fileName[fileName.length - 1] === '/'
? fileName.slice(0, -1)
: fileName) + r.path
)

// if child path is already absolute, do not make any concatenations
if (r.path && r.path.startsWith('/')) {
routes.push(r.path)
} else if (r.path === '' && fileName[fileName.length - 1] === '/') {
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think plain old if-else is more readable than ternary operator with some parentness.

routes.push(fileName.slice(0, -1) + r.path)
} else {
routes.push(fileName + r.path)
}
})
return routes
}
Expand Down
31 changes: 31 additions & 0 deletions packages/utils/test/route.test.js
Expand Up @@ -40,6 +40,37 @@ describe('util: route', () => {
expect(routes).toEqual(['/', '/foo/bar', '/foo/baz'])
})

test('should flat absolute routes', () => {
const routes = flatRoutes([
{
name: 'foo',
path: '/foo',
children: [
{ name: 'foo-bar', path: '/foo/bar' },
{ name: 'foo-baz', path: '/foo/baz' }
]
}
])

expect(routes).toEqual(['/foo/bar', '/foo/baz'])
})

test('should flat absolute routes with empty path', () => {
const routes = flatRoutes([
{
name: 'foo',
path: '/foo',
children: [
{ name: 'foo-root', path: '' },
{ name: 'foo-bar', path: '/foo/bar' },
{ name: 'foo-baz', path: '/foo/baz' }
]
}
])

expect(routes).toEqual(['/foo', '/foo/bar', '/foo/baz'])
})

describe('util: route guard', () => {
test('should guard parent dir', () => {
expect(() => {
Expand Down