Zod - TypeScript-first schema declaration and validation library #11
Nhan Nguyen
Posted on December 16, 2023
✨ 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;
}
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(),
})
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(' '),
}))
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:
- Medium: https://medium.com/@nhannguyendevjs/
- Dev: https://dev.to/nhannguyendevjs/
- Hashnode: https://nhannguyen.hashnode.dev/
- Linkedin: https://www.linkedin.com/in/nhannguyendevjs/
- X (formerly Twitter): https://twitter.com/nhannguyendevjs/
Posted on December 16, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
December 28, 2023
December 17, 2023