Issue
Guys I have this code that saves my products in cache, I would like to better understand how it works,
getItemById(id) {
// return this.http.get(`${environment.API_URL}item/getById/${id}`);
return
this.cacheS.getOrSetCache(`StoreService_getItemById_${id}_${this.layout.emp.id}`,
this.http.get(`${environment.API_URL}item/getById/${id}`), 300000);
}
getOrSetCache(key: string, request: Observable<any>, msToExpire = 300000): Observable<any> {
let cache: any = {};
cache = JSON.parse(localStorage.getItem(key));
return (cache?.data && (cache?.exp > Date.now())) ?
of(cache.data) :
request.pipe(tap(v => {
localStorage.setItem(key, JSON.stringify({data: v, exp: (Date.now() + msToExpire)}));
}));
}
My question is more about how it manages to save in cache with an expiration date, and when the date expires, make the request again
This code works, but I couldn't understand how, is there any other better way to cache with expiration date?
Solution
when you call getOrSetCache
, you pass msToExpire
to arguments. Date.now()
returns the current time. If this element is not in the cache, you make a request and after receive data, you save in to ls, and set time to expire as date.now() + msToExpire
. And in the next call of this function you compare exp
from your save element with current time Date.now()
.
For example the cache is empty, and you call getOrSetCache
at 17:00. And let's imagine that the msToExpire
= 30 min. Since the cache is empty, we make a request and save the data to the cache exp: (Date.now() + msToExpire)
= 17:00 + 30 min = 17:30. Now, if call your function at 17:20 o'clock, this condition cache?.data && (cache?.exp > Date.now()))
returns true, cause 17:30 > 17:20 and you will receive data from cache. But if you call it at 17:31, condition will return false, and it make new request and rewrite data in cache with new timestamp
Answered By - Belouccio
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.