📖 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
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
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
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
Hint
Pass an options object with cacheKeyFactory: customCacheKey to the @UseInterceptors decorator.
Practice
(1/5)
1. What is the main purpose of using @CacheKey() in a NestJS service?
easy
A. To set the time duration for cache expiration
B. To clear all cached data automatically
C. To define a custom name for the cached data key
D. To disable caching for a method
Solution
Step 1: Understand the role of @CacheKey()
This decorator is used to specify a custom key name for the cached data instead of using a default or generated key.
Step 2: Differentiate from other cache decorators
@CacheTTL() sets cache duration, clearing cache is manual or by other methods, and disabling cache is not done by @CacheKey().
Final Answer:
To define a custom name for the cached data key -> Option C
Quick Check:
Custom cache key = @CacheKey() [OK]
Hint: Remember: CacheKey sets the cache name, TTL sets time [OK]
Common Mistakes:
Confusing @CacheKey() with @CacheTTL()
Thinking @CacheKey() clears cache
Assuming @CacheKey() disables caching
2. Which of the following is the correct way to apply a custom cache key to a method in NestJS?
easy
A. @CacheKey = 'myKey'\nasync getData() { return data; }
B. @CacheTTL(300)\nasync getData() { return data; }
C. cacheKey('myKey')\nasync getData() { return data; }
D. @CacheKey('myKey')\nasync getData() { return data; }
Solution
Step 1: Identify correct decorator syntax
In NestJS, decorators are applied with @DecoratorName(parameters) syntax above the method.
A. Because TTL value should be a number, not a string
B. Because @CacheKey must come after @CacheTTL
C. Because async methods cannot use caching decorators
D. Because the cache key 'dataKey' is invalid
Solution
Step 1: Check the @CacheTTL parameter type
The TTL decorator expects a number (seconds), but '300' is a string, which causes it to fail.
Step 2: Verify other decorator rules
Decorator order does not affect TTL, async methods support caching, and 'dataKey' is a valid string key.
Final Answer:
Because TTL value should be a number, not a string -> Option A
Quick Check:
TTL must be number, not string [OK]
Hint: TTL needs number type, not quoted string [OK]
Common Mistakes:
Passing TTL as string instead of number
Thinking decorator order matters here
Assuming async disables caching
5. You want to cache user data with a dynamic key based on user ID. Which approach correctly creates a custom cache key in NestJS for method getUserById(id: string)?
hard
A. Use @CacheKey(() => `user_${id}`) above the method
B. Manually generate the key inside the method and use @CacheKey() without parameters
C. Use @CacheKey('user_' + id) directly above the method
D. Use @CacheKey() and pass the key as a method argument
Solution
Step 1: Understand dynamic cache keys in NestJS
To create a dynamic cache key, you can pass a function to @CacheKey() that returns the key string using method parameters.
Step 2: Evaluate each option
Use @CacheKey(() => `user_${id}`) above the method correctly uses a function returning a template string with id. Manually generate the key inside the method and use @CacheKey() without parameters is invalid because @CacheKey() needs the key at decoration time. Use @CacheKey('user_' + id) directly above the method tries to concatenate directly but id is not available at decoration time. Use @CacheKey() and pass the key as a method argument is invalid as @CacheKey() does not accept method arguments.
Final Answer:
Use @CacheKey(() => `user_${id}`) above the method -> Option A
Quick Check:
Dynamic key = function in @CacheKey() [OK]
Hint: Use function in @CacheKey() for dynamic keys [OK]
Common Mistakes:
Trying to use method parameters directly in decorator string
Assuming @CacheKey() accepts method arguments
Generating key inside method but not linking to cache
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.