Zod Tutorial (10 exercises)

Transform Data from Within a Schema

As a reminder, here's what StarWarsPerson looked like before the transformation:

Adding the Transformation

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

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.

All of this is taking place at the StarWarsPerson level instead of inside of the fetch function or elsewhere.

Another Example

Zod's transform API works for any of its primitives.

For example, we can transform the name inside of the z.object:

Now we'll end up with a name of Awesome Luke Skywalker and nameAsArray will be ['Awesome', 'Luke', 'Skywalker'].

Transforms act at the lowest level, can be combined, and are just incredibly useful.


Matt Pocock: The big change we've made here is we've started using the transform API from Zod, which is super duper cool. What it does is it says when we parse this name, what we're going to do is take that person that we receive and then transform it. We can add new properties to it.

What we've got here is nameAsArray: person.name.split("-"). What this is doing is it's taking the name property that we parse here. Then, it's splitting it by space. What we end up with is an array of those persons' names. What we get...I'm just console.logging it down here, in the same way I did before.

We end up with an array of name 'Luke Skywalker' and nameAsArray 'Luke' "Skywalker'. It doesn't work for C-3P0 but it does work for Darth Vader, Leia Organa, Owen Lars, etc. I don't know who Owen Lars is.

This transform API, you can see it's actually working just at the StarWarsPerson level. This doesn't just work for objects. It can actually work for arrays, too, or work for any Zod primative. We can transform this and we can say...We've got the name. Let's just say we go Awesome and ${name}.

What this is going to do now is this is going to prepend Awesome onto all of the results. We've got Awesome Biggs Darklighter. Awesome Beru Whitesun Lars. Who are these people?

You get the idea. Transform is an incredibly useful API because it acts at the lowest level and allows you to...You can obviously do multiple transforms, as well, if you really want. It's an incredibly cool API.