#How to access the zod image objects outside of defineConfig function?

4 messages · Page 1 of 1 (latest)

latent hollow
#

I have a separate file to define my schema in /content/schema.ts. Then I import all the schemas into /content/config.ts and create my content collections. In some schemas I want to use the zod image object that Astro provides but I don't know how to access it outside the defineConfig function

...
const posts = defineConfig({
  type: "content",
  schema: ({image}) => PostSchema
});
stuck lindenBOT
#

Hi @latent hollow. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

You can access the image object from Astro by passing it as an argument to a function that returns your schema extension. This is demonstrated in the Astro documentation (https://starlight.astro.build/reference/frontmatter/#extend) where the image helper is used in a function that returns a Zod schema.

Here's an example of how you can do it:

// src/content/config.ts
import { defineCollection, z } from 'astro:content';
import { PostSchema } from './schema.ts';

export const collections = {
  posts: defineCollection({
    type: 'content',
    schema: ({ image }) => PostSchema({ image }),
  }),
};

And in your schema.ts file, you can define your PostSchema as a function that takes the image object as an argument:

// src/content/schema.ts
import { z } from 'astro:content';

export const PostSchema = ({ image }) => z.object({
  // ... your other fields
  cover: image(),
});

This way, you can use the image helper from Astro in your separate schema file.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@latent hollow kapa.ai is still learning and improving, please let us know how it did by reacting below