Transform Data from Within a Schema
Another useful feature of Zod is manipulating data from an API response after parsing.
To see this in action, we're going back to our Star Wars example.
Recall that we created
StarWarsPeopleResults with a
results array of
0:00 We're going back to our fetch example for a minute here because we want to be able to do something interesting, which is, we want to take the base StarWarsPerson that we've got here, and then what we're going to do is fetch all of these people. We actually want to do some manipulation of the data after we've parsed it.
0:21 What we need here and what our tests are expecting, is that the first thing that comes out of this StarWarsPeople thing is going to be Luke Skywalker, and the name is already Luke Skywalker. If we refactor this slightly, let's say, const results equals this, and just grab this, and we're going to say, expect results to equal this.
0:45 Our tests are still going to fail in the same way, but it means that we can just console.log (results). What that's going to do is going to show us all of the data that's coming back here. What we're getting is Luke Skywalker, C-3PO, etc. We're getting a similar result to what we got earlier, which is the results are the z.array(StarWarsPerson).
1:04 We want to find a way on StarWarsPerson itself, transform it, so we can add a new property which is named as array which is the name split with the space here. This is a more challenging one, but it's such a cool and useful pattern that I couldn't help but include it.