As a newcomer to zod.js, I have found that the DataSchema
function is extremely helpful in verifying API data types and simplifying the API response easily.
However, I'm curious if there is a way to streamline the data transformation process for myExpectedData
directly within the zod component (without using the array map method)?
Below is a snippet of my code:
const apiUrl = 'https://api.jikan.moe/v4/top/anime';
const DataSchema = z.array(
z.object({
mal_id: z.number().nullable(),
images: z.object({
jpg: z.object({
image_url: z.string().nullable()
}
)
})
})
)
type DataSchema = z.infer < typeof DataSchema > ;
async function fetchTopAnime() {
try {
const response = await axios.get(apiUrl);
const rawData = response.data
const AnimeData = DataSchema.parse(rawData.data)
const myExpectedData = AnimeData.map((el) => {
return {
...el,
images: el.images.jpg.image_url
}
})
console.log(myExpectedData);
} catch (error) {
console.error(`Error fetching data: ${error}`);
}
}
fetchTopAnime();