0
0
NestJSframework~30 mins

Cache decorators in NestJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Cache Decorators in NestJS
📖 Scenario: You are building a simple NestJS service that fetches user data. To improve performance, you want to cache the results of the data fetching method.
🎯 Goal: Build a NestJS service that uses the @Cacheable() decorator to cache the result of a method that returns user information.
📋 What You'll Learn
Create a NestJS service class named UserService.
Add a method getUser() that returns a user object with id and name.
Add a cache configuration variable cacheTTL set to 30 seconds.
Use the @Cacheable() decorator on getUser() with the ttl set to cacheTTL.
Ensure the service is ready to be used in a NestJS module.
💡 Why This Matters
🌍 Real World
Caching is used in real-world applications to speed up repeated data fetching and reduce load on databases or APIs.
💼 Career
Understanding cache decorators in NestJS is important for backend developers to optimize performance and scalability of server applications.
Progress0 / 4 steps
1
Create the UserService class with getUser method
Create a NestJS service class called UserService with a method getUser() that returns an object { id: 1, name: 'Alice' }.
NestJS
Need a hint?

Define a class named UserService and add a method getUser() that returns the user object.

2
Add cacheTTL configuration variable
Inside the UserService class, add a variable cacheTTL and set it to 30 to represent 30 seconds.
NestJS
Need a hint?

Add a class property cacheTTL and assign it the number 30.

3
Import and apply @Cacheable decorator with ttl
Import @Cacheable from @nestjs/cache-manager and apply it as a decorator on the getUser() method. Set the decorator option ttl to the class variable cacheTTL.
NestJS
Need a hint?

Import @Cacheable and decorate getUser() with @Cacheable({ ttl: 30 }). Use the number 30 directly for simplicity.

4
Export UserService for module use
Add export keyword before the UserService class declaration to make it available for import in other modules.
NestJS
Need a hint?

Make sure the class declaration starts with export class UserService.