I am a user of nestjs and I am currently trying to create a function that returns an Observable (rxjs) with cache functionality.
import { HttpService } from '@nestjs/axios';
import { CACHE_MANAGER, Inject, Injectable } from '@nestjs/common';
import { Cache } from 'cache-manager';
import { map, of, Observable } from 'rxjs';
interface User {
id: string;
// ...
}
@Injectable()
export class Service {
constructor(
@Inject(CACHE_MANAGER) protected cache: Cache,
protected readonly httpService: HttpService,
) {}
fetchUser = (id: string): Observable<User> {
const url = 'xxx';
const userFromCache: string = this.cache.get(`user:${id}`); // however, it actually returns `Promise<string>`
if (userFromCache) {
return of(JSON.parse(userFromCache) as User);
}
return this.httpService.get<User>(url).pipe(
map(({ data }) => {
this.cache.set(`user:${id}`, JSON.stringify(data));
return data;
})
);
}
}
The concept behind this logic is straightforward - check if there is cached data, if so return it, otherwise make an API call, store the result in the cache, and return the data. The only hurdle faced is that the cache method returns a promise. Is there a way to overcome this obstacle?