我正在使用nestjs,并希望编写一个带有缓存的返回Observable (rxjs)的函数。
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 user: string = this.cache.get(`user:${id}`); // but here is `Promise<string>` actually
if (user) {
return of(JSON.parse(user) as User);
}
return this.httpService.get<User>(url).pipe(
map(({ data }) => {
this.cache.set(`user:${id}`, JSON.stringify(data));
return data;
})
);
}
}逻辑非常简单,如果存在缓存,则返回缓存,否则调用api,保存到缓存,并返回结果。唯一的问题是缓存将返回一个承诺。怎样才能做到这一点?
发布于 2021-10-19 10:38:27
您可以使用RxJS from函数将承诺转换为可观察的承诺。在那里,您可以使用switchMap操作符+ of函数返回从缓存中获取的用户或进行HTTP调用。
fetchUser(id: string): Observable<User> {
const url = 'xxx';
const user$ = this.httpService.get<User>(url).pipe(
map(({ data }) => {
this.cache.set(`user:${id}`, JSON.stringify(data));
return data;
})
);
return from(this.cache.get(`user:${id}`)).pipe(
switchMap((user: string) =>
!!user ? of(user) : user$
)
);
}https://stackoverflow.com/questions/69629266
复制相似问题