Using the Expand Operator to Fetch Recursively
The last key feature we need to implement is to actually make use of the
gifsRequired
value (i.e. how many gifs we should display per request), but
there is some hidden complexity here. Let’s consider how we would actually
implement this.
At the moment, we fetch GIFs from this URL:
`https://www.reddit.com/r/${subreddit}/hot/.json?limit=100` +
(after ? `&after=${after}` : '')
Notice that we supply a limit=100
to tell the Reddit API how many posts we
want to return. It then might seem sensible to implement a gifsRequired
limit
like this:
`https://www.reddit.com/r/${subreddit}/hot/.json?limit=${gifsRequired}` +
(after ? `&after=${after}` : '')
However, that won’t quite work for us. At the moment this is what we do:
- Fetch
100
posts from Reddit - Filter those to only include valid GIFs
- Display those GIFs
The actual number of GIFs we end up displaying in our application won’t
necessarily be 100
or whatever limit we supply, it could be anywhere from 0
to 100
. This is where things get tricky.
We will continue to discuss this as we implement the solution, but the general
idea that we want to implement is (assuming an initial gifsRequired
value of
20
):
- Fetch
100
posts from Reddit - Filter those for valid GIFs
- If there are less than
20
valid GIFs, keep hitting the API until we do have20
valid GIFs
The tricky part is that last step, and it is where the expand
operator will
become extremely useful.