Fix routing behavior when getStaticPaths params include hyphens (#7694)

This commit is contained in:
Nate Moore 2023-07-18 04:36:43 -05:00 committed by GitHub
parent d80e5fcf8e
commit 06c255716a
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 19 additions and 7 deletions

View file

@ -0,0 +1,5 @@
---
'astro': patch
---
Fix route matching behavior when `getStaticPaths` result includes hyphenated params

View file

@ -71,7 +71,7 @@ export async function callGetStaticPaths({
keyedStaticPaths.keyed = new Map<string, GetStaticPathsItem>();
for (const sp of keyedStaticPaths) {
const paramsKey = stringifyParams(sp.params, route.component);
const paramsKey = stringifyParams(sp.params, route);
keyedStaticPaths.keyed.set(paramsKey, sp);
}
@ -127,7 +127,7 @@ export function findPathItemByKey(
params: Params,
route: RouteData
) {
const paramsKey = stringifyParams(params, route.component);
const paramsKey = stringifyParams(params, route);
const matchedStaticPath = staticPaths.keyed.get(paramsKey);
if (matchedStaticPath) {
return matchedStaticPath;

View file

@ -1,4 +1,4 @@
import type { GetStaticPathsItem, Params } from '../../@types/astro';
import type { GetStaticPathsItem, RouteData, Params } from '../../@types/astro';
import { validateGetStaticPathsParameter } from './validation.js';
/**
@ -27,15 +27,14 @@ export function getParams(array: string[]) {
* values and create a stringified key for the route
* that can be used to match request routes
*/
export function stringifyParams(params: GetStaticPathsItem['params'], routeComponent: string) {
export function stringifyParams(params: GetStaticPathsItem['params'], route: RouteData) {
// validate parameter values then stringify each value
const validatedParams = Object.entries(params).reduce((acc, next) => {
validateGetStaticPathsParameter(next, routeComponent);
validateGetStaticPathsParameter(next, route.component);
const [key, value] = next;
acc[key] = value?.toString();
return acc;
}, {} as Params);
// Always sort keys before stringifying to make sure objects match regardless of parameter ordering
return JSON.stringify(validatedParams, Object.keys(params).sort());
return JSON.stringify(route.generate(validatedParams))
}

View file

@ -126,4 +126,9 @@ describe('getStaticPaths - dev calls', () => {
);
}
});
it('properly handles hyphenation in getStaticPaths', async () => {
const res = await fixture.fetch('/pizza/parmesan-and-olives');
expect(res.status).to.equal(200);
});
});

View file

@ -4,6 +4,9 @@ export function getStaticPaths() {
params: { cheese: 'mozzarella', topping: 'pepperoni' },
}, {
params: { cheese: 'provolone', topping: 'sausage' },
}, {
// fix(#7265): hyphenated behavior
params: { cheese: 'parmesan-and', topping: 'olives' },
}]
}
const { cheese, topping } = Astro.params