Skip to content

Commit

Permalink
Fix getCollection return new instance in prod (#8022)
Browse files Browse the repository at this point in the history
  • Loading branch information
bluwy authored Aug 10, 2023
1 parent 86bee28 commit c23377c
Show file tree
Hide file tree
Showing 4 changed files with 45 additions and 1 deletion.
5 changes: 5 additions & 0 deletions .changeset/smart-nails-push.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'astro': patch
---

Always return a new array instance from `getCollection` in prod
3 changes: 2 additions & 1 deletion packages/astro/src/content/runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,8 @@ export function createGetCollection({
// Cache `getCollection()` calls in production only
// prevents stale cache in development
if (import.meta.env.PROD && cacheEntriesByCollection.has(collection)) {
entries = cacheEntriesByCollection.get(collection)!;
// Always return a new instance so consumers can safely mutate it
entries = [...cacheEntriesByCollection.get(collection)!]
} else {
entries = await Promise.all(
lazyImports.map(async (lazyImport) => {
Expand Down
16 changes: 16 additions & 0 deletions packages/astro/test/content-collections-render.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,22 @@ describe('Content Collections - render()', () => {
expect(h2).to.have.a.lengthOf(1);
expect(h2.attr('data-components-export-applied')).to.equal('true');
});

it('getCollection should return new instances of the array to be mutated safely', async () => {
const app = await fixture.loadTestAdapterApp();

let request = new Request('http://example.com/sort-blog-collection');
let response = await app.render(request);
let html = await response.text();
let $ = cheerio.load(html);
expect($('li').first().text()).to.equal('With Layout Prop');

request = new Request('http://example.com/');
response = await app.render(request);
html = await response.text();
$ = cheerio.load(html);
expect($('li').first().text()).to.equal('Hello world');
})
});

describe('Dev - SSG', () => {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
---
import { getCollection } from 'astro:content';
const blog = await getCollection('blog');
// Sort descending by title, make sure mutating `blog` doesn't mutate other pages that call `getCollection` too
blog.sort((a, b) => a.data.title < b.data.title ? 1 : -1)
---
<html>
<head>
<title>Index</title>
</head>
<body>
<h1>Blog Posts</h1>

<ul>
{blog.map(post => (
<li>{ post.data.title }</li>
))}
</ul>
</body>
</html>

0 comments on commit c23377c

Please sign in to comment.