Skip to content

Commit

Permalink
fix: make reference() a sync transform (#12781)
Browse files Browse the repository at this point in the history
  • Loading branch information
ascorbic authored Jan 2, 2025
1 parent f706899 commit 96c4b92
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 4 deletions.
5 changes: 5 additions & 0 deletions .changeset/fluffy-ants-reflect.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'astro': patch
---

Fixes a regression that caused `default()` to not work with `reference()`
17 changes: 14 additions & 3 deletions packages/astro/src/content/runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import {
unescapeHTML,
} from '../runtime/server/index.js';
import { CONTENT_LAYER_TYPE, IMAGE_IMPORT_PREFIX } from './consts.js';
import { type DataEntry, globalDataStore } from './data-store.js';
import { type DataEntry, type ImmutableDataStore, globalDataStore } from './data-store.js';
import type { ContentLookupMap } from './utils.js';

type LazyImport = () => Promise<any>;
Expand Down Expand Up @@ -604,6 +604,10 @@ async function render({
}

export function createReference({ lookupMap }: { lookupMap: ContentLookupMap }) {
// We're handling it like this to avoid needing an async schema. Not ideal, but should
// be safe because the store will already have been loaded by the time this is called.
let store: ImmutableDataStore | null = null;
globalDataStore.get().then((s) => (store = s));
return function reference(collection: string) {
return z
.union([
Expand All @@ -618,15 +622,22 @@ export function createReference({ lookupMap }: { lookupMap: ContentLookupMap })
}),
])
.transform(
async (
(
lookup:
| string
| { id: string; collection: string }
| { slug: string; collection: string },
ctx,
) => {
if (!store) {
ctx.addIssue({
code: ZodIssueCode.custom,
message: `**${ctx.path.join('.')}:** Reference to ${collection} could not be resolved: store not available.\nThis is an Astro bug, so please file an issue at https://github.com/withastro/astro/issues.`,
});
return;
}

const flattenedErrorPath = ctx.path.join('.');
const store = await globalDataStore.get();
const collectionIsInStore = store.hasCollection(collection);

if (typeof lookup === 'object') {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ const spacecraft = defineCollection({
publishedDate: z.coerce.date(),
tags: z.array(z.string()),
heroImage: image().optional(),
cat: reference('cats').optional(),
cat: reference('cats').default('siamese'),
something: z
.string()
.optional()
Expand Down

0 comments on commit 96c4b92

Please sign in to comment.