0
0
NestJSframework~30 mins

Why caching reduces response latency in NestJS - See It in Action

Choose your learning style9 modes available
Why caching reduces response latency
📖 Scenario: You are building a simple NestJS service that fetches user data. To make the service faster, you want to add caching so repeated requests for the same user do not take long.
🎯 Goal: Build a NestJS service that caches user data in memory to reduce response latency on repeated requests.
📋 What You'll Learn
Create a simple user data object
Add a cache variable to store fetched users
Implement a method to check cache before fetching user data
Return cached data if available, otherwise fetch and cache it
💡 Why This Matters
🌍 Real World
Caching is used in web services to speed up responses by storing data temporarily so repeated requests are faster.
💼 Career
Understanding caching helps backend developers optimize APIs and improve user experience by reducing wait times.
Progress0 / 4 steps
1
Create initial user data object
Create a constant called users that is an object with these exact entries: 1: { id: 1, name: 'Alice' }, 2: { id: 2, name: 'Bob' }, 3: { id: 3, name: 'Charlie' }.
NestJS
Need a hint?

Use a constant object named users with keys 1, 2, and 3 each holding an object with id and name.

2
Add cache storage variable
Add a variable called cache and set it to an empty object {} to store cached user data.
NestJS
Need a hint?

Use const cache = {} to create an empty object for caching.

3
Implement caching logic in getUser function
Write a function called getUser that takes id as a parameter. Inside, first check if cache[id] exists. If yes, return cache[id]. Otherwise, get the user from users[id], store it in cache[id], then return it.
NestJS
Need a hint?

Use an if statement to check cache[id]. Return cached data if found. Otherwise, get from users, cache it, then return.

4
Export getUser function for use in NestJS service
Add export before the function getUser declaration to make it available outside this module.
NestJS
Need a hint?

Add export before the function to share it with other files.