0
0
NestJSframework~30 mins

Custom cache keys in NestJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Custom Cache Keys in NestJS
📖 Scenario: You are building a NestJS service that caches user data. To improve cache management, you want to create custom cache keys based on user IDs.
🎯 Goal: Build a NestJS service that uses a custom cache key function to store and retrieve cached user data.
📋 What You'll Learn
Create a NestJS service with a method to get user data.
Add a custom cache key function that uses the user ID.
Use the cache interceptor with the custom cache key function.
Ensure the cache key is unique per user ID.
💡 Why This Matters
🌍 Real World
Custom cache keys help store and retrieve cached data uniquely, improving performance and reducing redundant data fetching in web applications.
💼 Career
Understanding custom cache keys in NestJS is useful for backend developers working on scalable and efficient server-side applications.
Progress0 / 4 steps
1
Create a NestJS service with a method to get user data
Create a NestJS service class called UserService with a method getUserData that takes a parameter userId and returns a string `User data for ${userId}`.
NestJS
Need a hint?

Define a class with a method that returns a template string using the userId parameter.

2
Add a custom cache key function using the user ID
Create a function called customCacheKey that takes context as a parameter and returns a string cache key in the format `user-cache-${userId}`. Extract userId from context.args[0].
NestJS
Need a hint?

Use context.args[0] to get the userId and return a string with that ID.

3
Use the cache interceptor with the custom cache key function
In a NestJS controller class called UserController, create a method getUser that takes userId as a parameter and calls userService.getUserData(userId). Use the @UseInterceptors(CacheInterceptor) decorator with options to set cacheKeyFactory to customCacheKey. Inject UserService in the constructor.
NestJS
Need a hint?

Use @Controller, inject UserService, and decorate getUser with @UseInterceptors(CacheInterceptor).

4
Configure the cache interceptor to use the custom cache key factory
Modify the @UseInterceptors(CacheInterceptor) decorator on UserController to pass options with cacheKeyFactory set to customCacheKey.
NestJS
Need a hint?

Pass an options object with cacheKeyFactory: customCacheKey to the @UseInterceptors decorator.