summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorGravatar Ben Holmes <hey@bholmes.dev> 2023-03-10 13:50:34 -0500
committerGravatar GitHub <noreply@github.com> 2023-03-10 13:50:34 -0500
commitf6eddffa0414d54767e9f9e1ee5a936b8a20146b (patch)
tree7676a81fb09426b4bde0bf02ff99e0e0d382d512
parentc44aa15534007c3ac320fa6e632c760ddb2ce2f3 (diff)
downloadastro-f6eddffa0414d54767e9f9e1ee5a936b8a20146b.tar.gz
astro-f6eddffa0414d54767e9f9e1ee5a936b8a20146b.tar.zst
astro-f6eddffa0414d54767e9f9e1ee5a936b8a20146b.zip
feat: cache `getCollection()` calls in production (#6503)
* feat: cache getCollection() in prod * chore: changeset
-rw-r--r--.changeset/nasty-cougars-double.md5
-rw-r--r--packages/astro/src/content/internal.ts49
2 files changed, 34 insertions, 20 deletions
diff --git a/.changeset/nasty-cougars-double.md b/.changeset/nasty-cougars-double.md
new file mode 100644
index 000000000..1f83bf9b1
--- /dev/null
+++ b/.changeset/nasty-cougars-double.md
@@ -0,0 +1,5 @@
+---
+'astro': patch
+---
+
+Add caching to `getCollection()` queries for faster SSG production builds
diff --git a/packages/astro/src/content/internal.ts b/packages/astro/src/content/internal.ts
index bdc99bbc7..951a52f6d 100644
--- a/packages/astro/src/content/internal.ts
+++ b/packages/astro/src/content/internal.ts
@@ -38,6 +38,7 @@ export function createCollectionToGlobResultMap({
return collectionToGlobResultMap;
}
+const cacheEntriesByCollection = new Map<string, any[]>();
export function createGetCollection({
collectionToEntryMap,
collectionToRenderEntryMap,
@@ -47,27 +48,35 @@ export function createGetCollection({
}) {
return async function getCollection(collection: string, filter?: (entry: any) => unknown) {
const lazyImports = Object.values(collectionToEntryMap[collection] ?? {});
- const entries = Promise.all(
- lazyImports.map(async (lazyImport) => {
- const entry = await lazyImport();
- return {
- id: entry.id,
- slug: entry.slug,
- body: entry.body,
- collection: entry.collection,
- data: entry.data,
- async render() {
- return render({
- collection: entry.collection,
- id: entry.id,
- collectionToRenderEntryMap,
- });
- },
- };
- })
- );
+ let entries: any[] = [];
+ // Cache `getCollection()` calls in production only
+ // prevents stale cache in development
+ if (import.meta.env.PROD && cacheEntriesByCollection.has(collection)) {
+ entries = cacheEntriesByCollection.get(collection)!;
+ } else {
+ entries = await Promise.all(
+ lazyImports.map(async (lazyImport) => {
+ const entry = await lazyImport();
+ return {
+ id: entry.id,
+ slug: entry.slug,
+ body: entry.body,
+ collection: entry.collection,
+ data: entry.data,
+ async render() {
+ return render({
+ collection: entry.collection,
+ id: entry.id,
+ collectionToRenderEntryMap,
+ });
+ },
+ };
+ })
+ );
+ cacheEntriesByCollection.set(collection, entries);
+ }
if (typeof filter === 'function') {
- return (await entries).filter(filter);
+ return entries.filter(filter);
} else {
return entries;
}