Execute Set Operations with Node.js

Learn how to execute set commands using the redis npm package, and develop an API utilizing Redis caching.

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, let’s first hit the third-party API to fetch random jokes for the Programming category:

Get hands-on with 1400+ tech skills courses.