Search code examples
schemazodastrojs

Defining an Astro portfolio image gallery using Zod via a collection schema


I am creating a portfolio using Astro, each project is a JSON file following the same pattern. How do I define galleryImages key within each JSON file as a collection schema?

Example project JSON:

{
  "start": "September 2022",
  "galleryImages": [
    {
      "image": "images/web0.png"
    },
    {
      "image": "images/web1.png"
    }
  ],
  "subtitle": "iOS & Web Development",
  "title": "Yelp Shops",
  "project": "yelp",
  "icons": {
    "fa": [
      "FaReact",
      "FaSwift",
      "FaPython",
      "FaNode",
      "FaBootstrap",
      "FaGithub"
    ],
    "di": [
      "DiSwift"
    ]
  },
  "link": "https://next-yelp-shops.wl.r.appspot.com/",
  "end": {
    "date": "December 2022"
  },
  "image": "images/web0.png",
  "description": "Find the best restaurants near you! This iOS app and website fetches business data from Yelp, autodetects location using an IPInfo API, and provides address search via Google's geocoding API. Challenges during development were learning Swift, SwiftUI, and Google Cloud's App Engine and Cloud Functions. My favorite features to develop were realtime search suggestions, interface design, and developing the API with Python."
}

I understand the "image" key can be defined as so:

const project = defineCollection({
    type: 'data',
    schema: ({ image }) =>
        z.object({
            ...
            image: image(),
            ...
        }),
})

How should I define the galleryImages as a schema? I have not found any examples of content collections importing a list of images from a directory.


Solution

  • This should work:

    const project = defineCollection({
        type: 'data',
        schema: ({ image }) =>
            z.object({
                ...
                galleryImages: z.array(z.object({ image: image() })),
                ...
            }),
    })
    

    For the rest of the fields, you can use https://transform.tools/json-to-zod