Fix collections regex (#557)

* fix: 🐛 Fixes bug #532

Matching for collection routes should look for exact filename matches

* test:  Adding test coverage to make sure collection routes are matched exactly

* chore: Adding changeset
This commit is contained in:
Tony @ Navillus 2021-06-28 13:22:15 +02:00 committed by GitHub
parent 11cf22999d
commit aa8605761b
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 44 additions and 1 deletions

View file

@ -0,0 +1,5 @@
---
'astro': patch
---
Updates collections to match URLs by exact template filename

View file

@ -115,7 +115,7 @@ export function searchForPage(url: URL, astroConfig: AstroConfig): SearchResult
function loadCollection(url: string, astroConfig: AstroConfig): { currentPage?: number; location: PageLocation } | undefined {
const pages = glob('**/$*.astro', { cwd: fileURLToPath(astroConfig.pages), filesOnly: true });
for (const pageURL of pages) {
const reqURL = new RegExp('^/' + pageURL.replace(/\$([^/]+)\.astro/, '$1') + '/?(.*)');
const reqURL = new RegExp('^/' + pageURL.replace(/\$([^/]+)\.astro/, '$1') + '(?:\/(.*)|\/?$)');
const match = url.match(reqURL);
if (match) {
let currentPage: number | undefined;

View file

@ -109,4 +109,18 @@ Collections('generates individual pages from a collection', async ({ runtime })
}
});
Collections('matches collection filename exactly', async ({ runtime }) => {
const result = await runtime.load('/individuals');
if (result.error) throw new Error(result.error);
const $ = doc(result.contents);
assert.ok($('#posts').length);
const urls = [
...$('#posts a').map(function () {
return $(this).attr('href');
}),
];
assert.equal(urls, ['/post/nested/a', '/post/three', '/post/two', '/post/one']);
});
Collections.run();

View file

@ -0,0 +1,24 @@
---
const { collection } = Astro.props;
export async function createCollection() {
return {
async data() {
let data = Astro.fetchContent('./post/**/*.md');
data.sort((a, b) => new Date(b.date) - new Date(a.date));
return data;
},
pageSize: 10
};
}
---
<div id="posts">
{collection.data.map((post) => (
<article>
<h1>{post.title}</h1>
<a href={post.url}>Read more</a>
</article>
))}
</div>