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

Allow dynamic segments in injected routes #5331

Merged
merged 3 commits into from Nov 8, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
5 changes: 5 additions & 0 deletions .changeset/good-ghosts-attack.md
@@ -0,0 +1,5 @@
---
'astro': patch
---

Allow dynamic segments in injected routes
18 changes: 7 additions & 11 deletions packages/astro/src/core/routing/manifest/create.ts
Expand Up @@ -352,7 +352,12 @@ export function createRouteManifest(
)
.reverse() // prepend to the routes array from lowest to highest priority
.forEach(({ pattern: name, entryPoint }) => {
const resolved = require.resolve(entryPoint, { paths: [cwd || fileURLToPath(config.root)] });
let resolved: string;
try {
resolved = require.resolve(entryPoint, { paths: [cwd || fileURLToPath(config.root)] });
} catch(e) {
resolved = fileURLToPath(new URL(entryPoint, config.root));
}
const component = slash(path.relative(cwd || fileURLToPath(config.root), resolved));

const isDynamic = (str: string) => str?.[0] === '[';
Expand All @@ -363,16 +368,7 @@ export function createRouteManifest(
.filter(Boolean)
.map((s: string) => {
validateSegment(s);

const dynamic = isDynamic(s);
const content = dynamic ? normalize(s) : s;
return [
{
content,
dynamic,
spread: isSpread(s),
},
];
return getParts(s, resolved);
});

const type = resolved.endsWith('.astro') ? 'page' : 'endpoint';
Expand Down
45 changes: 45 additions & 0 deletions packages/astro/test/units/dev/dev.test.js
Expand Up @@ -106,4 +106,49 @@ describe('dev container', () => {
expect($('body.two')).to.have.a.lengthOf(1);
});
});

it('Allows dynamic segments in injected routes', async () => {
const fs = createFs({
'/src/components/test.astro': `<h1>{Astro.params.slug}</h1>`,
'/src/pages/test-[slug].astro': `<h1>{Astro.params.slug}</h1>`,
},
root
);

await runInContainer({
fs,
root,
userConfig: {
output: 'server',
integrations: [{
name: '@astrojs/test-integration',
hooks: {
'astro:config:setup': ({ injectRoute }) => {
injectRoute({
pattern: '/another-[slug]',
entryPoint: './src/components/test.astro',
});
},
},
}]
}
}, async (container) => {
let r = createRequestAndResponse({
method: 'GET',
url: '/test-one',
});
container.handle(r.req, r.res);
await r.done;
expect(r.res.statusCode).to.equal(200);

// Try with the injected route
r = createRequestAndResponse({
method: 'GET',
url: '/another-two',
});
container.handle(r.req, r.res);
await r.done;
expect(r.res.statusCode).to.equal(200);
});
});
});