0
0
NestJSframework~3 mins

Why Cache decorators in NestJS? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could speed up your app with just one simple tag above your functions?

The Scenario

Imagine you have a web app that fetches user data from a database every time someone visits their profile page.

Each visit triggers the same slow database query again and again.

The Problem

Manually adding caching means writing extra code everywhere to check if data is already saved.

This makes your code messy, hard to maintain, and easy to forget.

Also, you risk serving outdated data or missing cache updates.

The Solution

Cache decorators let you add caching with a simple tag above your functions.

This keeps your code clean and automatically stores and retrieves data from cache.

You don't have to write repetitive cache logic yourself.

Before vs After
Before
async getUser(id) {
  const cached = await cache.get(id);
  if (cached) return cached;
  const user = await db.findUser(id);
  await cache.set(id, user);
  return user;
}
After
@Cacheable()
async getUser(id) {
  return await db.findUser(id);
}
What It Enables

You can easily speed up your app by caching results without cluttering your code.

Real Life Example

When many users view the same product page, cache decorators serve the stored product info instantly instead of querying the database each time.

Key Takeaways

Manual caching adds repetitive, error-prone code.

Cache decorators simplify caching by adding it declaratively.

This keeps code clean and improves app speed automatically.