DEV Community

Nhan Nguyen
Nhan Nguyen

Posted on

Zod - TypeScript-first schema declaration and validation library #11

Image description

Transform Data from Within a Schema

Another useful feature of Zod is manipulating data from an API response after parsing.

We are going back to our Star Wars example:

import { z } from 'zod';

const StarWarsPerson = z.object({
  name: z.string(),
})

const StarWarsPeopleResults = z.object({
  results: z.array(StarWarsPerson),
})

export const fetchStarWarsPeople = async () => {
  const data = await fetch(
    'https://www.totaltypescript.com/swapi/people.json',
  ).then((res) => res.json());

  const parsedData = StarWarsPeopleResults.parse(data);

  return parsedData.results;
}
Enter fullscreen mode Exit fullscreen mode

We created StarWarsPeopleResults with a results array of StarWarsPerson schemas.

When we get the name of a StarWarsPerson from the API, it's their full name.

What we want to do is add a transformation to StarWarsPerson itself.

We need to take our base StarWarsPerson and add a transformation that will split the names on space to give us a nameAsArray

👉 Solution:

Here is what StarWarsPerson looked like before the transformation:

const StarWarsPerson = z.object({
  name: z.string(),
})
Enter fullscreen mode Exit fullscreen mode

When we parse the name in .object(), we are going to take the person we receive and transform it to add additional properties:

const StarWarsPerson = z
  .object({
    name: z.string(),
  })
  .transform((person) => ({
    ...person,
    nameAsArray: person.name.split(' '),
  }))
Enter fullscreen mode Exit fullscreen mode

Inside of the .transform(), person is the object from above that includes the name.

This is also where we add the nameAsArray property that satisfies the test.

This occurs at the StarWarsPerson level instead of inside the fetch function or elsewhere.


I hope you found it useful. Thanks for reading. 🙏
Let's get connected! You can find me on:

Top comments (0)