Generators help fetch and process data from APIs more granular, improving code modularity and user-friendliness. This tutorial teaches you how to use TypeScript generators for cleaner programming using a real-world example.
The schema for the API response is defined using Zod, which ensures that the fetched data matches the expected structure. This is useful for validating the response:
Pay attention to the optional next_url. It serves as our indicator of whether an API endpoint contains additional results. We will keep fetching more data as long as there is a URL for the next batches, but once it becomes undefined, we will cease querying the endpoint.
In the traditional approach, we use an asynchronous function in TypeScript that handles the fetching, parsing, and looping through the paginated results:
The fetchData function holds the business logic to query data, while dealing with the next URL is tackled outside this function. As a result, the executing code must be aware of the internal details of the endpoint. This leads to poor encapsulation and makes it harder to manage for more complex asynchronous flows.
Generator Function Approach
In the generator approach, we create an async generator function to yield the results, making it easier to handle each chunk of data separately:
The generator also separates data fetching logic (keeping track of the url) from the iteration logic (for await...of loop). This approach makes the code more modular and user-friendly, as the consuming code no longer needs to update the next_url.
It's even possible to return each response individually instead of yielding parsed data in batches of 200. This way, each call to yield will provide a single result item:
Be aware that you need to adjust the returned result type accordingly:
Final Result
Below is the complete TypeScript code that defines an async generator function to fetch data from a REST API, parses the response, and yields each individual result item. This approach provides fine-grained control over processing each piece of data: