Implement Transaction-Based API Using Redis

Learn how to execute transactions using the redis npm package and develop an API utilizing Redis transactions.

We’ve discussed and implemented a few APIs using the redis npm package and different types of data structures, such as strings, lists, and sets. Now we’re going to build an API that will help us purchase a product from a list of available products.

To make things simpler, we’ll assume that when the app starts, we have a balance of $5,000 stored in Redis as a key-value pair. We’ll use dummy data consisting of five products, each stored in a JSON file having an id, name, and price of the product.

Now that we have the products to purchase, we’ll create the API with the following functionality:

  • Check whether the product we’re trying to purchase is available in our dummy data.

  • Check whether the current balance is enough to purchase the product. If not, then return the response with an error message.

  • If we have enough funds, then we start our transaction by performing two steps:

    • Reduce and update the current balance by the product price. Store the updated current balance in Redis.

    • Store the product id in a list in Redis. We’ll name this list purchasedItems and insert the product id from the left side of the list.

Let’s now move ahead with the implementation.

Sample data of products available to purchase

Before moving on, let’s have a quick look at our dummy data consisting of product information, as shown below:

Get hands-on with 1200+ tech skills courses.