Remove AstroError if content directory is empty (#8382)

Co-authored-by: Emanuele Stoppa <my.burning@gmail.com>
This commit is contained in:
Timon Jurschitsch 2023-09-21 10:34:20 +02:00 committed by GitHub
parent 4398e92987
commit e522a5eb41
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
7 changed files with 70 additions and 4 deletions

View file

@ -0,0 +1,5 @@
---
'astro': patch
---
Do not throw an error for an empty collection directory.

View file

@ -13,6 +13,7 @@ import {
type AstroComponentFactory,
} from '../runtime/server/index.js';
import type { ContentLookupMap } from './utils.js';
import type { AstroIntegration } from '../@types/astro.js';
type LazyImport = () => Promise<any>;
type GlobResult = Record<string, LazyImport>;
@ -55,10 +56,7 @@ export function createGetCollection({
} else if (collection in dataCollectionToEntryMap) {
type = 'data';
} else {
throw new AstroError({
...AstroErrorData.CollectionDoesNotExistError,
message: AstroErrorData.CollectionDoesNotExistError.message(collection),
});
return warnOfEmptyCollection(collection)
}
const lazyImports = Object.values(
type === 'content'
@ -392,3 +390,16 @@ type PropagatedAssetsModule = {
function isPropagatedAssetsModule(module: any): module is PropagatedAssetsModule {
return typeof module === 'object' && module != null && '__astroPropagation' in module;
}
function warnOfEmptyCollection(collection: string): AstroIntegration {
return {
name: 'astro-collection',
hooks: {
'astro:server:start': ({ logger }) => {
logger.warn(
`The collection **${collection}** does not exist or is empty. Ensure a collection directory with this name exists.`
);
},
},
};
}

View file

@ -244,6 +244,22 @@ describe('Content Collections', () => {
});
});
describe('With empty collections directory', () => {
it('Handles the empty directory correclty', async () => {
const fixture = await loadFixture({
root: './fixtures/content-collections-empty-dir/'
});
let error;
try {
await fixture.build();
} catch (e) {
error = e.message;
}
expect(error).to.be.undefined;
// TODO: try to render a page
})
})
describe('SSR integration', () => {
let app;

View file

@ -0,0 +1,9 @@
{
"name": "@test/content-collections-empty-dir",
"version": "0.0.0",
"private": true,
"type": "module",
"dependencies": {
"astro": "workspace:*"
}
}

View file

@ -0,0 +1,11 @@
import { z, defineCollection } from 'astro:content';
const blog = defineCollection({
schema: z.object({
title: z.string(),
}),
});
export const collections = {
blog,
};

View file

@ -0,0 +1,8 @@
---
import { getCollection } from 'astro:content'
const blogs = await getCollection("blogs")
// console.log(blogs)
---
<p>This should still render</p>

View file

@ -2367,6 +2367,12 @@ importers:
specifier: workspace:*
version: link:../../..
packages/astro/test/fixtures/content-collections-empty-dir:
dependencies:
astro:
specifier: workspace:*
version: link:../../..
packages/astro/test/fixtures/content-collections-empty-md-file:
dependencies:
astro: