Search⌘ K
AI Features

Execute Set Operations with Node.js

Explore how to use Redis sets in Node.js by building an API that fetches and caches random programming and pun jokes. Learn to store unique jokes in Redis sets, manage cache expiration, and reduce external API calls by retrieving jokes from the cache when available.

To recap, we've used strings and lists in Redis and created simple APIs to understand how these work. Let’s now begin with sets. As already discussed, sets store distinct elements only, which makes them an important data structure to store data. We’ll build an API to fetch random jokes related to two categories:

  • Programming

  • PunsA joke that exploits multiple meanings or similar-sounding words to create a humorous effect

We’ll follow the steps mentioned below in order to implement the functionality:

  1. We fetch jokes based on the category provided by the user, by accessing a third-party API.

  2. We then store the jokes in a set corresponding to their category.

  3. As soon as we have five or more jokes in our set, we fetch them from Redis and set an expiration time of 40 seconds for that set. For example, if the set containing the programming jokes exceeds five, then we always fetch the programming jokes from the set instead of making another third-party API request for subsequent calls. This Redis fetch happens until the key doesn’t expire (i.e., after 40 seconds).

Let’s now start the implementation.

Understand the jokes API response

Before moving on, ...