From c6e3834cc4edf52a20e422cd9af5c69805fa0651 Mon Sep 17 00:00:00 2001 From: Maxime Thirouin Date: Thu, 23 Feb 2017 11:43:24 +0100 Subject: [PATCH] Added: better support of react-router routes (IndexRoute and trailing slashes) --- src/static/routes-to-urls/__tests__/index.js | 10 +++++++--- src/static/routes-to-urls/index.js | 19 ++++++++++++++----- 2 files changed, 21 insertions(+), 8 deletions(-) diff --git a/src/static/routes-to-urls/__tests__/index.js b/src/static/routes-to-urls/__tests__/index.js index 12a528ea4..5c208aac6 100644 --- a/src/static/routes-to-urls/__tests__/index.js +++ b/src/static/routes-to-urls/__tests__/index.js @@ -1,7 +1,7 @@ // @ flow import React from "react" -import { Route } from "react-router" +import { Route, IndexRoute } from "react-router" import routesToUrls from "../index.js" @@ -56,10 +56,13 @@ const collection: PhenomicCollection = [ const routes = ( - + + + + - + @@ -75,6 +78,7 @@ it("generate a list of routes based on tags", () => { urls ).toEqual( [ + "/author", "/author/Jack", "/author/James", "/author/John", diff --git a/src/static/routes-to-urls/index.js b/src/static/routes-to-urls/index.js index 45fa065f6..9f6e25bb4 100644 --- a/src/static/routes-to-urls/index.js +++ b/src/static/routes-to-urls/index.js @@ -9,14 +9,18 @@ import arrayUnique from "../../_utils/array-unique" const defaultConsole = console.log const flattenRoute = (route) => { - const root = route.path ? route.path : "" + // @todo remove the default route.path, user should use IndexRoute instead? let routesUrls = route.path ? [ route.path ] : [] + if (route.indexRoute) { + routesUrls.push(route.path) + } if (route.childRoutes) { + const root = route.path route.childRoutes.forEach((route) => { routesUrls = [ ...routesUrls, - ...flattenRoute(route).map((r) => urlJoin(root, r)), + ...flattenRoute(route).map((r) => root ? urlJoin(root, r) : r), ] }) } @@ -153,8 +157,9 @@ export default ( // for testing log: Function = defaultConsole, ): Array => { - const flattenedRoutes = createRoutes(routes) - .reduce((acc, r) => [ ...acc, ...flattenRoute(r) ], []) + const flattenedRoutes = arrayUnique( + createRoutes(routes).reduce((acc, r) => [ ...acc, ...flattenRoute(r) ], []) + ) if (flattenedRoutes.filter((url) => url.indexOf("*") > -1).length > 1) { throw new Error( @@ -165,5 +170,9 @@ export default ( ) } - return hydrateRoutesUrls(flattenedRoutes, collection, log) + const normalizedRoutes = flattenedRoutes.map( + (route) => "/" + route.replace(/^\/+/, "").replace(/\/+$/, "") + ) + + return hydrateRoutesUrls(normalizedRoutes, collection, log) }