0
Fork 0
mirror of https://github.com/withastro/astro.git synced 2025-02-10 22:38:53 -05:00

feat: cache getCollection() calls in production (#6503)

* feat: cache getCollection() in prod

* chore: changeset
This commit is contained in:
Ben Holmes 2023-03-10 13:50:34 -05:00 committed by GitHub
parent c44aa15534
commit f6eddffa04
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 34 additions and 20 deletions

View file

@ -0,0 +1,5 @@
---
'astro': patch
---
Add caching to `getCollection()` queries for faster SSG production builds

View file

@ -38,6 +38,7 @@ export function createCollectionToGlobResultMap({
return collectionToGlobResultMap; return collectionToGlobResultMap;
} }
const cacheEntriesByCollection = new Map<string, any[]>();
export function createGetCollection({ export function createGetCollection({
collectionToEntryMap, collectionToEntryMap,
collectionToRenderEntryMap, collectionToRenderEntryMap,
@ -47,7 +48,13 @@ export function createGetCollection({
}) { }) {
return async function getCollection(collection: string, filter?: (entry: any) => unknown) { return async function getCollection(collection: string, filter?: (entry: any) => unknown) {
const lazyImports = Object.values(collectionToEntryMap[collection] ?? {}); const lazyImports = Object.values(collectionToEntryMap[collection] ?? {});
const entries = Promise.all( 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) => { lazyImports.map(async (lazyImport) => {
const entry = await lazyImport(); const entry = await lazyImport();
return { return {
@ -66,8 +73,10 @@ export function createGetCollection({
}; };
}) })
); );
cacheEntriesByCollection.set(collection, entries);
}
if (typeof filter === 'function') { if (typeof filter === 'function') {
return (await entries).filter(filter); return entries.filter(filter);
} else { } else {
return entries; return entries;
} }