Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Exploring Caching with NestJS and Redis

Posted on Jun 18 In this tutorial, we will be exploring the world of caching, with Nestjs and Redis. Before we dive head-in into Redis, NestJS provides its in-memory cache, that can serve as an in-memory data store, but can easily be switched to high-performant caching system like Redis.To get started, you can fork this github repository. Please, ensure you select the base branch as it contains the base application setup for this tutorial. After setting up you base application setup, you can proceed to install the cache-manager package and its dependencies.In case you are familiar with NestJS in-memory cache implementation, there is a current update to the cache-manager, we are using version 5 throughout this tutorial. As opposed to the version 4, the version 5 now provides ttl (Time-To-Live) in milliseconds instead. We have to do the conversion before parsing it to NestJS as NestJs does not do the conversion for us.To enable caching, we have to import the CacheModule into the app.module.ts file.Our app.module.ts file should look like the one above.We are also going to import it into our Contact module. With any feature module in NestJS, there is a need to import the cache-manager into them respectively. If you have a module that does not require caching, then it is not a necessity. Our contact.module.ts should be similar to the code block below:A good alternative, is setting the isGlobal option for the CacheModule.register(). This option can be considered if you need caching availability across all your modules.Let's proceed to our Contact controller to modify some of our existing endpoints. For the @Get('contacts/:contactId') endpoint, we want to check if our response is in cache, before calling the method. This is achievable using the @useInterceptors decorator:Our getContact method should be similar to this below:Things to note: Implementing an override, our getContact will be:Now RedisAccording to the official Redis website, “Redis is an open source, in-memory data structure store used as a database, cache, message broker, and streaming engine.”Polled from RedisTo use Redis instead of the in-memory cache, we will need to install the relevant package:This package is a nestjs wrapper for passing configurations to the node_redis package. We can now change some config of our app.module.ts to use Redis.Note: cache-manager-redis-store is been discontinued to allow for the package we just installed. This package we installed is been tracked directly by the Nestjs team.This has allowed us to add new config options like: redisStore: represent the node-cache-manager-redis-yet we just installed host and port are set to their defaultIncase you don't have Redis server running yet, you can look up various installation methods for your operating system or consider the Docker optionHeading to our contact.controller page, we can configure our getContact method, to check if we have a cached data yet before querying the main database. If it exists, we want to return it else we want to set it after querying the DB.Our getContact should be similar to this:Let's take a brief look at the code block above:The cachedData variable is checking if we have an existing cache, if it exists, you can check your logger and you'll get Getting data from cache.If our data does not exist in cache, the codeblock above helps us to set in cache.Your cached data will now persist to your local Redis server.You can test out the endpoint and you should get a result similar to my output in your logger:You can confirm in your GUI of choice (I like TablePlus) by sending a request to your NestJS app where caching is used and you'll see the data is now persisted:Congratulations, you have just added a Redis cache to your NestJS application.In this tutorial, we have successfully added a Redis cache to our Nestjs application. Redis enables lower application latency and very high data access. This allows software engineers to build highly performant, reliable solutions.And that's it! What do you think? Let me know in the comments below.Templates let you quickly answer FAQs or store snippets for re-use. Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink. Hide child comments as well Confirm For further actions, you may consider blocking this person and/or reporting abuse Phil Leggetter - Apr 27 Neil Chen - Apr 17 Akram Mahmoud - Apr 28 Jeff Lindsay - Apr 27 Once suspended, fikkyman1 will not be able to comment or publish posts until their suspension is removed. Once unsuspended, fikkyman1 will be able to comment and publish posts again. Once unpublished, all posts by fikkyman1 will become hidden and only accessible to themselves. If fikkyman1 is not suspended, they can still re-publish their posts from their dashboard. Note: Once unpublished, this post will become invisible to the public and only accessible to Sagacité. They can still re-publish the post if they are not suspended. Thanks for keeping DEV Community safe. Here is what you can do to flag fikkyman1: fikkyman1 consistently posts content that violates DEV Community's code of conduct because it is harassing, offensive or spammy. Unflagging fikkyman1 will restore default visibility to their posts. DEV Community — A constructive and inclusive social network for software developers. With you every step of your journey. Built on Forem — the open source software that powers DEV and other inclusive communities.Made with love and Ruby on Rails. DEV Community © 2016 - 2023. We're a place where coders share, stay up-to-date and grow their careers.



This post first appeared on VedVyas Articles, please read the originial post: here

Share the post

Exploring Caching with NestJS and Redis

×

Subscribe to Vedvyas Articles

Get updates delivered right to your inbox!

Thank you for your subscription

×