Skip to content

Commit a10002a

Browse files
fix(firebase): cache lru to transfer state
1 parent cda82b5 commit a10002a

File tree

2 files changed

+19
-1
lines changed

2 files changed

+19
-1
lines changed

src/modules/firebase/common.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
import { makeStateKey } from '@angular/platform-browser'
2+
3+
export function makeRtDbStateTransferKey(fullUrl: string) {
4+
return makeStateKey<string>(`G.${fullUrl}`)
5+
}

src/modules/firebase/server.firebase.rtdb.service.ts

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@ import {
1010
import { Observable, of } from 'rxjs'
1111
import { IUniversalRtdbService } from './rtdb.interface'
1212
import { createHash } from 'crypto'
13+
import { TransferState, StateKey } from '@angular/platform-browser'
14+
import { makeRtDbStateTransferKey } from './common'
1315

1416
function sha256(data: string) {
1517
return createHash('sha256')
@@ -47,13 +49,23 @@ function attemptToGetCachedValue<T>(key: string, lru?: LruCache) {
4749
return lru && lru.get<T>(sha256(key))
4850
}
4951

52+
function writeLruCacheToTransferState<T>(
53+
ts: TransferState,
54+
key: StateKey<string>
55+
) {
56+
return function(val: T) {
57+
ts.set(key, val)
58+
}
59+
}
60+
5061
// tslint:disable:no-this
5162
// tslint:disable-next-line:no-class
5263
@Injectable()
5364
export class ServerUniversalRtDbService implements IUniversalRtdbService {
5465
constructor(
5566
private http: HttpClient,
5667
private afdb: AngularFireDatabase,
68+
private ts: TransferState,
5769
@Optional()
5870
@Inject(FIREBASE_USER_AUTH_TOKEN)
5971
private authToken?: string,
@@ -67,13 +79,14 @@ export class ServerUniversalRtDbService implements IUniversalRtdbService {
6779
const params = getParams({ auth: this.authToken })
6880
const cacheKey = getFullUrl(url, params)
6981
const cachedValue = attemptToGetCachedValue<T>(cacheKey, this.lru)
82+
const tsKey = makeRtDbStateTransferKey(url)
7083

7184
const baseObs = this.authToken
7285
? this.http.get<T>(url, { params })
7386
: this.http.get<T>(url)
7487

7588
return cachedValue
76-
? of(cachedValue)
89+
? of(cachedValue).pipe(tap(writeLruCacheToTransferState(this.ts, tsKey)))
7790
: baseObs.pipe(
7891
take(1),
7992
tap(attemptToCacheInLru(cacheKey, this.lru)),

0 commit comments

Comments
 (0)