Consider a NestJS service that caches a value using CacheModule with default settings. What will be the behavior when retrieving a cached value immediately after setting it?
import { CacheModule, Injectable, Module, Inject, CACHE_MANAGER } from '@nestjs/common'; import { Cache } from 'cache-manager'; @Injectable() class SampleService { constructor(@Inject(CACHE_MANAGER) private cacheManager: Cache) {} async cacheValue() { await this.cacheManager.set('key', 'value'); return await this.cacheManager.get('key'); } } @Module({ imports: [CacheModule.register()], providers: [SampleService], }) export class AppModule {}
Think about how the default in-memory cache store works in NestJS CacheModule.
By default, CacheModule uses an in-memory store that immediately stores and retrieves data synchronously. So, setting and getting a value right after works as expected.
Choose the correct way to configure CacheModule with a time-to-live (TTL) of 5 seconds.
Check the official CacheModule options for TTL property name and units.
The correct option uses 'ttl' in seconds. Option B uses milliseconds which is incorrect. Options C and D use invalid property names.
Examine the following CacheModule setup. Why will it cause a runtime error?
import { CacheModule } from '@nestjs/common'; CacheModule.register({ store: 'redis', host: 'localhost', port: 6379 });
Think about how to properly configure a Redis cache store in NestJS CacheModule.
The 'store' option expects a function or a store instance, not a string. Using 'store: "redis"' causes a runtime error. You must import and pass the Redis store function.
Given this NestJS service using CacheModule, what will be the value of cachedData after fetchData() is called twice in a row?
import { Injectable, Inject, CACHE_MANAGER } from '@nestjs/common'; import { Cache } from 'cache-manager'; @Injectable() class DataService { constructor(@Inject(CACHE_MANAGER) private cacheManager: Cache) {} async fetchData() { const cached = await this.cacheManager.get('data'); if (cached) return cached; const data = 'fresh data'; await this.cacheManager.set('data', data, { ttl: 1 }); return data; } } // Assume fetchData() is called twice within 2 seconds.
Consider the TTL of 1 second and the timing of calls.
The TTL is 1 second, so if the second call happens after 1 second, the cache expired and 'fresh data' is returned again. If calls happen within 1 second, second call would return cached data.
When configuring CacheModule globally in a NestJS app, which statement is correct?
Think about the purpose of the isGlobal option in NestJS modules.
Setting isGlobal: true in CacheModule.register() makes the cache service available app-wide without needing to import CacheModule in every module.