Skip to content

Commit

Permalink
fix(gatsby-plugin-page-creator): support index routes when using the …
Browse files Browse the repository at this point in the history
…File System Route API (#31339)

Co-authored-by: LekoArts <lekoarts@gmail.com>
  • Loading branch information
angeloashmore and LekoArts committed May 11, 2021
1 parent 844c19e commit 6ad990c
Show file tree
Hide file tree
Showing 2 changed files with 79 additions and 0 deletions.
68 changes: 68 additions & 0 deletions packages/gatsby-plugin-page-creator/src/__tests__/derive-path.ts
Expand Up @@ -265,6 +265,74 @@ describe(`derive-path`, () => {
).toEqual(`foo/dolores/[...name]`)
})

it(`supports index paths`, () => {
expect(
derivePath(
`{Page.path}`,
{
path: `/`,
},
reporter
).derivedPath
).toEqual(`index`)
expect(
derivePath(
`{Page.path}.js`,
{
path: `/`,
},
reporter
).derivedPath
).toEqual(`index.js`)
expect(
derivePath(
`foo/{Page.path}`,
{
path: `/`,
},
reporter
).derivedPath
).toEqual(`foo`)
expect(
derivePath(
`foo/{Page.path}/bar`,
{
path: `/`,
},
reporter
).derivedPath
).toEqual(`foo/bar`)
expect(
derivePath(
`foo/{Page.pathOne}/{Page.pathTwo}`,
{
pathOne: `/`,
pathTwo: `bar`,
},
reporter
).derivedPath
).toEqual(`foo/bar`)
expect(
derivePath(
`foo/{Page.pathOne}/{Page.pathTwo}`,
{
pathOne: `/`,
pathTwo: `/bar`,
},
reporter
).derivedPath
).toEqual(`foo/bar`)
expect(
derivePath(
`foo/{Page.path}/[...name]`,
{
path: `/`,
},
reporter
).derivedPath
).toEqual(`foo/[...name]`)
})

it(`handles special chars`, () => {
expect(
derivePath(
Expand Down
11 changes: 11 additions & 0 deletions packages/gatsby-plugin-page-creator/src/derive-path.ts
Expand Up @@ -6,9 +6,12 @@ import {
extractAllCollectionSegments,
switchToPeriodDelimiters,
stripTrailingSlash,
removeFileExtension,
} from "./path-utils"

const doubleForwardSlashes = /\/\/+/g
// Match 0 or 1 of "/"
const indexRoute = /^\/?$/

// Generates the path for the page from the file path
// product/{Product.id} => /product/:id, pulls from nodes.id
Expand Down Expand Up @@ -64,6 +67,14 @@ export function derivePath(
// 4. Remove double forward slashes that could occur in the final URL
modifiedPath = modifiedPath.replace(doubleForwardSlashes, `/`)

// 5. Remove trailing slashes that could occur in the final URL
modifiedPath = stripTrailingSlash(modifiedPath)

// 6. If the final URL appears to be an index path, use the "index" file naming convention
if (indexRoute.test(removeFileExtension(modifiedPath))) {
modifiedPath = `index${modifiedPath}`
}

const derivedPath = modifiedPath

return {
Expand Down

0 comments on commit 6ad990c

Please sign in to comment.