我正在使用 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,保存到快取,回傳結果。唯一的問題是快取會回傳一個承諾。如何使這項作業?
uj5u.com熱心網友回復:
您可以使用 RxJSfrom函式將 Promise 轉換為 Observable。從那里,您可以使用switchMapoperator offunction 回傳從快取中獲取的用戶或進行 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://www.uj5u.com/net/326551.html
上一篇:帶有情感的MUIv5主題/mui
